From ef1a68b5e3ed29c60bae450c062911a7ab8cd67a Mon Sep 17 00:00:00 2001 From: Ara Date: Thu, 3 Jul 2025 07:38:42 +0530 Subject: [PATCH 01/43] Adding a troubleshooting guide for terminal problems (#4592) --- docs/docs.json | 4 + .../at-mentions/terminal-mentions.mdx | 13 + .../terminal-integration.mdx | 21 +- .../terminal-integration-guide.mdx | 399 ++++++++++++++++++ docs/troubleshooting/terminal-quick-fixes.mdx | 51 +++ .../sections/TerminalSettingsSection.tsx | 59 ++- 6 files changed, 522 insertions(+), 25 deletions(-) create mode 100644 docs/troubleshooting/terminal-integration-guide.mdx create mode 100644 docs/troubleshooting/terminal-quick-fixes.mdx diff --git a/docs/docs.json b/docs/docs.json index ef40b1df..394ed2cf 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -170,6 +170,10 @@ "running-models-locally/ollama" ] }, + { + "group": "Troubleshooting", + "pages": ["troubleshooting/terminal-quick-fixes", "troubleshooting/terminal-integration-guide"] + }, { "group": "More Info", "pages": ["more-info/telemetry"] diff --git a/docs/features/at-mentions/terminal-mentions.mdx b/docs/features/at-mentions/terminal-mentions.mdx index b80b4d13..d73c32da 100644 --- a/docs/features/at-mentions/terminal-mentions.mdx +++ b/docs/features/at-mentions/terminal-mentions.mdx @@ -58,3 +58,16 @@ When you use the terminal mention in your message, here's what happens behind th 6. The AI can now "see" the complete terminal output with all formatting preserved This process happens automatically whenever you use the terminal mention, giving the AI access to your command results, error messages, and other terminal output without you having to copy it manually. + +## Troubleshooting Terminal Issues + +If you're experiencing issues with terminal mentions or terminal integration in general (such as "Shell Integration Unavailable" or commands not showing output), please refer to our comprehensive [Terminal Integration Troubleshooting Guide](/troubleshooting/terminal-integration-guide). + +Common issues include: + +- Terminal mentions not capturing output +- "Shell Integration Unavailable" messages in Cline chat +- Commands executing but output not visible to Cline +- Terminal integration working inconsistently + +The troubleshooting guide provides platform-specific solutions and detailed configuration steps to resolve these issues. diff --git a/docs/features/commands-and-shortcuts/terminal-integration.mdx b/docs/features/commands-and-shortcuts/terminal-integration.mdx index a453f5f7..bc6bf1aa 100644 --- a/docs/features/commands-and-shortcuts/terminal-integration.mdx +++ b/docs/features/commands-and-shortcuts/terminal-integration.mdx @@ -74,8 +74,25 @@ This approach ensures that all terminal output, including colors and formatting, - **Select specific output when needed**: By default, the integration captures all terminal content, but you can also select specific lines before right-clicking to focus on just the relevant output. -- **Combine with file mentions**: After sending terminal output to Cline, you can enhance your question by mentioning relevant files using the @ mentions feature. +- **Combine terminal outputs with file mentions**: After sending terminal output to Cline, you can enhance your question by mentioning relevant files using the @ mentions feature. -- **Use for build and test output**: Terminal integration is particularly useful for understanding complex build errors or test failures that span multiple lines. +- **Contextualize build & test outputs with the terminal**: Terminal integration is particularly useful for understanding complex build errors or test failures that span multiple lines. Next time you're staring at a cryptic error message in your terminal, try using Cline's terminal integration instead of copying and pasting. You'll get more accurate help because Cline can see the complete terminal context with proper formatting. + +## Troubleshooting Terminal Issues + +If you're experiencing issues with terminal integration, such as "Shell Integration Unavailable" or commands not showing output, please refer to our comprehensive [Terminal Integration Troubleshooting Guide](/troubleshooting/terminal-integration-guide). + +The troubleshooting guide covers: + +- Common terminal integration issues and quick fixes +- Platform-specific solutions for Windows, macOS, and Linux +- Shell-specific configurations for zsh, bash, PowerShell, and more +- Advanced debugging techniques +- Terminal settings optimization + + + **Quick Fix**: Most terminal issues can be resolved by switching to bash in the Cline settings and increasing the shell + integration timeout to 10 seconds. + diff --git a/docs/troubleshooting/terminal-integration-guide.mdx b/docs/troubleshooting/terminal-integration-guide.mdx new file mode 100644 index 00000000..99a64154 --- /dev/null +++ b/docs/troubleshooting/terminal-integration-guide.mdx @@ -0,0 +1,399 @@ +--- +title: "Terminal Integration Troubleshooting Guide" +sidebarTitle: "Terminal Troubleshooting" +description: "Complete guide to resolving terminal integration issues in Cline" +--- + +This guide helps you resolve terminal integration issues in Cline. Terminal integration is crucial for Cline to execute commands and read their output, enabling it to understand errors, test results, and command responses. + + + If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings, under "Terminal Settings" + + This resolves most terminal integration problems. + + + +## Quick Diagnosis Flowchart + +Follow this flowchart to quickly identify your issue: + +```mermaid +graph TD + A[Terminal Issue] --> B{Can Cline execute commands?} + B -->|No| C[Shell Integration Unavailable] + B -->|Yes| D{Can Cline see the output?} + D -->|No| E[Output Capture Failed] + D -->|Yes| F{Is the output corrupted?} + F -->|Yes| G[Character Filtering Issue] + F -->|No| H{Does the command hang?} + H -->|Yes| I[Long-Running Command Issue] + H -->|No| J[Check Terminal Settings] + + C --> K[Try Solution 1] + E --> L[Try Solution 2] + G --> M[Try Solution 3] + I --> N[Try Solution 4] + + style A fill:#f9f,stroke:#333,stroke-width:2px + style K fill:#9f9,stroke:#333,stroke-width:2px + style L fill:#9f9,stroke:#333,stroke-width:2px + style M fill:#9f9,stroke:#333,stroke-width:2px + style N fill:#9f9,stroke:#333,stroke-width:2px +``` + +## Common Issues & Quick Solutions + +### 1. Shell Integration Unavailable + +**Symptoms:** + +- Message: "Shell Integration Unavailable" +- Commands execute but Cline can't read output +- Terminal works fine manually but not with Cline + +**Quick Solutions:** + +#### macOS + +- **Switch to bash** + + 1. Go to Cline Settings + 2. Left-Click the **"Terminal Settings"** tab + 3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down menu + +- **Disable Oh-My-Zsh temporarily**: + + 1. If using zsh, enter `mv ~/.zshrc ~/.zshrc.backup` into the terminal + 2. Restart VSCode + +- **Set environment**: + 1.a For Zsh users, use one of the following Zsh commands to edit your shell profile: + + - `nano ~/.zshrc` + - `vim ~/.zshrc` + - `code ~/.zshrc` + + 1.b For Bash users + + - nano ~/.bash_profile + + 2. Add the following to your shell config: `export TERM=xterm-256color` + 3. Save your configuration + +#### Windows + +- **Use PowerShell 7** + + 1. Install from Microsoft Store + 2. Go to Cline Settings + 3. Left-Click the **"Terminal Settings"** tab + 4. Navigate to **"Default Terminal Profile"** and select **"PowerShell 7"** from the drop-down menu + +- **Disable Windows ConPTY** + + 1. Navigate to your VSCode Settings + 2. Enter "Integrated: Windows Enable Conpty" into the Settings searchbar + 3. Uncheck the option + +- **Try Command Prompt** + 1. Go to Cline Settings + 2. Left-Click the **"Terminal Settings"** tab + 3. Navigate to **"Default Terminal Profile"** and select **"Command Prompt"** from the drop-down menu + +#### Linux + +- **Use bash** + + 1. Go to Cline Settings + 2. Left-Click the **"Terminal Settings"** tab + 3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down menu + +- **Check permissions** + + 1. Ensure VSCode has terminal access permissions + +- **Disable custom prompts** + 1. Comment out prompt customizations in `.bashrc` + +### 2. Command Output Not Visible + +**Symptoms:** + +- Cline states in chat: "[Command is running but producing no output]" +- Commands complete but Cline doesn't see results +- Commands work sometimes but not consistently + +**Solutions:** + +- **Increase Shell Integration Timeout** + + 1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window + 2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column + 3. Navigate to "Shell integration timeout (seconds)" and enter **"10"** into the text field + +- **Disable Terminal Reuse** + + 1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window + 2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column + 3. Look for **"Enable aggressive terminal reuse"**, and **uncheck** this option + +- **Check for interfering extensions** + 1. Disable other terminal-related VSCode extensions + +### 3. Character Filtering Issues + +**Symptoms:** + +- Commas missing from output (JSON appears corrupted) +- Special characters stripped from terminal output +- Syntax errors that don't appear when running manually + +**Solution:** +This is a known bug in output processing. Workarounds: + +- Recommend AI to use file output instead + 1. Tell Cline in chat or Cline rules, to use `command > output.txt` before reading the file/s + + + This family of issues is only partially solved in the latest Cline versions, so if you still face this, create a GitHub issue + if it is a persistent problem. + + +### 4. Long-Running Commands & Progress Bars + +**Symptoms:** + +- Docker builds never complete in Cline +- Progress bars consume thousands of tokens +- The Cline button "Proceed while running" doesn't work properly in chat + + + This family of issues has been solved in latest Cline versions but if you still face any issues, then create a GitHub issue + for this. + + +## Terminal Settings Explained + +Access these in Cline by clicking the settings icon, and navigating to the "Terminal Settings" section: + +### Default Terminal Profile + +- **What it does**: Selects which shell Cline uses for commands +- **When to change**: If experiencing shell integration issues with your default shell +- **Recommended**: - macOS: bash (if zsh has issues) - Windows: PowerShell 7 - Linux: bash + +### Shell Integration Timeout + +- **What it does**: How long Cline waits for the terminal to be ready +- **Default**: 4 seconds +- **When to increase**: + - Slow shell startup (heavy .zshrc/.bashrc) + - WSL environments + - SSH connections +- **Recommended**: - Start with 10 seconds if having issues + +### Enable Aggressive Terminal Reuse + +- **What it does**: Reuses existing terminals even if not in the correct directory +- **When to disable**: + - Commands execute in wrong directory + - Virtual environment issues + - Terminal state corruption +- **Trade-off**: - Disabling creates more terminals but ensures clean state + +### Terminal Output Line Limit + +- **What it does**: Limits how many lines Cline reads from terminal output +- **Default**: 500 lines +- **When to adjust**: + - Increase for verbose build outputs + - Decrease if hitting token limits + - Set to 100 for commands with progress bars + +## Platform-Specific Solutions + +### macOS Issues + +#### Oh-My-Zsh Conflicts + +Oh-My-Zsh often interferes with shell integration. Solutions: + +1. Create a minimal `.zshrc` for VSCode: + ```bash + # ~/.zshrc-vscode + export TERM=xterm-256color + export PAGER=cat + # Minimal PATH and environment setup + ``` +2. Configure VSCode to use it: + ```json + { + "terminal.integrated.env.osx": { + "ZDOTDIR": "~/.zshrc-vscode" + } + } + ``` + +#### macOS 15+ Issues + +Recent macOS versions have stricter terminal permissions: + +1. System Preferences → Privacy & Security → Developer Tools +2. Add Visual Studio Code +3. Restart VSCode completely + +### Windows Issues + +#### PowerShell Execution Policy + +If commands fail silently: + +```powershell +Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser +``` + +#### WSL Integration + +For WSL issues: + +1. Use WSL extension for VSCode +2. Open folder in WSL: `code .` from WSL terminal +3. Select "WSL Bash" as terminal profile in Cline + +#### Path Issues + +Windows path problems: + +1. Use forward slashes in Cline: `C:/Users/...` +2. Quote paths with spaces: `"C:/Program Files/..."` +3. Avoid `~` - use full paths + +### Linux/SSH/Container Issues + +#### SSH Connections + +For remote development: + +1. Install Cline on the remote machine, not locally +2. Use SSH extension's integrated terminal +3. Increase timeout to 15+ seconds + +#### Docker Containers + +When developing in containers: + +1. Install Cline in the container +2. Use Dev Containers extension +3. Ensure shell integration scripts are available + +## Shell-Specific Fixes + +### Zsh + +```bash +# Add to ~/.zshrc +export TERM=xterm-256color +export PAGER=cat +# Disable fancy prompts for VSCode +if [[ "$TERM_PROGRAM" == "vscode" ]]; then + PS1="%n@%m %1~ %# " +fi +``` + +### Bash + +```bash +# Add to ~/.bashrc +export TERM=xterm-256color +export PAGER=cat +# Simple prompt for VSCode +if [[ "$TERM_PROGRAM" == "vscode" ]]; then + PS1='\u@\h:\w\$ ' +fi +``` + +### Fish + +```fish +# Add to ~/.config/fish/config.fish +set -x TERM xterm-256color +set -x PAGER cat +# Disable fancy features in VSCode +if test "$TERM_PROGRAM" = "vscode" + function fish_prompt + echo (whoami)'@'(hostname)':'(pwd)'> ' + end +end +``` + +### PowerShell + +```powershell +# Add to $PROFILE +$env:PAGER = "cat" +# Disable progress bars +$ProgressPreference = 'SilentlyContinue' +``` + +## Advanced Troubleshooting + +### Debug Mode + +Enable terminal debugging to see what's happening: + +1. Open VSCode Command Palette (Cmd/Ctrl+Shift+P) +2. Run: "Developer: Set Log Level..." +3. Choose "Trace" +4. Check Output panel → "Cline" for terminal logs + +### Manual Shell Integration Test + +Test if shell integration works at all: + +```bash +# In VSCode terminal +echo $TERM_PROGRAM # Should show "vscode" +echo $VSCODE_SHELL_INTEGRATION # Should be "1" +``` + +## FAQ + +### Why does Cline create so many terminals? + +When shell integration fails, Cline can't reuse terminals safely (they might be running long processes). Enable shell integration or adjust the terminal reuse setting. + +### Can I use my custom shell (nushell, xonsh, etc.)? + +Cline officially supports bash, zsh, fish, and PowerShell. Custom shells may work but aren't guaranteed. Use bash as a fallback. + +### Why do some commands work but others don't? + +Commands that use interactive features (pagers, progress bars, curses) often fail. Set `PAGER=cat` and use non-interactive flags. + +### How do I know if shell integration is working? + +Working integration shows command output in Cline's chat. Failed integration shows "Shell Integration Unavailable" or "[Command is running but producing no output]". + +## Still Having Issues? + +If you've tried everything: + +1. **Collect Debug Info**: + + ```bash + echo "Shell: $SHELL" + echo "Term: $TERM" + echo "VSCode: $TERM_PROGRAM" + which bash + bash --version + ``` + +2. **Report the Issue**: + - Use `/reportbug` in Cline github issues + - Include your debug info + - Mention which solutions you tried + + + Remember: Most terminal issues are resolved by switching to bash and increasing the timeout. Start there before trying complex + solutions. + diff --git a/docs/troubleshooting/terminal-quick-fixes.mdx b/docs/troubleshooting/terminal-quick-fixes.mdx new file mode 100644 index 00000000..153c3887 --- /dev/null +++ b/docs/troubleshooting/terminal-quick-fixes.mdx @@ -0,0 +1,51 @@ +--- +title: "Terminal Quick Fixes" +sidebarTitle: "Terminal Quick Fixes" +description: "Quick solutions for common terminal issues" +--- + +**Here is a list of common fixes, starting with the most applicable:** + +- **Switch to bash** (solves most instances) + + 1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window + 2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column + 3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down + +- **Increase timeout** + + 1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window + 2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column + 3. Navigate to "Shell integration timeout (seconds)" and enter **"10"** into the text field + +- **Disable terminal reuse** + 1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window + 2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column + 3. Look for **"Enable aggressive terminal reuse"**, and **uncheck** this option + +## Platform-Specific Fixes + +### macOS + Oh-My-Zsh + +```bash +# Create minimal config for VSCode +echo 'export TERM=xterm-256color' > ~/.zshrc-vscode +echo 'export PAGER=cat' >> ~/.zshrc-vscode +``` + +### Windows PowerShell + +```powershell +# Run as Administrator +Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser +``` + +### WSL + +- Open folder from WSL: `code .` +- Select **"WSL Bash"** in Cline settings, under **"Terminal Settings"** +- Increase **"Shell integration timeout (seconds)"** to **15** + +## Full Guide + +For detailed troubleshooting, see the [Complete Terminal Troubleshooting Guide](/troubleshooting/terminal-integration-guide). diff --git a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx index 366b03a1..4788eed9 100644 --- a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx @@ -78,69 +78,82 @@ export const TerminalSettingsSection: React.FC = (
{renderSectionHeader("terminal")}
-
-
-
From 021a014012618e29885ef400bcfe614eb393eb28 Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Wed, 2 Jul 2025 21:45:30 -0700 Subject: [PATCH 02/43] setting claude 4 as best model (#4637) Co-authored-by: Cline Evaluation --- .../components/settings/OpenRouterModelPicker.tsx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index cbaaf183..eac9ace7 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -44,13 +44,13 @@ export interface OpenRouterModelPickerProps { // Featured models for Cline provider const featuredModels = [ { - id: "google/gemini-2.5-pro", - description: "Large 1M context window, great value", + id: "anthropic/claude-sonnet-4", + description: "Recommended for agentic coding in Cline", label: "Best", }, { - id: "anthropic/claude-sonnet-4", - description: "Recommended for agentic coding in Cline", + id: "google/gemini-2.5-pro", + description: "Large 1M context window, great value", label: "Trending", }, { @@ -326,8 +326,8 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } If you're unsure which model to choose, Cline works best with{" "} handleModelChange("google/gemini-2.5-pro")}> - google/gemini-2.5-pro. + onClick={() => handleModelChange("anthropic/claude-sonnet-4")}> + anthropic/claude-sonnet-4. You can also try searching "free" for no-cost options currently available. From 6c2c0780eea9a37ec408ebee8c1371ec8bdd9c6f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 2 Jul 2025 22:15:45 -0700 Subject: [PATCH 03/43] v3.18.2 Release Notes (#4581) --- .changeset/afraid-experts-beg.md | 5 ----- .changeset/gold-berries-give.md | 5 ----- .changeset/khaki-fishes-unite.md | 5 ----- .changeset/lovely-readers-design.md | 5 ----- .changeset/lucky-fans-greet.md | 5 ----- .changeset/poor-years-grab.md | 5 ----- .changeset/shy-fishes-check.md | 5 ----- CHANGELOG.md | 9 +++++++++ package-lock.json | 4 ++-- package.json | 2 +- 10 files changed, 12 insertions(+), 38 deletions(-) delete mode 100644 .changeset/afraid-experts-beg.md delete mode 100644 .changeset/gold-berries-give.md delete mode 100644 .changeset/khaki-fishes-unite.md delete mode 100644 .changeset/lovely-readers-design.md delete mode 100644 .changeset/lucky-fans-greet.md delete mode 100644 .changeset/poor-years-grab.md delete mode 100644 .changeset/shy-fishes-check.md diff --git a/.changeset/afraid-experts-beg.md b/.changeset/afraid-experts-beg.md deleted file mode 100644 index 888b827d..00000000 --- a/.changeset/afraid-experts-beg.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Add confirmation popup when deleting tasks diff --git a/.changeset/gold-berries-give.md b/.changeset/gold-berries-give.md deleted file mode 100644 index 845c8c72..00000000 --- a/.changeset/gold-berries-give.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Refactor chat view into multiple modular files diff --git a/.changeset/khaki-fishes-unite.md b/.changeset/khaki-fishes-unite.md deleted file mode 100644 index b3bf964b..00000000 --- a/.changeset/khaki-fishes-unite.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Include litellm_session_id as part of chat completion requests diff --git a/.changeset/lovely-readers-design.md b/.changeset/lovely-readers-design.md deleted file mode 100644 index 7e3a6b53..00000000 --- a/.changeset/lovely-readers-design.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": minor ---- - -Add Claude Sonnet 4 and Opus 4 model in SAP AI Core provider. diff --git a/.changeset/lucky-fans-greet.md b/.changeset/lucky-fans-greet.md deleted file mode 100644 index 001f3144..00000000 --- a/.changeset/lucky-fans-greet.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -add cline.walkthrough command to command handler diff --git a/.changeset/poor-years-grab.md b/.changeset/poor-years-grab.md deleted file mode 100644 index 97e5ab22..00000000 --- a/.changeset/poor-years-grab.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -fix: Do not read auth variables from the user env when using Claude Code diff --git a/.changeset/shy-fishes-check.md b/.changeset/shy-fishes-check.md deleted file mode 100644 index 2acf47df..00000000 --- a/.changeset/shy-fishes-check.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -feat: Introduce Thinking Budget customization for Claude Code diff --git a/CHANGELOG.md b/CHANGELOG.md index 981c16fb..92614d19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [3.18.2] + +- Fix issue where terminal output would not be captured if shell integration fails by falling back to capturing the terminal content. +- Add confirmation popup when deleting tasks +- Add support for Claude Sonnet 4 and Opus 4 model in SAP AI Core provider (Thanks @lizzzcai!) +- Add support for `litellm_session_id` to group requests in a single session (Thanks @jorgegarciarey!) +- Add "Thinking Budget" customization for Claude Code (Thanks @BarreiroT!) +- Fix issue where the extension would use the user's environment variables for authentication when using Claude Code (Thanks @BarreiroT!) + ## [3.18.1] - Add support for Claude 4 Sonnet in SAP AI Core provider (Thanks @GTxx!) diff --git a/package-lock.json b/package-lock.json index 585c7f5d..edcf9dad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.1", + "version": "3.18.2", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.1", + "version": "3.18.2", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index ec77a82a..bcd651bc 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.1", + "version": "3.18.2", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" From d576b68cca927eb6f53a67ad5fc0efe59c614dc1 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 3 Jul 2025 16:24:14 -0500 Subject: [PATCH 04/43] Move plan/act model settings to global storage (#4636) * move model settings to global storage * cleanup * only run migration if globalState key is undefined --- .../context-tracking/FileContextTracker.ts | 10 +- src/core/controller/index.ts | 105 ++++++-------- src/core/controller/ui/initializeWebview.ts | 4 +- src/core/storage/state-keys.ts | 15 +- src/core/storage/state-migrations.ts | 63 ++++++--- src/core/storage/state.ts | 128 ++++++++---------- src/core/task/ToolExecutor.ts | 4 +- src/core/task/index.ts | 4 +- src/extension.ts | 8 +- src/services/test/TestServer.ts | 2 +- 10 files changed, 164 insertions(+), 179 deletions(-) diff --git a/src/core/context/context-tracking/FileContextTracker.ts b/src/core/context/context-tracking/FileContextTracker.ts index 14f7d4ce..a0bc5b07 100644 --- a/src/core/context/context-tracking/FileContextTracker.ts +++ b/src/core/context/context-tracking/FileContextTracker.ts @@ -244,7 +244,9 @@ export class FileContextTracker { async storePendingFileContextWarning(files: string[]): Promise { try { const key = `pendingFileContextWarning_${this.taskId}` - await updateWorkspaceState(this.context, key, files) + // NOTE: Using 'as any' because dynamic keys like pendingFileContextWarning_${taskId} + // are legitimate workspace state keys but don't fit the strict LocalStateKey type system + await updateWorkspaceState(this.context, key as any, files) } catch (error) { console.error("Error storing pending file context warning:", error) } @@ -256,7 +258,7 @@ export class FileContextTracker { async retrievePendingFileContextWarning(): Promise { try { const key = `pendingFileContextWarning_${this.taskId}` - const files = (await getWorkspaceState(this.context, key)) as string[] + const files = (await getWorkspaceState(this.context, key as any)) as string[] return files } catch (error) { console.error("Error retrieving pending file context warning:", error) @@ -271,7 +273,7 @@ export class FileContextTracker { try { const files = await this.retrievePendingFileContextWarning() if (files) { - await updateWorkspaceState(this.context, `pendingFileContextWarning_${this.taskId}`, undefined) + await updateWorkspaceState(this.context, `pendingFileContextWarning_${this.taskId}` as any, undefined) return files } } catch (error) { @@ -302,7 +304,7 @@ export class FileContextTracker { if (orphanedPendingContextTasks.length > 0) { for (const key of orphanedPendingContextTasks) { - await updateWorkspaceState(context, key, undefined) + await updateWorkspaceState(context, key as any, undefined) } } diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 6da05eeb..6e797a78 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -113,7 +113,7 @@ export class Controller { try { await storeSecret(this.context, "clineApiKey", undefined) await updateGlobalState(this.context, "userInfo", undefined) - await updateWorkspaceState(this.context, "apiProvider", "openrouter") + await updateGlobalState(this.context, "apiProvider", "openrouter") await this.postStateToWebview() vscode.window.showInformationMessage("Successfully logged out of Cline") } catch (error) { @@ -255,11 +255,6 @@ export class Controller { previousModeReasoningEffort: newReasoningEffort, previousModeAwsBedrockCustomSelected: newAwsBedrockCustomSelected, previousModeAwsBedrockCustomModelBaseId: newAwsBedrockCustomModelBaseId, - previousModeSapAiCoreClientId: newSapAiCoreClientId, - previousModeSapAiCoreClientSecret: newSapAiCoreClientSecret, - previousModeSapAiCoreBaseUrl: newSapAiCoreBaseUrl, - previousModeSapAiCoreTokenUrl: newSapAiCoreTokenUrl, - previousModeSapAiCoreResourceGroup: newSapAiResourceGroup, previousModeSapAiCoreModelId: newSapAiCoreModelId, planActSeparateModelsSetting, } = await getAllExtensionState(this.context) @@ -268,9 +263,9 @@ export class Controller { if (shouldSwitchModel) { // Save the last model used in this mode - await updateWorkspaceState(this.context, "previousModeApiProvider", apiConfiguration.apiProvider) - await updateWorkspaceState(this.context, "previousModeThinkingBudgetTokens", apiConfiguration.thinkingBudgetTokens) - await updateWorkspaceState(this.context, "previousModeReasoningEffort", apiConfiguration.reasoningEffort) + await updateGlobalState(this.context, "previousModeApiProvider", apiConfiguration.apiProvider) + await updateGlobalState(this.context, "previousModeThinkingBudgetTokens", apiConfiguration.thinkingBudgetTokens) + await updateGlobalState(this.context, "previousModeReasoningEffort", apiConfiguration.reasoningEffort) switch (apiConfiguration.apiProvider) { case "anthropic": case "vertex": @@ -280,16 +275,16 @@ export class Controller { case "qwen": case "deepseek": case "xai": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.apiModelId) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId) break case "bedrock": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.apiModelId) - await updateWorkspaceState( + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId) + await updateGlobalState( this.context, "previousModeAwsBedrockCustomSelected", apiConfiguration.awsBedrockCustomSelected, ) - await updateWorkspaceState( + await updateGlobalState( this.context, "previousModeAwsBedrockCustomModelBaseId", apiConfiguration.awsBedrockCustomModelBaseId, @@ -297,51 +292,38 @@ export class Controller { break case "openrouter": case "cline": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.openRouterModelId) - await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.openRouterModelInfo) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.openRouterModelId) + await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.openRouterModelInfo) break case "vscode-lm": // Important we don't set modelId to this, as it's an object not string (webview expects model id to be a string) - await updateWorkspaceState( + await updateGlobalState( this.context, "previousModeVsCodeLmModelSelector", apiConfiguration.vsCodeLmModelSelector, ) break case "openai": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.openAiModelId) - await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.openAiModelInfo) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.openAiModelId) + await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.openAiModelInfo) break case "ollama": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.ollamaModelId) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.ollamaModelId) break case "lmstudio": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.lmStudioModelId) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.lmStudioModelId) break case "litellm": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.liteLlmModelId) - await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.liteLlmModelInfo) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.liteLlmModelId) + await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.liteLlmModelInfo) break case "requesty": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.requestyModelId) - await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.requestyModelInfo) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.requestyModelId) + await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.requestyModelInfo) break case "sapaicore": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.apiModelId) - await updateWorkspaceState(this.context, "previousModeSapAiCoreClientId", apiConfiguration.sapAiCoreClientId) - await updateWorkspaceState( - this.context, - "previousModeSapAiCoreClientSecret", - apiConfiguration.sapAiCoreClientSecret, - ) - await updateWorkspaceState(this.context, "previousModeSapAiCoreBaseUrl", apiConfiguration.sapAiCoreBaseUrl) - await updateWorkspaceState(this.context, "previousModeSapAiCoreTokenUrl", apiConfiguration.sapAiCoreTokenUrl) - await updateWorkspaceState( - this.context, - "previousModeSapAiCoreResourceGroup", - apiConfiguration.sapAiResourceGroup, - ) - await updateWorkspaceState(this.context, "previousModeSapAiCoreModelId", apiConfiguration.sapAiCoreModelId) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId) + await updateGlobalState(this.context, "previousModeSapAiCoreModelId", apiConfiguration.sapAiCoreModelId) break } @@ -353,9 +335,9 @@ export class Controller { newReasoningEffort || newVsCodeLmModelSelector ) { - await updateWorkspaceState(this.context, "apiProvider", newApiProvider) - await updateWorkspaceState(this.context, "thinkingBudgetTokens", newThinkingBudgetTokens) - await updateWorkspaceState(this.context, "reasoningEffort", newReasoningEffort) + await updateGlobalState(this.context, "apiProvider", newApiProvider) + await updateGlobalState(this.context, "thinkingBudgetTokens", newThinkingBudgetTokens) + await updateGlobalState(this.context, "reasoningEffort", newReasoningEffort) switch (newApiProvider) { case "anthropic": case "vertex": @@ -365,41 +347,42 @@ export class Controller { case "qwen": case "deepseek": case "xai": - await updateWorkspaceState(this.context, "apiModelId", newModelId) + await updateGlobalState(this.context, "apiModelId", newModelId) break case "bedrock": - await updateWorkspaceState(this.context, "apiModelId", newModelId) - await updateWorkspaceState(this.context, "awsBedrockCustomSelected", newAwsBedrockCustomSelected) - await updateWorkspaceState(this.context, "awsBedrockCustomModelBaseId", newAwsBedrockCustomModelBaseId) + await updateGlobalState(this.context, "apiModelId", newModelId) + await updateGlobalState(this.context, "awsBedrockCustomSelected", newAwsBedrockCustomSelected) + await updateGlobalState(this.context, "awsBedrockCustomModelBaseId", newAwsBedrockCustomModelBaseId) break case "openrouter": case "cline": - await updateWorkspaceState(this.context, "openRouterModelId", newModelId) - await updateWorkspaceState(this.context, "openRouterModelInfo", newModelInfo) + await updateGlobalState(this.context, "openRouterModelId", newModelId) + await updateGlobalState(this.context, "openRouterModelInfo", newModelInfo) break case "vscode-lm": - await updateWorkspaceState(this.context, "vsCodeLmModelSelector", newVsCodeLmModelSelector) + await updateGlobalState(this.context, "vsCodeLmModelSelector", newVsCodeLmModelSelector) break case "openai": - await updateWorkspaceState(this.context, "openAiModelId", newModelId) - await updateWorkspaceState(this.context, "openAiModelInfo", newModelInfo) + await updateGlobalState(this.context, "openAiModelId", newModelId) + await updateGlobalState(this.context, "openAiModelInfo", newModelInfo) break case "ollama": - await updateWorkspaceState(this.context, "ollamaModelId", newModelId) + await updateGlobalState(this.context, "ollamaModelId", newModelId) break case "lmstudio": - await updateWorkspaceState(this.context, "lmStudioModelId", newModelId) + await updateGlobalState(this.context, "lmStudioModelId", newModelId) break case "litellm": - await updateWorkspaceState(this.context, "liteLlmModelId", newModelId) - await updateWorkspaceState(this.context, "liteLlmModelInfo", newModelInfo) + await updateGlobalState(this.context, "liteLlmModelId", newModelId) + await updateGlobalState(this.context, "liteLlmModelInfo", newModelInfo) break case "requesty": - await updateWorkspaceState(this.context, "requestyModelId", newModelId) - await updateWorkspaceState(this.context, "requestyModelInfo", newModelInfo) + await updateGlobalState(this.context, "requestyModelId", newModelId) + await updateGlobalState(this.context, "requestyModelInfo", newModelInfo) break case "sapaicore": - await updateWorkspaceState(this.context, "apiModelId", newModelId) + await updateGlobalState(this.context, "apiModelId", newModelId) + await updateGlobalState(this.context, "sapAiCoreModelId", newSapAiCoreModelId) break } @@ -412,7 +395,7 @@ export class Controller { // Save only non-mode properties to workspace storage const { mode, ...persistentChatSettings }: { mode: string } & StoredChatSettings = chatSettings - await updateWorkspaceState(this.context, "chatSettings", persistentChatSettings) + await updateGlobalState(this.context, "chatSettings", persistentChatSettings) await this.postStateToWebview() if (this.task) { @@ -486,7 +469,7 @@ export class Controller { await sendAuthCallbackEvent(customToken) const clineProvider: ApiProvider = "cline" - await updateWorkspaceState(this.context, "apiProvider", clineProvider) + await updateGlobalState(this.context, "apiProvider", clineProvider) // Update API configuration with the new provider and API key const { apiConfiguration } = await getAllExtensionState(this.context) @@ -645,7 +628,7 @@ export class Controller { } const openrouter: ApiProvider = "openrouter" - await updateWorkspaceState(this.context, "apiProvider", openrouter) + await updateGlobalState(this.context, "apiProvider", openrouter) await storeSecret(this.context, "openRouterApiKey", apiKey) await this.postStateToWebview() if (this.task) { diff --git a/src/core/controller/ui/initializeWebview.ts b/src/core/controller/ui/initializeWebview.ts index 74f17ea1..f799ffa8 100644 --- a/src/core/controller/ui/initializeWebview.ts +++ b/src/core/controller/ui/initializeWebview.ts @@ -1,7 +1,7 @@ import type { Controller } from "../index" import { EmptyRequest, Empty } from "@shared/proto/common" import { handleModelsServiceRequest } from "../models" -import { getAllExtensionState, getGlobalState, updateWorkspaceState } from "../../storage/state" +import { getAllExtensionState, getGlobalState, updateGlobalState } from "../../storage/state" import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels" import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplaceCatalog" import { telemetryService } from "@/services/posthog/telemetry/TelemetryService" @@ -32,7 +32,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe // Update model info in state (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there) const { apiConfiguration } = await getAllExtensionState(controller.context) if (apiConfiguration.openRouterModelId && response.models[apiConfiguration.openRouterModelId]) { - await updateWorkspaceState( + await updateGlobalState( controller.context, "openRouterModelInfo", response.models[apiConfiguration.openRouterModelId], diff --git a/src/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index 31ee6cf0..0f1d5753 100644 --- a/src/core/storage/state-keys.ts +++ b/src/core/storage/state-keys.ts @@ -77,13 +77,8 @@ export type GlobalStateKey = | "sapAiCoreTokenUrl" | "sapAiCoreBaseUrl" | "sapAiResourceGroup" - | "sapAiCoreClientId" - | "sapAiCoreClientSecret" - | "sapAiCoreModelId" | "claudeCodePath" - -export type LocalStateKey = - | "localClineRulesToggles" + // Settings around plan/act and ephemeral model configuration | "chatSettings" // Current active model configuration (per workspace) | "apiProvider" @@ -105,6 +100,7 @@ export type LocalStateKey = | "requestyModelInfo" | "togetherModelId" | "fireworksModelId" + | "sapAiCoreModelId" // Previous mode saved configurations (per workspace) | "previousModeApiProvider" | "previousModeModelId" @@ -114,9 +110,6 @@ export type LocalStateKey = | "previousModeReasoningEffort" | "previousModeAwsBedrockCustomSelected" | "previousModeAwsBedrockCustomModelBaseId" - | "previousModeSapAiCoreClientId" - | "previousModeSapAiCoreClientSecret" - | "previousModeSapAiCoreBaseUrl" - | "previousModeSapAiCoreTokenUrl" - | "previousModeSapAiCoreResourceGroup" | "previousModeSapAiCoreModelId" + +export type LocalStateKey = "localClineRulesToggles" | "localCursorRulesToggles" | "localWindsurfRulesToggles" | "workflowToggles" diff --git a/src/core/storage/state-migrations.ts b/src/core/storage/state-migrations.ts index 327ac5b4..e434df52 100644 --- a/src/core/storage/state-migrations.ts +++ b/src/core/storage/state-migrations.ts @@ -2,11 +2,11 @@ import * as vscode from "vscode" import { ensureRulesDirectoryExists } from "./disk" import fs from "fs/promises" import path from "path" -import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState, getAllExtensionState } from "./state" +import { updateGlobalState, getAllExtensionState, getGlobalState } from "./state" import { GlobalStateKey } from "./state-keys" -export async function migratePlanActGlobalToWorkspaceStorage(context: vscode.ExtensionContext) { - // Keys that were migrated from global storage to workspace storage +export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionContext) { + // Keys to migrate from workspace storage back to global storage const keysToMigrate = [ // Core settings "apiProvider", @@ -31,6 +31,7 @@ export async function migratePlanActGlobalToWorkspaceStorage(context: vscode.Ext "requestyModelInfo", "togetherModelId", "fireworksModelId", + "sapAiCoreModelId", // Previous mode settings "previousModeApiProvider", @@ -41,17 +42,24 @@ export async function migratePlanActGlobalToWorkspaceStorage(context: vscode.Ext "previousModeReasoningEffort", "previousModeAwsBedrockCustomSelected", "previousModeAwsBedrockCustomModelBaseId", + "previousModeSapAiCoreModelId", ] for (const key of keysToMigrate) { - const globalValue = await getGlobalState(context, key as GlobalStateKey) - if (globalValue !== undefined) { - const workspaceValue = await getWorkspaceState(context, key) - if (workspaceValue === undefined) { - await updateWorkspaceState(context, key, globalValue) - } - // Delete from global storage regardless of whether we copied it - await updateGlobalState(context, key as GlobalStateKey, undefined) + // Use raw workspace state since these keys shouldn't be in workspace storage + const workspaceValue = await context.workspaceState.get(key) + const globalValue = await context.globalState.get(key) + + if (workspaceValue !== undefined && globalValue === undefined) { + console.log(`[Storage Migration] migrating key: ${key} to global storage. Current value: ${workspaceValue}`) + + // Move to global storage + await updateGlobalState(context, key as GlobalStateKey, workspaceValue) + // Remove from workspace storage + await context.workspaceState.update(key, undefined) + const newWorkspaceValue = await context.workspaceState.get(key) + + console.log(`[Storage Migration] migrated key: ${key} to global storage. Current value: ${newWorkspaceValue}`) } } } @@ -126,22 +134,37 @@ export async function migrateCustomInstructionsToGlobalRules(context: vscode.Ext export async function migrateModeFromWorkspaceStorageToControllerState(context: vscode.ExtensionContext) { try { - // Get current chatSettings from workspace storage - const chatSettings = (await getWorkspaceState(context, "chatSettings")) as any + // Check legacy workspace storage (use raw methods since chatSettings is now global) + const workspaceChatSettings = (await context.workspaceState.get("chatSettings")) as any - if (chatSettings && typeof chatSettings === "object" && "mode" in chatSettings) { - console.log("Cleaning up mode from workspace storage...") + if (workspaceChatSettings && typeof workspaceChatSettings === "object" && "mode" in workspaceChatSettings) { + console.log("Cleaning up mode from legacy workspace storage...") // Remove mode property from chatSettings - const { mode, ...cleanedChatSettings } = chatSettings + const { mode, ...cleanedChatSettings } = workspaceChatSettings - // Save cleaned chatSettings back to workspace storage - await updateWorkspaceState(context, "chatSettings", cleanedChatSettings) + // Save cleaned chatSettings back to workspace storage (will be migrated later) + await context.workspaceState.update("chatSettings", cleanedChatSettings) - console.log("Successfully removed mode from workspace storage chatSettings") + console.log("Successfully removed mode from legacy workspace storage chatSettings") + } + + // Also check global storage for any mode cleanup needed + const globalChatSettings = (await context.globalState.get("chatSettings")) as any + + if (globalChatSettings && typeof globalChatSettings === "object" && "mode" in globalChatSettings) { + console.log("Cleaning up mode from global storage...") + + // Remove mode property from chatSettings + const { mode, ...cleanedChatSettings } = globalChatSettings + + // Save cleaned chatSettings back to global storage + await updateGlobalState(context, "chatSettings", cleanedChatSettings) + + console.log("Successfully removed mode from global storage chatSettings") } } catch (error) { - console.error("Failed to cleanup mode from workspace storage:", error) + console.error("Failed to cleanup mode from storage:", error) // Continue execution - migration failure shouldn't break extension startup } } diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index 7286abcd..1c43651c 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -2,7 +2,7 @@ import * as vscode from "vscode" import { DEFAULT_CHAT_SETTINGS } from "@shared/ChatSettings" import { DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings" import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings" -import { GlobalStateKey, SecretKey } from "./state-keys" +import { GlobalStateKey, LocalStateKey, SecretKey } from "./state-keys" import { ApiConfiguration, ApiProvider, BedrockModelId, ModelInfo } from "@shared/api" import { HistoryItem } from "@shared/HistoryItem" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" @@ -44,11 +44,11 @@ export async function getSecret(context: vscode.ExtensionContext, key: SecretKey // workspace -export async function updateWorkspaceState(context: vscode.ExtensionContext, key: string, value: any) { +export async function updateWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey, value: any) { await context.workspaceState.update(key, value) } -export async function getWorkspaceState(context: vscode.ExtensionContext, key: string) { +export async function getWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey) { return await context.workspaceState.get(key) } @@ -125,7 +125,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { sapAiCoreBaseUrl, sapAiCoreTokenUrl, sapAiResourceGroup, - sapAiCoreModelId, claudeCodePath, ] = await Promise.all([ getGlobalState(context, "isNewUser") as Promise, @@ -199,7 +198,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { getGlobalState(context, "sapAiCoreBaseUrl") as Promise, getGlobalState(context, "sapAiCoreTokenUrl") as Promise, getGlobalState(context, "sapAiResourceGroup") as Promise, - getGlobalState(context, "sapAiCoreModelId") as Promise, getGlobalState(context, "claudeCodePath") as Promise, ]) @@ -234,47 +232,39 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { previousModeReasoningEffort, previousModeAwsBedrockCustomSelected, previousModeAwsBedrockCustomModelBaseId, - previousModeSapAiCoreClientId, - previousModeSapAiCoreClientSecret, - previousModeSapAiCoreBaseUrl, - previousModeSapAiCoreTokenUrl, - previousModeSapAiCoreResourceGroup, previousModeSapAiCoreModelId, + sapAiCoreModelId, ] = await Promise.all([ - getWorkspaceState(context, "chatSettings") as Promise, - getWorkspaceState(context, "apiProvider") as Promise, - getWorkspaceState(context, "apiModelId") as Promise, - getWorkspaceState(context, "thinkingBudgetTokens") as Promise, - getWorkspaceState(context, "reasoningEffort") as Promise, - getWorkspaceState(context, "vsCodeLmModelSelector") as Promise, - getWorkspaceState(context, "awsBedrockCustomSelected") as Promise, - getWorkspaceState(context, "awsBedrockCustomModelBaseId") as Promise, - getWorkspaceState(context, "openRouterModelId") as Promise, - getWorkspaceState(context, "openRouterModelInfo") as Promise, - getWorkspaceState(context, "openAiModelId") as Promise, - getWorkspaceState(context, "openAiModelInfo") as Promise, - getWorkspaceState(context, "ollamaModelId") as Promise, - getWorkspaceState(context, "lmStudioModelId") as Promise, - getWorkspaceState(context, "liteLlmModelId") as Promise, - getWorkspaceState(context, "liteLlmModelInfo") as Promise, - getWorkspaceState(context, "requestyModelId") as Promise, - getWorkspaceState(context, "requestyModelInfo") as Promise, - getWorkspaceState(context, "togetherModelId") as Promise, - getWorkspaceState(context, "fireworksModelId") as Promise, - getWorkspaceState(context, "previousModeApiProvider") as Promise, - getWorkspaceState(context, "previousModeModelId") as Promise, - getWorkspaceState(context, "previousModeModelInfo") as Promise, - getWorkspaceState(context, "previousModeVsCodeLmModelSelector") as Promise, - getWorkspaceState(context, "previousModeThinkingBudgetTokens") as Promise, - getWorkspaceState(context, "previousModeReasoningEffort") as Promise, - getWorkspaceState(context, "previousModeAwsBedrockCustomSelected") as Promise, - getWorkspaceState(context, "previousModeAwsBedrockCustomModelBaseId") as Promise, - getWorkspaceState(context, "previousModeSapAiCoreClientId") as Promise, - getWorkspaceState(context, "previousModeSapAiCoreClientSecret") as Promise, - getWorkspaceState(context, "previousModeSapAiCoreBaseUrl") as Promise, - getWorkspaceState(context, "previousModeSapAiCoreTokenUrl") as Promise, - getWorkspaceState(context, "previousModeSapAiCoreResourceGroup") as Promise, - getWorkspaceState(context, "previousModeSapAiCoreModelId") as Promise, + getGlobalState(context, "chatSettings") as Promise, + getGlobalState(context, "apiProvider") as Promise, + getGlobalState(context, "apiModelId") as Promise, + getGlobalState(context, "thinkingBudgetTokens") as Promise, + getGlobalState(context, "reasoningEffort") as Promise, + getGlobalState(context, "vsCodeLmModelSelector") as Promise, + getGlobalState(context, "awsBedrockCustomSelected") as Promise, + getGlobalState(context, "awsBedrockCustomModelBaseId") as Promise, + getGlobalState(context, "openRouterModelId") as Promise, + getGlobalState(context, "openRouterModelInfo") as Promise, + getGlobalState(context, "openAiModelId") as Promise, + getGlobalState(context, "openAiModelInfo") as Promise, + getGlobalState(context, "ollamaModelId") as Promise, + getGlobalState(context, "lmStudioModelId") as Promise, + getGlobalState(context, "liteLlmModelId") as Promise, + getGlobalState(context, "liteLlmModelInfo") as Promise, + getGlobalState(context, "requestyModelId") as Promise, + getGlobalState(context, "requestyModelInfo") as Promise, + getGlobalState(context, "togetherModelId") as Promise, + getGlobalState(context, "fireworksModelId") as Promise, + getGlobalState(context, "previousModeApiProvider") as Promise, + getGlobalState(context, "previousModeModelId") as Promise, + getGlobalState(context, "previousModeModelInfo") as Promise, + getGlobalState(context, "previousModeVsCodeLmModelSelector") as Promise, + getGlobalState(context, "previousModeThinkingBudgetTokens") as Promise, + getGlobalState(context, "previousModeReasoningEffort") as Promise, + getGlobalState(context, "previousModeAwsBedrockCustomSelected") as Promise, + getGlobalState(context, "previousModeAwsBedrockCustomModelBaseId") as Promise, + getGlobalState(context, "previousModeSapAiCoreModelId") as Promise, + getGlobalState(context, "sapAiCoreModelId") as Promise, ]) let apiProvider: ApiProvider @@ -410,11 +400,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { previousModeReasoningEffort, previousModeAwsBedrockCustomSelected, previousModeAwsBedrockCustomModelBaseId, - previousModeSapAiCoreClientId, - previousModeSapAiCoreClientSecret, - previousModeSapAiCoreBaseUrl, - previousModeSapAiCoreTokenUrl, - previousModeSapAiCoreResourceGroup, previousModeSapAiCoreModelId, mcpMarketplaceEnabled: mcpMarketplaceEnabled, mcpRichDisplayEnabled: mcpRichDisplayEnabled ?? true, @@ -505,26 +490,28 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a sapAiCoreModelId, claudeCodePath, } = apiConfiguration - // Workspace state updates - await updateWorkspaceState(context, "apiProvider", apiProvider) - await updateWorkspaceState(context, "apiModelId", apiModelId) - await updateWorkspaceState(context, "thinkingBudgetTokens", thinkingBudgetTokens) - await updateWorkspaceState(context, "reasoningEffort", reasoningEffort) - await updateWorkspaceState(context, "vsCodeLmModelSelector", vsCodeLmModelSelector) - await updateWorkspaceState(context, "awsBedrockCustomSelected", awsBedrockCustomSelected) - await updateWorkspaceState(context, "awsBedrockCustomModelBaseId", awsBedrockCustomModelBaseId) - await updateWorkspaceState(context, "openRouterModelId", openRouterModelId) - await updateWorkspaceState(context, "openRouterModelInfo", openRouterModelInfo) - await updateWorkspaceState(context, "openAiModelId", openAiModelId) - await updateWorkspaceState(context, "openAiModelInfo", openAiModelInfo) - await updateWorkspaceState(context, "ollamaModelId", ollamaModelId) - await updateWorkspaceState(context, "lmStudioModelId", lmStudioModelId) - await updateWorkspaceState(context, "liteLlmModelId", liteLlmModelId) - await updateWorkspaceState(context, "liteLlmModelInfo", liteLlmModelInfo) - await updateWorkspaceState(context, "requestyModelId", requestyModelId) - await updateWorkspaceState(context, "requestyModelInfo", requestyModelInfo) - await updateWorkspaceState(context, "togetherModelId", togetherModelId) - await updateWorkspaceState(context, "fireworksModelId", fireworksModelId) + + // Ephemeral model config updates + await updateGlobalState(context, "apiProvider", apiProvider) + await updateGlobalState(context, "apiModelId", apiModelId) + await updateGlobalState(context, "thinkingBudgetTokens", thinkingBudgetTokens) + await updateGlobalState(context, "reasoningEffort", reasoningEffort) + await updateGlobalState(context, "vsCodeLmModelSelector", vsCodeLmModelSelector) + await updateGlobalState(context, "awsBedrockCustomSelected", awsBedrockCustomSelected) + await updateGlobalState(context, "awsBedrockCustomModelBaseId", awsBedrockCustomModelBaseId) + await updateGlobalState(context, "openRouterModelId", openRouterModelId) + await updateGlobalState(context, "openRouterModelInfo", openRouterModelInfo) + await updateGlobalState(context, "openAiModelId", openAiModelId) + await updateGlobalState(context, "openAiModelInfo", openAiModelInfo) + await updateGlobalState(context, "ollamaModelId", ollamaModelId) + await updateGlobalState(context, "lmStudioModelId", lmStudioModelId) + await updateGlobalState(context, "liteLlmModelId", liteLlmModelId) + await updateGlobalState(context, "liteLlmModelInfo", liteLlmModelInfo) + await updateGlobalState(context, "requestyModelId", requestyModelId) + await updateGlobalState(context, "requestyModelInfo", requestyModelInfo) + await updateGlobalState(context, "togetherModelId", togetherModelId) + await updateGlobalState(context, "fireworksModelId", fireworksModelId) + await updateGlobalState(context, "sapAiCoreModelId", sapAiCoreModelId) // Global state updates await updateGlobalState(context, "awsRegion", awsRegion) @@ -552,12 +539,9 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs) await updateGlobalState(context, "fireworksModelMaxCompletionTokens", fireworksModelMaxCompletionTokens) await updateGlobalState(context, "fireworksModelMaxTokens", fireworksModelMaxTokens) - await updateGlobalState(context, "favoritedModelIds", favoritedModelIds) - await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs) await updateGlobalState(context, "sapAiCoreBaseUrl", sapAiCoreBaseUrl) await updateGlobalState(context, "sapAiCoreTokenUrl", sapAiCoreTokenUrl) await updateGlobalState(context, "sapAiResourceGroup", sapAiResourceGroup) - await updateGlobalState(context, "sapAiCoreModelId", sapAiCoreModelId) await updateGlobalState(context, "claudeCodePath", claudeCodePath) // Secret updates diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 7afdcc8c..dc920013 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -49,7 +49,7 @@ import { ContextManager } from "../context/context-management/ContextManager" import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation" import { formatResponse } from "../prompts/responses" import { ensureTaskDirectoryExists } from "../storage/disk" -import { getWorkspaceState } from "../storage/state" +import { getGlobalState, getWorkspaceState } from "../storage/state" import { TaskState } from "./TaskState" import { MessageStateHandler } from "./message-state" import { AutoApprove } from "./tools/autoApprove" @@ -1917,7 +1917,7 @@ export class ToolExecutor { const clineVersion = vscode.extensions.getExtension("saoudrizwan.claude-dev")?.packageJSON.version || "Unknown" const systemInfo = `VSCode: ${vscode.version}, Node.js: ${process.version}, Architecture: ${os.arch()}` - const providerAndModel = `${(await getWorkspaceState(this.context, "apiProvider")) as string} / ${this.api.getModel().id}` + const providerAndModel = `${await getGlobalState(this.context, "apiProvider")} / ${this.api.getModel().id}` // Ask user for confirmation const bugReportData = JSON.stringify({ diff --git a/src/core/task/index.ts b/src/core/task/index.ts index d98fbe4f..b7bad52b 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -70,7 +70,7 @@ import { getSavedClineMessages, GlobalFileNames, } from "@core/storage/disk" -import { getWorkspaceState } from "@core/storage/state" +import { getGlobalState, getWorkspaceState } from "@core/storage/state" import { processFilesIntoText } from "@integrations/misc/extract-text" import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" import { McpHub } from "@services/mcp/McpHub" @@ -1873,7 +1873,7 @@ export class Task { } // Used to know what models were used in the task if user wants to export metadata for error reporting purposes - const currentProviderId = (await getWorkspaceState(this.getContext(), "apiProvider")) as string + const currentProviderId = (await getGlobalState(this.getContext(), "apiProvider")) as string if (currentProviderId && this.api.getModel().id) { try { await this.modelContextTracker.recordModelUsage(currentProviderId, this.api.getModel().id, this.chatSettings.mode) diff --git a/src/extension.ts b/src/extension.ts index e3fbdb3f..43cc8a38 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -23,7 +23,7 @@ import { WebviewProviderType } from "./shared/webview/types" import { sendHistoryButtonClickedEvent } from "./core/controller/ui/subscribeToHistoryButtonClicked" import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToAccountButtonClicked" import { - migratePlanActGlobalToWorkspaceStorage, + migrateWorkspaceToGlobalStorage, migrateCustomInstructionsToGlobalRules, migrateModeFromWorkspaceStorageToControllerState, migrateWelcomeViewCompleted, @@ -60,9 +60,6 @@ export async function activate(context: vscode.ExtensionContext) { maybeSetupHostProviders(context) - // Migrate global storage values to workspace storage (one-time cleanup) - await migratePlanActGlobalToWorkspaceStorage(context) - // Migrate custom instructions to global Cline rules (one-time cleanup) await migrateCustomInstructionsToGlobalRules(context) @@ -72,6 +69,9 @@ export async function activate(context: vscode.ExtensionContext) { // Migrate welcomeViewCompleted setting based on existing API keys (one-time cleanup) await migrateWelcomeViewCompleted(context) + // Migrate workspace storage values back to global storage (reverting previous migration) + await migrateWorkspaceToGlobalStorage(context) + // Clean up orphaned file context warnings (startup cleanup) await FileContextTracker.cleanupOrphanedWarnings(context) diff --git a/src/services/test/TestServer.ts b/src/services/test/TestServer.ts index 65886630..c64e450c 100644 --- a/src/services/test/TestServer.ts +++ b/src/services/test/TestServer.ts @@ -273,7 +273,7 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server await updateApiConfiguration(visibleWebview.controller.context, updatedConfig) // Update global state to use cline provider - await updateWorkspaceState(visibleWebview.controller.context, "apiProvider", "cline" as ApiProvider) + await updateGlobalState(visibleWebview.controller.context, "apiProvider", "cline" as ApiProvider) // Post state to webview to reflect changes await visibleWebview.controller.postStateToWebview() From 50dc89b551f8ad366dafa5f0f2815b18865503e4 Mon Sep 17 00:00:00 2001 From: Kevin Taylor Date: Thu, 3 Jul 2025 14:40:58 -0700 Subject: [PATCH 05/43] Strip thinking tokens from Cerebras reasoning model inputs (#4635) * Strip thinking tokens from Cerebras reasoning model inputs Filter out thinking tokens in message history * changeset * changeset --------- Co-authored-by: Cline Evaluation --- .changeset/chilly-sheep-rhyme.md | 5 +++++ src/api/providers/cerebras.ts | 20 +++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 .changeset/chilly-sheep-rhyme.md diff --git a/.changeset/chilly-sheep-rhyme.md b/.changeset/chilly-sheep-rhyme.md new file mode 100644 index 00000000..0edea60d --- /dev/null +++ b/.changeset/chilly-sheep-rhyme.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Improve cerebras Qwen model performance by removing thinking tokens from the model input \ No newline at end of file diff --git a/src/api/providers/cerebras.ts b/src/api/providers/cerebras.ts index 641d574d..1576ba45 100644 --- a/src/api/providers/cerebras.ts +++ b/src/api/providers/cerebras.ts @@ -33,6 +33,15 @@ export class CerebrasHandler implements ApiHandler { content: string }> = [{ role: "system", content: systemPrompt }] + // Helper function to strip thinking tags from content + const stripThinkingTags = (content: string): string => { + return content.replace(/[\s\S]*?<\/think>/g, "").trim() + } + + // Check if this is a reasoning model that uses thinking tags + const modelId = this.getModel().id + const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill") + // Convert Anthropic messages to Cerebras format for (const message of messages) { if (message.role === "user") { @@ -50,7 +59,7 @@ export class CerebrasHandler implements ApiHandler { : message.content cerebrasMessages.push({ role: "user", content }) } else if (message.role === "assistant") { - const content = Array.isArray(message.content) + let content = Array.isArray(message.content) ? message.content .map((block) => { if (block.type === "text") { @@ -60,6 +69,13 @@ export class CerebrasHandler implements ApiHandler { }) .join("\n") : message.content || "" + + // Strip thinking tags from assistant messages for reasoning models + // so the model doesn't see its own thinking in the conversation history + if (isReasoningModel) { + content = stripThinkingTags(content) + } + cerebrasMessages.push({ role: "assistant", content }) } } @@ -74,8 +90,6 @@ export class CerebrasHandler implements ApiHandler { // Handle streaming response let reasoning: string | null = null // Track reasoning content for models that support thinking - const modelId = this.getModel().id - const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill") for await (const chunk of stream as any) { // Type assertion for the streaming chunk From bc5225ce5241015878314e22fa3ab43b709bf038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Barreiro?= <52393857+BarreiroT@users.noreply.github.com> Date: Thu, 3 Jul 2025 23:41:59 +0200 Subject: [PATCH 06/43] Improve Claude Code handling (#4619) * Prevent filling the chat with error messages * Improve env variables and remove the magic number * Add changeset * refactor * Update run.ts --------- Co-authored-by: Ara --- .changeset/thirty-islands-admire.md | 5 +++++ src/integrations/claude-code/run.ts | 29 ++++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 .changeset/thirty-islands-admire.md diff --git a/.changeset/thirty-islands-admire.md b/.changeset/thirty-islands-admire.md new file mode 100644 index 00000000..46dcd347 --- /dev/null +++ b/.changeset/thirty-islands-admire.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Improve Claude Code handling diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index 90fe9caa..7838b27a 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -77,6 +77,20 @@ export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator `Claude Code process exited with code ${exitCode}.${errorOutput ? ` Error output: ${errorOutput}` : ""}`, ) } + } catch (err) { + // When the command fails, execa throws an error with the arguments, which include the whole system prompt. + // We want to log that, but not show it to the user. + console.error(`Error during Claude Code execution:`, err) + if (err instanceof Error) { + const startOfCommand = err.message.indexOf(": ") + if (startOfCommand !== -1) { + const messageWithoutCommand = err.message.slice(0, startOfCommand).trim() + + throw new Error(messageWithoutCommand, { cause: err }) + } + } + + throw err } finally { rl.close() if (!process.killed) { @@ -107,9 +121,11 @@ const claudeCodeTools = [ ].join(",") const CLAUDE_CODE_TIMEOUT = 600000 // 10 minutes +// https://github.com/sindresorhus/execa/blob/main/docs/api.md#optionsmaxbuffer +const BUFFER_SIZE = 20_000_000 // 20 MB function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions) { - const claudePath = path || "claude" + const claudePath = path?.trim() || "claude" const args = [ "-p", @@ -129,10 +145,17 @@ function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetToken args.push("--model", modelId) } + /** + * @see {@link https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables} + */ const env: NodeJS.ProcessEnv = { ...process.env, - // The default is 32000. However, I've gotten larger responses, so we increase it unless the user specified it. + // Respect the user's environment variables but set defaults. + // The default is 32000. However, I've gotten larger responses. CLAUDE_CODE_MAX_OUTPUT_TOKENS: process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS || "64000", + // Disable telemetry, auto-updater and error reporting. + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC || "1", + DISABLE_NON_ESSENTIAL_MODEL_CALLS: process.env.DISABLE_NON_ESSENTIAL_MODEL_CALLS || "1", MAX_THINKING_TOKENS: (thinkingBudgetTokens || 0).toString(), } @@ -146,7 +169,7 @@ function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetToken stderr: "pipe", env, cwd, - maxBuffer: 1024 * 1024 * 1000, + maxBuffer: BUFFER_SIZE, timeout: CLAUDE_CODE_TIMEOUT, }) From 36e3f4cdd3cf84d26728010778380f32dac5d9a7 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 3 Jul 2025 14:54:10 -0700 Subject: [PATCH 07/43] add log + run options (#4630) * log + options * changeset --------- Co-authored-by: Cline Evaluation --- .changeset/breezy-zebras-enjoy.md | 5 +++++ evals/cli/src/commands/runDiffEval.ts | 5 +++++ evals/cli/src/index.ts | 2 ++ evals/diff-edits/ClineWrapper.ts | 23 ++++++++++++----------- evals/diff-edits/TestRunner.ts | 22 ++++++++++++---------- evals/diff-edits/helpers.ts | 6 ++++++ evals/diff-edits/types.ts | 2 ++ 7 files changed, 44 insertions(+), 21 deletions(-) create mode 100644 .changeset/breezy-zebras-enjoy.md diff --git a/.changeset/breezy-zebras-enjoy.md b/.changeset/breezy-zebras-enjoy.md new file mode 100644 index 00000000..336daede --- /dev/null +++ b/.changeset/breezy-zebras-enjoy.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Improved eval framework with more logging and run options diff --git a/evals/cli/src/commands/runDiffEval.ts b/evals/cli/src/commands/runDiffEval.ts index 909ef4f2..94f702d8 100644 --- a/evals/cli/src/commands/runDiffEval.ts +++ b/evals/cli/src/commands/runDiffEval.ts @@ -6,6 +6,7 @@ interface RunDiffEvalOptions { modelIds: string systemPromptName: string validAttemptsPerCase: number + maxAttemptsPerCase?: number parsingFunction: string diffEditFunction: string thinkingBudget: number @@ -71,6 +72,10 @@ export async function runDiffEvalHandler(options: RunDiffEvalOptions) { args.push("--verbose") } + if (options.maxAttemptsPerCase) { + args.push("--max-attempts-per-case", String(options.maxAttemptsPerCase)) + } + if (options.maxCases) { args.push("--max-cases", String(options.maxCases)) } diff --git a/evals/cli/src/index.ts b/evals/cli/src/index.ts index 036a99c5..48579f31 100644 --- a/evals/cli/src/index.ts +++ b/evals/cli/src/index.ts @@ -87,6 +87,7 @@ program .option("--model-ids ", "Comma-separated list of model IDs to test") .option("--system-prompt-name ", "The name of the system prompt to use", "basicSystemPrompt") .option("-n, --valid-attempts-per-case ", "Number of valid attempts per test case per model (will retry until this many valid attempts are collected)", "1") + .option("--max-attempts-per-case ", "Maximum total attempts per test case (default: 10x valid attempts)") .option("--max-cases ", "Maximum number of test cases to run (limits total cases loaded)") .option("--parsing-function ", "The parsing function to use", "parseAssistantMessageV2") .option("--diff-edit-function ", "The diff editing function to use", "constructNewFileContentV2") @@ -102,6 +103,7 @@ program const fullOptions = { ...options, validAttemptsPerCase: parseInt(options.validAttemptsPerCase, 10), + maxAttemptsPerCase: options.maxAttemptsPerCase ? parseInt(options.maxAttemptsPerCase, 10) : undefined, thinkingBudget: parseInt(options.thinkingBudget, 10), maxCases: options.maxCases ? parseInt(options.maxCases, 10) : undefined, } diff --git a/evals/diff-edits/ClineWrapper.ts b/evals/diff-edits/ClineWrapper.ts index ad435ff5..b236b6fd 100644 --- a/evals/diff-edits/ClineWrapper.ts +++ b/evals/diff-edits/ClineWrapper.ts @@ -30,6 +30,7 @@ const diffEditingFunctions: Record = { } import { TestInput, TestResult, ExtractedToolCall } from "./types" +import { log } from "./helpers" export { TestInput, TestResult, ExtractedToolCall } interface StreamResult { @@ -284,21 +285,21 @@ export async function runSingleEvaluation(input: TestInput): Promise } // check that we are editing the correct file path - console.log(`Expected file path: "${originalFilePath}"`); - console.log(`Actual file path used: "${diffToolPath}"`); + log(input.isVerbose, `Expected file path: "${originalFilePath}"`) + log(input.isVerbose, `Actual file path used: "${diffToolPath}"`) if (diffToolPath !== originalFilePath) { - console.log(`❌ File path mismatch detected!`); + log(input.isVerbose, `❌ File path mismatch detected!`) // Enhanced logging: if (streamResult?.assistantMessage) { - console.log(` Full model output (assistantMessage):`); - console.log(` -----------------------------------------`); - console.log(` ${streamResult.assistantMessage}`); - console.log(` -----------------------------------------`); + log(input.isVerbose, ` Full model output (assistantMessage):`) + log(input.isVerbose, ` -----------------------------------------`) + log(input.isVerbose, ` ${streamResult.assistantMessage}`) + log(input.isVerbose, ` -----------------------------------------`) } if (toolCall) { - console.log(` Parsed tool call that caused mismatch:`); - console.log(` ${JSON.stringify(toolCall, null, 2)}`); - console.log(` -----------------------------------------`); + log(input.isVerbose, ` Parsed tool call that caused mismatch:`) + log(input.isVerbose, ` ${JSON.stringify(toolCall, null, 2)}`) + log(input.isVerbose, ` -----------------------------------------`) } return { success: false, @@ -321,7 +322,7 @@ export async function runSingleEvaluation(input: TestInput): Promise // If it's just a string, diffSuccess stays true and replacementData stays undefined } catch (error: any) { diffSuccess = false - console.log("ERROR:",error) + log(input.isVerbose, `ERROR: ${error}`) } return { diff --git a/evals/diff-edits/TestRunner.ts b/evals/diff-edits/TestRunner.ts index 32436fec..d517448d 100644 --- a/evals/diff-edits/TestRunner.ts +++ b/evals/diff-edits/TestRunner.ts @@ -7,7 +7,7 @@ import { constructNewFileContent as constructNewFileContent_06_26_25 } from "./d import { constructNewFileContent as constructNewFileContentV3 } from "../../src/core/assistant-message/diff" import { basicSystemPrompt } from "./prompts/basicSystemPrompt-06-06-25" import { claude4SystemPrompt } from "./prompts/claude4SystemPrompt-06-06-25" -import { formatResponse } from "./helpers" +import { formatResponse, log } from "./helpers" import { Anthropic } from "@anthropic-ai/sdk" import * as fs from "fs" import * as path from "path" @@ -40,12 +40,6 @@ const encoding = get_encoding("cl100k_base"); let openRouterModelDataGlobal: Record = {}; // Global to store fetched data -function log(isVerbose: boolean, message: string) { - if (isVerbose) { - console.log(message) - } -} - const systemPromptGeneratorLookup: Record = { basicSystemPrompt: basicSystemPrompt, claude4SystemPrompt: claude4SystemPrompt, @@ -641,6 +635,7 @@ class NodeTestRunner { thinkingBudgetTokens: testConfig.thinking_tokens_budget, originalDiffEditToolCallMessage: testConfig.replay ? testCase.original_diff_edit_tool_call_message : undefined, diffApplyFile: testConfig.diff_apply_file, + isVerbose: isVerbose, } if (isVerbose) { @@ -807,8 +802,8 @@ class NodeTestRunner { log(isVerbose, `Warning: Failed to store result in database: ${error}`); } - // Safety check to prevent infinite loops - limit to 10 attempts per valid attempt requested - if (totalAttempts >= testConfig.number_of_runs * 10) { + // Safety check to prevent infinite loops - use configurable max attempts limit + if (totalAttempts >= testConfig.max_attempts_per_case) { log(isVerbose, ` ⚠️ Reached maximum attempts (${totalAttempts}) for test case ${testCase.test_id}. Only got ${validAttempts}/${testConfig.number_of_runs} valid attempts.`); break; } @@ -927,6 +922,7 @@ async function main() { .option("--model-ids ", "Comma-separated list of model IDs to test") .option("--system-prompt-name ", "The name of the system prompt to use", "basicSystemPrompt") .option("-n, --valid-attempts-per-case ", "Number of valid attempts per test case per model (will retry until this many valid attempts are collected)", "1") + .option("--max-attempts-per-case ", "Maximum total attempts per test case (default: 10x valid attempts)") .option("--max-cases ", "Maximum number of test cases to run (limits total cases loaded)") .option("--parsing-function ", "The parsing function to use", "parseAssistantMessageV2") .option("--diff-edit-function ", "The diff editing function to use", "diff-06-25-25") @@ -957,6 +953,11 @@ async function main() { } const validAttemptsPerCase = parseInt(options.validAttemptsPerCase, 10); + + // Compute dynamic default for max attempts: 10x valid attempts if not specified + const maxAttemptsPerCase = options.maxAttemptsPerCase + ? parseInt(options.maxAttemptsPerCase, 10) + : validAttemptsPerCase * 10; const runner = new NodeTestRunner(options.replay || !!options.replayRunId) @@ -1062,6 +1063,7 @@ async function main() { model_id: modelId, system_prompt_name: options.systemPromptName, number_of_runs: validAttemptsPerCase, + max_attempts_per_case: maxAttemptsPerCase, parsing_function: options.parsingFunction, diff_edit_function: options.diffEditFunction, thinking_tokens_budget: parseInt(options.thinkingBudget, 10), @@ -1129,7 +1131,7 @@ async function main() { remainingTasks = remainingTasks.filter(task => { const taskId = `${task.modelId}-${task.testCase.test_id}`; - if (taskStates[taskId].total >= validAttemptsPerCase * 10) { + if (taskStates[taskId].total >= task.testConfig.max_attempts_per_case) { log(isVerbose, ` ⚠️ Reached maximum attempts for ${task.testCase.test_id} with ${task.modelId}.`); return false; } diff --git a/evals/diff-edits/helpers.ts b/evals/diff-edits/helpers.ts index 63ccd6d0..78e6c72c 100644 --- a/evals/diff-edits/helpers.ts +++ b/evals/diff-edits/helpers.ts @@ -23,3 +23,9 @@ export const formatResponse = { return formatImagesIntoBlocks(images) }, } + +export function log(isVerbose: boolean, message: string) { + if (isVerbose) { + console.log(message) + } +} diff --git a/evals/diff-edits/types.ts b/evals/diff-edits/types.ts index a8005b40..f9715233 100644 --- a/evals/diff-edits/types.ts +++ b/evals/diff-edits/types.ts @@ -29,6 +29,7 @@ export interface TestConfig { model_id: string system_prompt_name: string number_of_runs: number + max_attempts_per_case: number parsing_function: string diff_edit_function: string thinking_tokens_budget: number @@ -103,4 +104,5 @@ export interface TestInput { thinkingBudgetTokens: number originalDiffEditToolCallMessage?: string diffApplyFile?: string + isVerbose: boolean } From 4569300f00818d7d542a1d24cb4d897503c3e4f5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 3 Jul 2025 15:06:57 -0700 Subject: [PATCH 08/43] v3.18.3 Release Notes (#4644) * changeset version bump * Updating CHANGELOG.md format * Update CHANGELOG.md for version 3.18.3 --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: github-actions Co-authored-by: Cline Evaluation --- .changeset/breezy-zebras-enjoy.md | 5 ----- .changeset/chilly-sheep-rhyme.md | 5 ----- .changeset/thirty-islands-admire.md | 5 ----- CHANGELOG.md | 5 +++++ package-lock.json | 4 ++-- package.json | 2 +- 6 files changed, 8 insertions(+), 18 deletions(-) delete mode 100644 .changeset/breezy-zebras-enjoy.md delete mode 100644 .changeset/chilly-sheep-rhyme.md delete mode 100644 .changeset/thirty-islands-admire.md diff --git a/.changeset/breezy-zebras-enjoy.md b/.changeset/breezy-zebras-enjoy.md deleted file mode 100644 index 336daede..00000000 --- a/.changeset/breezy-zebras-enjoy.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Improved eval framework with more logging and run options diff --git a/.changeset/chilly-sheep-rhyme.md b/.changeset/chilly-sheep-rhyme.md deleted file mode 100644 index 0edea60d..00000000 --- a/.changeset/chilly-sheep-rhyme.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Improve cerebras Qwen model performance by removing thinking tokens from the model input \ No newline at end of file diff --git a/.changeset/thirty-islands-admire.md b/.changeset/thirty-islands-admire.md deleted file mode 100644 index 46dcd347..00000000 --- a/.changeset/thirty-islands-admire.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Improve Claude Code handling diff --git a/CHANGELOG.md b/CHANGELOG.md index 92614d19..73516bfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [3.18.3] + +- Improve Cerebras Qwen model performance by removing thinking tokens from model input (Thanks @kevint-cerebras!) +- Improve Claude Code provider with better error handling and performance optimizations (Thanks @BarreiroT!) + ## [3.18.2] - Fix issue where terminal output would not be captured if shell integration fails by falling back to capturing the terminal content. diff --git a/package-lock.json b/package-lock.json index edcf9dad..c196726a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.2", + "version": "3.18.3", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.2", + "version": "3.18.3", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index bcd651bc..63611a5d 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.2", + "version": "3.18.3", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" From 2979d47e01e0eeb64b67d8b95bf9d9249dfc8320 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Thu, 3 Jul 2025 15:08:52 -0700 Subject: [PATCH 09/43] Replace cwd from the workspaceFolders with the host bridge. (#4645) Don't export cwd from task/index.ts. This top-level property cwd will be removed in a following PR because await cannot be used at the top-level. Use the hostbridge util getCwd() in createRuleFile.ts and refreshRules.ts instead of import the cwd from `task`. Add a util function to get the desktop directory instead of constructing it multiple places, update uses with the new function getDesktopDir() Replace function getCwd in FileContextTracker.ts with just getCwd from paths.ts. --- .../context-tracking/FileContextTracker.ts | 17 ++++------------- src/core/controller/file/createRuleFile.ts | 3 ++- src/core/controller/file/refreshRules.ts | 3 ++- src/core/task/index.ts | 11 +++++------ src/core/task/message-state.ts | 4 ++-- src/core/task/tools/autoApprove.ts | 4 ++-- src/integrations/checkpoints/CheckpointUtils.ts | 4 ++-- src/utils/path.ts | 6 +++++- 8 files changed, 24 insertions(+), 28 deletions(-) diff --git a/src/core/context/context-tracking/FileContextTracker.ts b/src/core/context/context-tracking/FileContextTracker.ts index a0bc5b07..a0d3fa36 100644 --- a/src/core/context/context-tracking/FileContextTracker.ts +++ b/src/core/context/context-tracking/FileContextTracker.ts @@ -36,17 +36,6 @@ export class FileContextTracker { this.taskId = taskId } - /** - * Gets the current working directory or returns undefined if it cannot be determined - */ - private async getCwd(): Promise { - const cwd = await getCwd(undefined) - if (!cwd) { - console.info("No workspace folder available - cannot determine current working directory") - } - return cwd - } - /** * File watchers are set up for each file that is tracked in the task metadata. */ @@ -56,8 +45,9 @@ export class FileContextTracker { return } - const cwd = await this.getCwd() + const cwd = await getCwd() if (!cwd) { + console.info("No workspace folder available - cannot determine current working directory") return } @@ -87,8 +77,9 @@ export class FileContextTracker { */ async trackFileContext(filePath: string, operation: "read_tool" | "user_edited" | "cline_edited" | "file_mentioned") { try { - const cwd = await this.getCwd() + const cwd = await getCwd() if (!cwd) { + console.info("No workspace folder available - cannot determine current working directory") return } diff --git a/src/core/controller/file/createRuleFile.ts b/src/core/controller/file/createRuleFile.ts index 30a2fdff..2c204603 100644 --- a/src/core/controller/file/createRuleFile.ts +++ b/src/core/controller/file/createRuleFile.ts @@ -6,8 +6,8 @@ import { createRuleFile as createRuleFileImpl } from "@core/context/instructions import * as vscode from "vscode" import * as path from "path" import { handleFileServiceRequest } from "./index" -import { cwd } from "@core/task" import { refreshWorkflowToggles } from "@/core/context/instructions/user-instructions/workflows" +import { getCwd, getDesktopDir } from "@/utils/path" /** * Creates a rule file in either global or workspace rules directory @@ -32,6 +32,7 @@ export const createRuleFile: FileMethodHandler = async (controller: Controller, throw new Error("Missing or invalid parameters") } + const cwd = await getCwd(getDesktopDir()) const { filePath, fileExists } = await createRuleFileImpl(request.isGlobal, request.filename, cwd, request.type) if (!filePath) { diff --git a/src/core/controller/file/refreshRules.ts b/src/core/controller/file/refreshRules.ts index f8c466ba..2c9e7a3e 100644 --- a/src/core/controller/file/refreshRules.ts +++ b/src/core/controller/file/refreshRules.ts @@ -4,7 +4,7 @@ import type { Controller } from "../index" import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules" import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules" import { refreshWorkflowToggles } from "@core/context/instructions/user-instructions/workflows" -import { cwd } from "@core/task" +import { getCwd, getDesktopDir } from "@/utils/path" /** * Refreshes all rule toggles (Cline, External, and Workflows) @@ -14,6 +14,7 @@ import { cwd } from "@core/task" */ export async function refreshRules(controller: Controller, _request: EmptyRequest): Promise { try { + const cwd = await getCwd(getDesktopDir()) const { globalToggles, localToggles } = await refreshClineRulesToggles(controller.context, cwd) const { cursorLocalToggles, windsurfLocalToggles } = await refreshExternalRulesToggles(controller.context, cwd) const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(controller.context, cwd) diff --git a/src/core/task/index.ts b/src/core/task/index.ts index b7bad52b..1bfda153 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -26,7 +26,8 @@ import { getApiMetrics } from "@shared/getApiMetrics" import { HistoryItem } from "@shared/HistoryItem" import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages" import { ClineAskResponse, ClineCheckpointRestore } from "@shared/WebviewMessage" -import { arePathsEqual } from "@utils/path" +import { getGitRemoteUrls } from "@utils/git" +import { arePathsEqual, getDesktopDir } from "@utils/path" import cloneDeep from "clone-deep" import { execa } from "execa" import { setTimeout as setTimeoutPromise } from "node:timers/promises" @@ -35,7 +36,6 @@ import pTimeout from "p-timeout" import pWaitFor from "p-wait-for" import * as path from "path" import * as vscode from "vscode" -import { getGitRemoteUrls } from "@utils/git" import { parseAssistantMessageV2, parseAssistantMessageV3, ToolUseName } from "@core/assistant-message" import { @@ -70,7 +70,7 @@ import { getSavedClineMessages, GlobalFileNames, } from "@core/storage/disk" -import { getGlobalState, getWorkspaceState } from "@core/storage/state" +import { getGlobalState } from "@core/storage/state" import { processFilesIntoText } from "@integrations/misc/extract-text" import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" import { McpHub } from "@services/mcp/McpHub" @@ -86,8 +86,7 @@ import { formatErrorWithStatusCode, updateApiReqMsg } from "./utils" export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false -export const cwd = - vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution +const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution export type ToolResponse = string | Array type UserContent = Array @@ -2572,7 +2571,7 @@ export class Task { if (includeFileDetails) { details += `\n\n# Current Working Directory (${cwd.toPosix()}) Files\n` - const isDesktop = arePathsEqual(cwd, path.join(os.homedir(), "Desktop")) + const isDesktop = arePathsEqual(cwd, getDesktopDir()) if (isDesktop) { // don't want to immediately access desktop since it would show permission popup details += "(Desktop files not shown automatically. Use list_files to explore if needed.)" diff --git a/src/core/task/message-state.ts b/src/core/task/message-state.ts index 04d794a9..29a651e1 100644 --- a/src/core/task/message-state.ts +++ b/src/core/task/message-state.ts @@ -12,7 +12,7 @@ import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker" import { HistoryItem } from "@/shared/HistoryItem" import Anthropic from "@anthropic-ai/sdk" import { TaskState } from "./TaskState" -import { getCwd } from "@/utils/path" +import { getCwd, getDesktopDir } from "@/utils/path" interface MessageStateHandlerParams { context: vscode.ExtensionContext @@ -83,7 +83,7 @@ export class MessageStateHandler { } catch (error) { console.error("Failed to get task directory size:", taskDir, error) } - const cwd = await getCwd(path.join(os.homedir(), "Desktop")) + const cwd = await getCwd(getDesktopDir()) await this.updateTaskHistory({ id: this.taskId, ts: lastRelevantMessage.ts, diff --git a/src/core/task/tools/autoApprove.ts b/src/core/task/tools/autoApprove.ts index 8150d4aa..ede57c14 100644 --- a/src/core/task/tools/autoApprove.ts +++ b/src/core/task/tools/autoApprove.ts @@ -2,7 +2,7 @@ import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { ToolUseName } from "@core/assistant-message" import * as path from "path" import os from "os" -import { getCwd } from "@/utils/path" +import { getCwd, getDesktopDir } from "@/utils/path" export class AutoApprove { autoApprovalSettings: AutoApprovalSettings @@ -54,7 +54,7 @@ export class AutoApprove { async shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): Promise { let isLocalRead: boolean = false if (autoApproveActionpath) { - const cwd = await getCwd(path.join(os.homedir(), "Desktop")) + const cwd = await getCwd(getDesktopDir()) const absolutePath = path.resolve(cwd, autoApproveActionpath) isLocalRead = absolutePath.startsWith(cwd) } else { diff --git a/src/integrations/checkpoints/CheckpointUtils.ts b/src/integrations/checkpoints/CheckpointUtils.ts index 36e58ea0..aab4c1d5 100644 --- a/src/integrations/checkpoints/CheckpointUtils.ts +++ b/src/integrations/checkpoints/CheckpointUtils.ts @@ -2,7 +2,7 @@ import { mkdir, access, constants } from "fs/promises" import * as path from "path" import * as vscode from "vscode" import os from "os" -import { getCwd } from "@/utils/path" +import { getCwd, getDesktopDir } from "@/utils/path" /** * Gets the path to the shadow Git repository in globalStorage. @@ -61,7 +61,7 @@ export async function getWorkingDirectory(): Promise { } const homedir = os.homedir() - const desktopPath = path.join(homedir, "Desktop") + const desktopPath = getDesktopDir() const documentsPath = path.join(homedir, "Documents") const downloadsPath = path.join(homedir, "Downloads") diff --git a/src/utils/path.ts b/src/utils/path.ts index fd1f85e7..c4a223ee 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -84,7 +84,7 @@ export function getReadablePath(cwd: string, relPath?: string): string { relPath = relPath || "" // path.resolve is flexible in that it will resolve relative paths like '../../' to the cwd and even ignore the cwd if the relPath is actually an absolute path const absolutePath = path.resolve(cwd, relPath) - if (arePathsEqual(cwd, path.join(os.homedir(), "Desktop"))) { + if (arePathsEqual(cwd, getDesktopDir())) { // User opened vscode without a workspace, so cwd is the Desktop. Show the full absolute path to keep the user aware of where files are being created return absolutePath.toPosix() } @@ -108,6 +108,10 @@ export const getCwd = async (defaultCwdPath = ""): Promise => { return workspaceFolders.paths.shift() || defaultCwdPath } +export function getDesktopDir() { + return path.join(os.homedir(), "Desktop") +} + // Returns the workspace path of the file in the current editor. // If there is no path, it returns the top level workspace directory. export const getWorkspacePath = async (defaultCwdPath = "") => { From 9578d7cde13927d4f7f764420010fbccdd491ecf Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Thu, 3 Jul 2025 15:36:08 -0700 Subject: [PATCH 10/43] Instead of getting the cwd from the workspaceFolders use the host bridge util getCwd() (#4647) Remove top-level property cwd task, await can't be used at the top level. Make cwd a class property, and pass the cwd into the constructor of task (await can't be used in the constructor either). --- src/core/controller/index.ts | 3 ++- src/core/task/index.ts | 44 ++++++++++++++++++------------------ 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 6e797a78..0c143a38 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -1,5 +1,5 @@ import { telemetryService } from "@/services/posthog/telemetry/TelemetryService" -import { getCwd } from "@/utils/path" +import { getCwd, getDesktopDir } from "@/utils/path" import { Anthropic } from "@anthropic-ai/sdk" import { buildApiHandler } from "@api/index" import { cleanupLegacyCheckpoints } from "@integrations/checkpoints/CheckpointMigration" @@ -179,6 +179,7 @@ export class Controller { terminalOutputLineLimit ?? 500, defaultTerminalProfile ?? "default", enableCheckpointsSetting ?? true, + await getCwd(getDesktopDir()), task, images, files, diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 1bfda153..2457c320 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -31,7 +31,6 @@ import { arePathsEqual, getDesktopDir } from "@utils/path" import cloneDeep from "clone-deep" import { execa } from "execa" import { setTimeout as setTimeoutPromise } from "node:timers/promises" -import os from "os" import pTimeout from "p-timeout" import pWaitFor from "p-wait-for" import * as path from "path" @@ -86,8 +85,6 @@ import { formatErrorWithStatusCode, updateApiReqMsg } from "./utils" export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false -const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution - export type ToolResponse = string | Array type UserContent = Array @@ -95,6 +92,7 @@ export class Task { // Core task variables readonly taskId: string private taskIsFavorited?: boolean + private cwd: string taskState: TaskState @@ -151,6 +149,7 @@ export class Task { terminalOutputLineLimit: number, defaultTerminalProfile: string, enableCheckpointsSetting: boolean, + cwd: string, task?: string, images?: string[], files?: string[], @@ -180,6 +179,7 @@ export class Task { this.browserSettings = browserSettings this.chatSettings = chatSettings this.enableCheckpoints = enableCheckpointsSetting + this.cwd = cwd // Set up MCP notification callback for real-time notifications this.mcpHub.setNotificationCallback(async (serverName: string, level: string, message: string) => { @@ -1096,7 +1096,7 @@ export class Task { const [taskResumptionMessage, userResponseMessage] = formatResponse.taskResumption( this.chatSettings?.mode === "plan" ? "plan" : "act", agoText, - cwd, + this.cwd, wasRecent, responseText, hasPendingFileContextWarnings, @@ -1327,7 +1327,7 @@ export class Task { // Create a child process const childProcess = execa(command, { shell: true, - cwd, + cwd: this.cwd, reject: false, all: true, // Merge stdout and stderr }) @@ -1404,7 +1404,7 @@ export class Task { } Logger.info("Executing command in VS code terminal: " + command) - const terminalInfo = await this.terminalManager.getOrCreateTerminal(cwd) + const terminalInfo = await this.terminalManager.getOrCreateTerminal(this.cwd) terminalInfo.terminal.show() // weird visual bug when creating new terminals (even manually) where there's an empty space at the top. const process = this.terminalManager.runCommand(terminalInfo, command) @@ -1580,7 +1580,7 @@ export class Task { const supportsBrowserUse = modelSupportsBrowserUse && !disableBrowserTool // only enable browser use if the model supports it and the user hasn't disabled it const isNextGenModel = isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api) - let systemPrompt = await SYSTEM_PROMPT(cwd, supportsBrowserUse, this.mcpHub, this.browserSettings, isNextGenModel) + let systemPrompt = await SYSTEM_PROMPT(this.cwd, supportsBrowserUse, this.mcpHub, this.browserSettings, isNextGenModel) await this.migratePreferredLanguageToolSetting() const preferredLanguage = getLanguageKey(this.chatSettings.preferredLanguage as LanguageDisplay) @@ -1589,18 +1589,18 @@ export class Task { ? `# Preferred Language\n\nSpeak in ${preferredLanguage}.` : "" - const { globalToggles, localToggles } = await refreshClineRulesToggles(this.getContext(), cwd) - const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.getContext(), cwd) + const { globalToggles, localToggles } = await refreshClineRulesToggles(this.getContext(), this.cwd) + const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.getContext(), this.cwd) const globalClineRulesFilePath = await ensureRulesDirectoryExists() const globalClineRulesFileInstructions = await getGlobalClineRules(globalClineRulesFilePath, globalToggles) - const localClineRulesFileInstructions = await getLocalClineRules(cwd, localToggles) + const localClineRulesFileInstructions = await getLocalClineRules(this.cwd, localToggles) const [localCursorRulesFileInstructions, localCursorRulesDirInstructions] = await getLocalCursorRules( - cwd, + this.cwd, cursorLocalToggles, ) - const localWindsurfRulesFileInstructions = await getLocalWindsurfRules(cwd, windsurfLocalToggles) + const localWindsurfRulesFileInstructions = await getLocalWindsurfRules(this.cwd, windsurfLocalToggles) const clineIgnoreContent = this.clineIgnoreController.clineIgnoreContent let clineIgnoreInstructions: string | undefined @@ -2356,7 +2356,7 @@ export class Task { // Track if we need to check clinerulesFile let needsClinerulesFileCheck = false - const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(this.getContext(), cwd) + const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(this.getContext(), this.cwd) const processUserContent = async () => { // This is a temporary solution to dynamically load context mentions from tool results. It checks for the presence of tags that indicate that the tool was rejected and feedback was provided (see formatToolDeniedFeedback, attemptCompletion, executeCommand, and consecutiveMistakeCount >= 3) or "" (see askFollowupQuestion), we place all user generated content in these tags so they can effectively be used as markers for when we should parse mentions). However if we allow multiple tools responses in the future, we will need to parse mentions specifically within the user content tags. @@ -2374,7 +2374,7 @@ export class Task { ) { const parsedText = await parseMentions( block.text, - cwd, + this.cwd, this.urlContentFetcher, this.fileContextTracker, ) @@ -2410,7 +2410,7 @@ export class Task { // After processing content, check clinerulesData if needed let clinerulesError = false if (needsClinerulesFileCheck) { - clinerulesError = await ensureLocalClineDirExists(cwd, GlobalFileNames.clineRules) + clinerulesError = await ensureLocalClineDirExists(this.cwd, GlobalFileNames.clineRules) } // Return all results @@ -2425,7 +2425,7 @@ export class Task { const visibleFilePaths = vscode.window.visibleTextEditors ?.map((editor) => editor.document?.uri?.fsPath) .filter(Boolean) - .map((absolutePath) => path.relative(cwd, absolutePath)) + .map((absolutePath) => path.relative(this.cwd, absolutePath)) // Filter paths through clineIgnoreController const allowedVisibleFiles = this.clineIgnoreController @@ -2444,7 +2444,7 @@ export class Task { .flatMap((group) => group.tabs) .map((tab) => (tab.input as vscode.TabInputText)?.uri?.fsPath) .filter(Boolean) - .map((absolutePath) => path.relative(cwd, absolutePath)) + .map((absolutePath) => path.relative(this.cwd, absolutePath)) // Filter paths through clineIgnoreController const allowedOpenTabs = this.clineIgnoreController @@ -2570,19 +2570,19 @@ export class Task { details += `\n\n# Current Time\n${formatter.format(now)} (${timeZone}, UTC${timeZoneOffsetStr})` if (includeFileDetails) { - details += `\n\n# Current Working Directory (${cwd.toPosix()}) Files\n` - const isDesktop = arePathsEqual(cwd, getDesktopDir()) + details += `\n\n# Current Working Directory (${this.cwd.toPosix()}) Files\n` + const isDesktop = arePathsEqual(this.cwd, getDesktopDir()) if (isDesktop) { // don't want to immediately access desktop since it would show permission popup details += "(Desktop files not shown automatically. Use list_files to explore if needed.)" } else { - const [files, didHitLimit] = await listFiles(cwd, true, 200) - const result = formatResponse.formatFilesList(cwd, files, didHitLimit, this.clineIgnoreController) + const [files, didHitLimit] = await listFiles(this.cwd, true, 200) + const result = formatResponse.formatFilesList(this.cwd, files, didHitLimit, this.clineIgnoreController) details += result } // Add git remote URLs section - const gitRemotes = await getGitRemoteUrls(cwd) + const gitRemotes = await getGitRemoteUrls(this.cwd) if (gitRemotes.length > 0) { details += `\n\n# Git Remote URLs\n${gitRemotes.join("\n")}` } From 172b46f1b0090235cd5c5f60489e8806563b7637 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Thu, 3 Jul 2025 15:36:21 -0700 Subject: [PATCH 11/43] Remove unused files *.bak (#4648) * Remove unused file Checkpoint-test-utils.ts.bak * Remove all .bak files from src/integrations --- .../checkpoints/Checkpoint-test-utils.ts.bak | 73 --------- .../checkpoints/CheckpointCommit.test.ts.bak | 155 ------------------ .../CheckpointCreation.test.ts.bak | 35 ---- .../checkpoints/CheckpointDiff.test.ts.bak | 68 -------- .../CheckpointDisabled.test.ts.bak | 94 ----------- .../checkpoints/CheckpointRevert.test.ts.bak | 95 ----------- .../CheckpointTaskSwitch.test.ts.bak | 120 -------------- 7 files changed, 640 deletions(-) delete mode 100644 src/integrations/checkpoints/Checkpoint-test-utils.ts.bak delete mode 100644 src/integrations/checkpoints/CheckpointCommit.test.ts.bak delete mode 100644 src/integrations/checkpoints/CheckpointCreation.test.ts.bak delete mode 100644 src/integrations/checkpoints/CheckpointDiff.test.ts.bak delete mode 100644 src/integrations/checkpoints/CheckpointDisabled.test.ts.bak delete mode 100644 src/integrations/checkpoints/CheckpointRevert.test.ts.bak delete mode 100644 src/integrations/checkpoints/CheckpointTaskSwitch.test.ts.bak diff --git a/src/integrations/checkpoints/Checkpoint-test-utils.ts.bak b/src/integrations/checkpoints/Checkpoint-test-utils.ts.bak deleted file mode 100644 index eff8f9e1..00000000 --- a/src/integrations/checkpoints/Checkpoint-test-utils.ts.bak +++ /dev/null @@ -1,73 +0,0 @@ -import * as vscode from "vscode" -import fs from "fs/promises" -import path from "path" -import os from "os" -import CheckpointTracker from "./CheckpointTracker" - -export async function createTestEnvironment() { - // Create temp directory structure - const tempDir = path.join(os.tmpdir(), `checkpoint-test-${Date.now()}`) - await fs.mkdir(tempDir, { recursive: true }) - - // Create storage path outside of working directory to avoid submodule issues - const globalStoragePath = path.join(os.tmpdir(), `storage-${Date.now()}`) - await fs.mkdir(globalStoragePath, { recursive: true }) - - // Create test file in a subdirectory - const testDir = path.join(tempDir, "src") - await fs.mkdir(testDir, { recursive: true }) - const testFilePath = path.join(testDir, "test.txt") - - // Create .gitignore to prevent git from treating directories as submodules - await fs.writeFile(path.join(tempDir, ".gitignore"), "storage/\n") - - // Mock VS Code workspace - const mockWorkspaceFolders = [ - { - uri: { fsPath: tempDir }, - name: "test", - index: 0, - }, - ] - - const originalDescriptor = Object.getOwnPropertyDescriptor(vscode.workspace, "workspaceFolders") - Object.defineProperty(vscode.workspace, "workspaceFolders", { - get: () => mockWorkspaceFolders, - }) - - // Mock findFiles to return no nested git repos - const originalFindFiles = vscode.workspace.findFiles - vscode.workspace.findFiles = async () => [] - - // Mock VS Code configuration - const originalGetConfiguration = vscode.workspace.getConfiguration - vscode.workspace.getConfiguration = () => - ({ - get: (key: string) => (key === "enableCheckpoints" ? true : undefined), - }) as any - - return { - tempDir, - globalStoragePath, - testFilePath, - originalDescriptor, - originalFindFiles, - originalGetConfiguration, - cleanup: async () => { - // Restore VS Code mocks - if (originalDescriptor) { - Object.defineProperty(vscode.workspace, "workspaceFolders", originalDescriptor) - } - vscode.workspace.getConfiguration = originalGetConfiguration - vscode.workspace.findFiles = originalFindFiles - - // Clean up temp directories - await fs.rm(tempDir, { recursive: true, force: true }) - await fs.rm(globalStoragePath, { recursive: true, force: true }) - } - } -} - -export async function createTestTracker(globalStoragePath?: string, taskId = "test-task-1") { - return await CheckpointTracker.create(taskId, globalStoragePath) -} diff --git a/src/integrations/checkpoints/CheckpointCommit.test.ts.bak b/src/integrations/checkpoints/CheckpointCommit.test.ts.bak deleted file mode 100644 index 88ad1ac8..00000000 --- a/src/integrations/checkpoints/CheckpointCommit.test.ts.bak +++ /dev/null @@ -1,155 +0,0 @@ -import { expect } from "chai" -import { describe, it, beforeEach, afterEach } from "mocha" -import fs from "fs/promises" -import path from "path" -import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils" - -describe("Checkpoint Commit Operations", () => { - let env: Awaited> - - beforeEach(async () => { - env = await createTestEnvironment() - }) - - afterEach(async () => { - await env.cleanup() - }) - - it("should create commit with single file changes", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create initial file - await fs.writeFile(env.testFilePath, "initial content") - - // Create first commit - const firstCommit = await tracker.commit() - expect(firstCommit).to.be.a("string").and.not.empty - - // Modify file - await fs.writeFile(env.testFilePath, "modified content") - - // Create second commit - const secondCommit = await tracker.commit() - expect(secondCommit).to.be.a("string").and.not.empty - expect(secondCommit).to.not.equal(firstCommit) - - // Verify commits are different - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - expect(diffSet).to.have.lengthOf(1) - expect(diffSet[0].before).to.equal("initial content") - expect(diffSet[0].after).to.equal("modified content") - }) - - it("should create commit with multiple file changes", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create initial files with newlines - const testFile2Path = path.join(env.tempDir, "src", "test2.txt") - await fs.writeFile(env.testFilePath, "file1 initial\n") - await fs.writeFile(testFile2Path, "file2 initial\n") - - // Create first commit - const firstCommit = await tracker.commit() - expect(firstCommit).to.be.a("string").and.not.empty - - // Modify both files with newlines - await fs.writeFile(env.testFilePath, "file1 modified\n") - await fs.writeFile(testFile2Path, "file2 modified\n") - - // Create second commit - const secondCommit = await tracker.commit() - expect(secondCommit).to.be.a("string").and.not.empty - expect(secondCommit).to.not.equal(firstCommit) - - // Get diff between commits - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - expect(diffSet).to.have.lengthOf(2) - - // Sort diffSet by path for consistent ordering - const sortedDiffs = diffSet.sort((a, b) => a.relativePath.localeCompare(b.relativePath)) - - // Verify file paths - expect(sortedDiffs[0].relativePath).to.equal("src/test.txt") - expect(sortedDiffs[1].relativePath).to.equal("src/test2.txt") - - // Verify file contents - expect(sortedDiffs[0].before).to.equal("file1 initial\n") - expect(sortedDiffs[0].after).to.equal("file1 modified\n") - expect(sortedDiffs[1].before).to.equal("file2 initial\n") - expect(sortedDiffs[1].after).to.equal("file2 modified\n") - }) - - it("should create commit when files are deleted", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create and commit initial file - await fs.writeFile(env.testFilePath, "initial content") - const firstCommit = await tracker.commit() - expect(firstCommit).to.be.a("string").and.not.empty - - // Delete file - await fs.unlink(env.testFilePath) - - // Create second commit - const secondCommit = await tracker.commit() - expect(secondCommit).to.be.a("string").and.not.empty - expect(secondCommit).to.not.equal(firstCommit) - - // Verify file deletion was committed - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - expect(diffSet).to.have.lengthOf(1) - expect(diffSet[0].before).to.equal("initial content") - expect(diffSet[0].after).to.equal("") - }) - - it("should create empty commit when no changes", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create and commit initial file - await fs.writeFile(env.testFilePath, "test content") - const firstCommit = await tracker.commit() - expect(firstCommit).to.be.a("string").and.not.empty - - // Create commit without changes - const secondCommit = await tracker.commit() - expect(secondCommit).to.be.a("string").and.not.empty - expect(secondCommit).to.not.equal(firstCommit) - - // Verify no changes between commits - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - expect(diffSet).to.have.lengthOf(0) - }) - - it("should handle files in nested directories", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create nested directory structure - const nestedDir = path.join(env.tempDir, "src", "deep", "nested") - await fs.mkdir(nestedDir, { recursive: true }) - const nestedFilePath = path.join(nestedDir, "nested.txt") - - // Create and commit file in nested directory - await fs.writeFile(nestedFilePath, "nested content") - const firstCommit = await tracker.commit() - expect(firstCommit).to.be.a("string").and.not.empty - - // Modify nested file - await fs.writeFile(nestedFilePath, "modified nested content") - - // Create second commit - const secondCommit = await tracker.commit() - expect(secondCommit).to.be.a("string").and.not.empty - - // Verify changes were committed - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - expect(diffSet).to.have.lengthOf(1) - expect(diffSet[0].relativePath).to.equal("src/deep/nested/nested.txt") - expect(diffSet[0].before).to.equal("nested content") - expect(diffSet[0].after).to.equal("modified nested content") - }) -}) diff --git a/src/integrations/checkpoints/CheckpointCreation.test.ts.bak b/src/integrations/checkpoints/CheckpointCreation.test.ts.bak deleted file mode 100644 index fd018f18..00000000 --- a/src/integrations/checkpoints/CheckpointCreation.test.ts.bak +++ /dev/null @@ -1,35 +0,0 @@ -import { expect } from "chai" -import { describe, it, beforeEach, afterEach } from "mocha" -import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils" -import CheckpointTracker from "./CheckpointTracker" - -describe("Checkpoint Creation", () => { - let env: Awaited> - - beforeEach(async () => { - env = await createTestEnvironment() - }) - - afterEach(async () => { - await env.cleanup() - }) - - it("should create a new checkpoint tracker", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - expect(tracker).to.not.be.undefined - expect(tracker).to.be.instanceOf(CheckpointTracker) - - // Verify shadow git config - const configWorkTree = await tracker?.getShadowGitConfigWorkTree() - expect(configWorkTree).to.not.be.undefined - }) - - it("should throw error when globalStoragePath is missing", async () => { - try { - await createTestTracker(undefined) - expect.fail("Expected error was not thrown") - } catch (error: any) { - expect(error.message).to.equal("Global storage path is required to create a checkpoint tracker") - } - }) -}) diff --git a/src/integrations/checkpoints/CheckpointDiff.test.ts.bak b/src/integrations/checkpoints/CheckpointDiff.test.ts.bak deleted file mode 100644 index 50318049..00000000 --- a/src/integrations/checkpoints/CheckpointDiff.test.ts.bak +++ /dev/null @@ -1,68 +0,0 @@ -import { expect } from "chai" -import { describe, it, beforeEach, afterEach } from "mocha" -import fs from "fs/promises" -import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils" - -describe("Checkpoint Diff Operations", () => { - let env: Awaited> - - beforeEach(async () => { - env = await createTestEnvironment() - }) - - afterEach(async () => { - await env.cleanup() - }) - - it("should detect file changes between commits", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create initial file - await fs.writeFile(env.testFilePath, "initial content") - - // Create first checkpoint - const firstCommit = await tracker.commit() - expect(firstCommit).to.not.be.undefined - - // Modify file - await fs.writeFile(env.testFilePath, "modified content") - - // Create second checkpoint - const secondCommit = await tracker.commit() - expect(secondCommit).to.not.be.undefined - - // Get diff between commits - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - - // Verify diff results - expect(diffSet).to.have.lengthOf(1) - expect(diffSet[0].relativePath).to.equal("src/test.txt") - expect(diffSet[0].before).to.equal("initial content") - expect(diffSet[0].after).to.equal("modified content") - }) - - it("should detect changes between commit and working directory", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create initial file - await fs.writeFile(env.testFilePath, "initial content") - - // Create checkpoint - const commit = await tracker.commit() - expect(commit).to.not.be.undefined - - // Modify file without committing - await fs.writeFile(env.testFilePath, "working directory changes") - - // Get diff between commit and working directory - const diffSet = await tracker.getDiffSet(commit) - - // Verify diff results - expect(diffSet).to.have.lengthOf(1) - expect(diffSet[0].relativePath).to.equal("src/test.txt") - expect(diffSet[0].before).to.equal("initial content") - expect(diffSet[0].after).to.equal("working directory changes") - }) -}) diff --git a/src/integrations/checkpoints/CheckpointDisabled.test.ts.bak b/src/integrations/checkpoints/CheckpointDisabled.test.ts.bak deleted file mode 100644 index 513104cc..00000000 --- a/src/integrations/checkpoints/CheckpointDisabled.test.ts.bak +++ /dev/null @@ -1,94 +0,0 @@ -import { expect } from "chai" -import { describe, it, beforeEach, afterEach } from "mocha" -import fs from "fs/promises" -import * as vscode from "vscode" -import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils" - -describe("Checkpoint Disabled State", () => { - let env: Awaited> - let originalGetConfiguration: typeof vscode.workspace.getConfiguration - - beforeEach(async () => { - env = await createTestEnvironment() - originalGetConfiguration = vscode.workspace.getConfiguration - - // Mock VS Code configuration to disable checkpoints - vscode.workspace.getConfiguration = () => - ({ - get: (key: string) => (key === "enableCheckpoints" ? false : undefined), - }) as any - }) - - afterEach(async () => { - await env.cleanup() - // Restore original configuration - vscode.workspace.getConfiguration = originalGetConfiguration - }) - - it("should return undefined when creating tracker", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - expect(tracker).to.be.undefined - }) - - it("should allow re-enabling checkpoints", async () => { - // First verify disabled state - const disabledTracker = await createTestTracker(env.globalStoragePath) - expect(disabledTracker).to.be.undefined - - // Mock configuration to enable checkpoints - vscode.workspace.getConfiguration = () => - ({ - get: (key: string) => (key === "enableCheckpoints" ? true : undefined), - }) as any - - // Verify tracker can be created when enabled - const enabledTracker = await createTestTracker(env.globalStoragePath) - expect(enabledTracker).to.not.be.undefined - - // Verify operations work - if (!enabledTracker) {throw new Error("Failed to create tracker")} - await fs.writeFile(env.testFilePath, "test content") - const commit = await enabledTracker.commit() - expect(commit).to.be.a("string").and.not.empty - }) - - it("should prevent operations when disabled mid-session", async () => { - // Start with checkpoints enabled - vscode.workspace.getConfiguration = () => - ({ - get: (key: string) => (key === "enableCheckpoints" ? true : undefined), - }) as any - - // Create tracker and initial commit - const tracker = await createTestTracker(env.globalStoragePath) - expect(tracker).to.not.be.undefined - if (!tracker) {throw new Error("Failed to create tracker")} - - await fs.writeFile(env.testFilePath, "initial content") - const firstCommit = await tracker.commit() - expect(firstCommit).to.be.a("string").and.not.empty - - // Disable checkpoints - vscode.workspace.getConfiguration = () => - ({ - get: (key: string) => (key === "enableCheckpoints" ? false : undefined), - }) as any - - // Verify new tracker cannot be created - const disabledTracker = await createTestTracker(env.globalStoragePath) - expect(disabledTracker).to.be.undefined - - // Verify existing tracker still works - // This is expected behavior since the tracker was created when enabled - await fs.writeFile(env.testFilePath, "modified content") - const secondCommit = await tracker.commit() - expect(secondCommit).to.be.a("string").and.not.empty - expect(secondCommit).to.not.equal(firstCommit) - - // Verify diffs still work on existing tracker - const diffSet = await tracker.getDiffSet(firstCommit, secondCommit) - expect(diffSet).to.have.lengthOf(1) - expect(diffSet[0].before).to.equal("initial content") - expect(diffSet[0].after).to.equal("modified content") - }) -}) diff --git a/src/integrations/checkpoints/CheckpointRevert.test.ts.bak b/src/integrations/checkpoints/CheckpointRevert.test.ts.bak deleted file mode 100644 index b8dbca3f..00000000 --- a/src/integrations/checkpoints/CheckpointRevert.test.ts.bak +++ /dev/null @@ -1,95 +0,0 @@ -import { expect } from "chai" -import { describe, it, beforeEach, afterEach } from "mocha" -import fs from "fs/promises" -import path from "path" -import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils" - -describe("Checkpoint Revert Operations", () => { - let env: Awaited> - - beforeEach(async () => { - env = await createTestEnvironment() - }) - - afterEach(async () => { - await env.cleanup() - }) - - it("should revert working directory to a previous checkpoint state", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create and commit initial state - await fs.writeFile(env.testFilePath, "initial content") - const firstCommit = await tracker.commit() - expect(firstCommit).to.not.be.undefined - - // Create and commit changes - await fs.writeFile(env.testFilePath, "modified content") - const secondCommit = await tracker.commit() - expect(secondCommit).to.not.be.undefined - - // Make more changes without committing - await fs.writeFile(env.testFilePath, "uncommitted changes") - - // Revert to first commit - await tracker.resetHead(firstCommit!) - - // Verify file content matches initial state - const resetContent = await fs.readFile(env.testFilePath, "utf8") - expect(resetContent).to.equal("initial content") - }) - - it("should handle reverting with multiple files", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create and commit initial state with multiple files - const testFile2Path = path.join(env.tempDir, "src", "test2.txt") - await fs.writeFile(env.testFilePath, "file1 initial") - await fs.writeFile(testFile2Path, "file2 initial") - const firstCommit = await tracker.commit() - expect(firstCommit).to.not.be.undefined - - // Modify both files and commit - await fs.writeFile(env.testFilePath, "file1 modified") - await fs.writeFile(testFile2Path, "file2 modified") - const secondCommit = await tracker.commit() - expect(secondCommit).to.not.be.undefined - - // Make more changes - await fs.writeFile(env.testFilePath, "file1 uncommitted") - await fs.writeFile(testFile2Path, "file2 uncommitted") - - // Reset to first commit - await tracker.resetHead(firstCommit!) - - // Verify both files match initial state - const file1Content = await fs.readFile(env.testFilePath, "utf8") - const file2Content = await fs.readFile(testFile2Path, "utf8") - expect(file1Content).to.equal("file1 initial") - expect(file2Content).to.equal("file2 initial") - }) - - it("should handle reverting when files are deleted", async () => { - const tracker = await createTestTracker(env.globalStoragePath) - if (!tracker) {throw new Error("Failed to create tracker")} - - // Create and commit initial state - await fs.writeFile(env.testFilePath, "initial content") - const firstCommit = await tracker.commit() - expect(firstCommit).to.not.be.undefined - - // Delete file and commit - await fs.unlink(env.testFilePath) - const secondCommit = await tracker.commit() - expect(secondCommit).to.not.be.undefined - - // Revert to first commit - await tracker.resetHead(firstCommit!) - - // Verify file is restored with original content - const resetContent = await fs.readFile(env.testFilePath, "utf8") - expect(resetContent).to.equal("initial content") - }) -}) diff --git a/src/integrations/checkpoints/CheckpointTaskSwitch.test.ts.bak b/src/integrations/checkpoints/CheckpointTaskSwitch.test.ts.bak deleted file mode 100644 index 3b9c203c..00000000 --- a/src/integrations/checkpoints/CheckpointTaskSwitch.test.ts.bak +++ /dev/null @@ -1,120 +0,0 @@ -import { expect } from "chai" -import { describe, it, beforeEach, afterEach } from "mocha" -import fs from "fs/promises" -import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils" -import { HistoryItem } from "../../shared/HistoryItem" -import CheckpointTracker from "./CheckpointTracker" - -describe("Checkpoint Task Switching", () => { - let env: Awaited> - let taskId1: string - let taskId2: string - let tracker1: CheckpointTracker | undefined - let tracker2: CheckpointTracker | undefined - - beforeEach(async () => { - env = await createTestEnvironment() - taskId1 = "task-1" - taskId2 = "task-2" - tracker1 = await createTestTracker(env.globalStoragePath, taskId1) - if (!tracker1) {throw new Error("Failed to create tracker1")} - }) - - afterEach(async () => { - await env.cleanup() - }) - - it("should maintain separate history for each task", async () => { - if (!tracker1) {throw new Error("Failed to create tracker1")} - - // Create and commit file in first task - await fs.writeFile(env.testFilePath, "task1 initial") - const task1Commit1 = await tracker1.commit() - expect(task1Commit1).to.be.a("string").and.not.empty - - // Modify and commit again in first task - await fs.writeFile(env.testFilePath, "task1 modified") - const task1Commit2 = await tracker1.commit() - expect(task1Commit2).to.be.a("string").and.not.empty - - // Create second task tracker - tracker2 = await createTestTracker(env.globalStoragePath, taskId2) - if (!tracker2) {throw new Error("Failed to create tracker2")} - - // Create and commit file in second task - await fs.writeFile(env.testFilePath, "task2 initial") - const task2Commit1 = await tracker2.commit() - expect(task2Commit1).to.be.a("string").and.not.empty - - // Create another commit to establish history - await fs.writeFile(env.testFilePath, "task2 modified") - const task2Commit2 = await tracker2.commit() - expect(task2Commit2).to.be.a("string").and.not.empty - - // Verify second task's history - const task2Diff = await tracker2.getDiffSet(task2Commit1, task2Commit2) - expect(task2Diff).to.have.lengthOf(1) - expect(task2Diff[0].before).to.equal("task2 initial") - expect(task2Diff[0].after).to.equal("task2 modified") - - // Switch back to first task by creating new tracker - const tracker1Again = await createTestTracker(env.globalStoragePath, taskId1) - if (!tracker1Again) {throw new Error("Failed to create tracker1Again")} - - // Verify first task's history is preserved - const task1Diff = await tracker1Again.getDiffSet(task1Commit1, task1Commit2) - expect(task1Diff[0].before).to.equal("task1 initial") - expect(task1Diff[0].after).to.equal("task1 modified") - - // Reset first task to initial state - if (!task1Commit1) {throw new Error("Failed to create initial commit")} - await tracker1Again.resetHead(task1Commit1) - const resetContent = await fs.readFile(env.testFilePath, "utf8") - expect(resetContent).to.equal("task1 initial") - }) - - it("should handle task deletion and recreation", async () => { - if (!tracker1) {throw new Error("Failed to create tracker1")} - - // Create and commit file in first task - await fs.writeFile(env.testFilePath, "task1 content") - const task1Commit = await tracker1.commit() - expect(task1Commit).to.be.a("string").and.not.empty - - // Create second task - tracker2 = await createTestTracker(env.globalStoragePath, taskId2) - if (!tracker2) {throw new Error("Failed to create tracker2")} - await fs.writeFile(env.testFilePath, "task2 content") - const task2Commit = await tracker2.commit() - expect(task2Commit).to.be.a("string").and.not.empty - - // Delete second task's checkpoints - const historyItem: HistoryItem = { - id: `test-${Date.now()}`, - ts: Date.now(), - task: taskId2, - shadowGitConfigWorkTree: env.tempDir, - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - } - await CheckpointTracker.deleteCheckpoints(taskId2, historyItem, env.globalStoragePath) - - // Recreate second task - const tracker2Again = await createTestTracker(env.globalStoragePath, taskId2) - if (!tracker2Again) {throw new Error("Failed to create tracker2Again")} - - // Create new commit in recreated task - await fs.writeFile(env.testFilePath, "task2 new content") - const newCommit = await tracker2Again.commit() - expect(newCommit).to.be.a("string").and.not.empty - - // Switch back to first task and verify its history is intact - const tracker1Again = await createTestTracker(env.globalStoragePath, taskId1) - if (!tracker1Again) {throw new Error("Failed to create tracker1Again")} - if (!task1Commit) {throw new Error("Failed to create initial commit")} - await tracker1Again.resetHead(task1Commit) - const resetContent = await fs.readFile(env.testFilePath, "utf8") - expect(resetContent).to.equal("task1 content") - }) -}) From 3248c3735858d2f13feaa965f11d08d426a63398 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Thu, 3 Jul 2025 15:53:53 -0700 Subject: [PATCH 12/43] Replace uses of vscode workspaceFolders with host bridge (#4649) * Instead of getting the cwd from the workspaceFolders use the host bridge util getCwd() Replace uses in integrations/claude-code/run.ts * Organize imports --- src/integrations/claude-code/run.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index 7838b27a..02793390 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -1,10 +1,8 @@ -import * as vscode from "vscode" +import { getCwd } from "@/utils/path" import type Anthropic from "@anthropic-ai/sdk" import { execa } from "execa" -import { ClaudeCodeMessage } from "./types" import readline from "readline" - -const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) +import { ClaudeCodeMessage } from "./types" type ClaudeCodeOptions = { systemPrompt: string @@ -22,7 +20,7 @@ type ProcessState = { } export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator { - const process = runProcess(options) + const process = runProcess(options, await getCwd()) const rl = readline.createInterface({ input: process.stdout, @@ -124,7 +122,7 @@ const CLAUDE_CODE_TIMEOUT = 600000 // 10 minutes // https://github.com/sindresorhus/execa/blob/main/docs/api.md#optionsmaxbuffer const BUFFER_SIZE = 20_000_000 // 20 MB -function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions) { +function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions, cwd: string) { const claudePath = path?.trim() || "claude" const args = [ From 4a2dad4552afc3856da91c58dfd6197d13c82a4c Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Thu, 3 Jul 2025 22:55:19 -0700 Subject: [PATCH 13/43] showOpenDialogue host bridge migration (#4651) * showOpenDialogue host bridge migration * addressing comments --------- Co-authored-by: Cline Evaluation --- proto/host/window.proto | 16 +++++++++++ src/hosts/vscode/window/showOpenDialogue.ts | 27 +++++++++++++++++++ src/integrations/misc/process-files.ts | 20 ++++++++------ .../runtime-files/vscode/vscode-stubs.js | 4 --- 4 files changed, 55 insertions(+), 12 deletions(-) create mode 100644 src/hosts/vscode/window/showOpenDialogue.ts diff --git a/proto/host/window.proto b/proto/host/window.proto index 820a78c5..19a39686 100644 --- a/proto/host/window.proto +++ b/proto/host/window.proto @@ -10,6 +10,7 @@ import "common.proto"; service WindowService { // Opens a text document in the editor and returns editor information. rpc showTextDocument(ShowTextDocumentRequest) returns (TextEditorInfo); + rpc showOpenDialogue(ShowOpenDialogueRequest) returns (SelectedResources); } message ShowTextDocumentRequest { @@ -30,3 +31,18 @@ message TextEditorInfo { optional int32 view_column = 2; bool is_active = 3; } + +message ShowOpenDialogueRequest { + cline.Metadata metadata = 1; + optional bool can_select_many = 2; + optional string open_label = 3; + optional ShowOpenDialogueFilterOption filters = 4; +} + +message ShowOpenDialogueFilterOption { + repeated string files = 1; +} + +message SelectedResources { + repeated string paths = 1; +} diff --git a/src/hosts/vscode/window/showOpenDialogue.ts b/src/hosts/vscode/window/showOpenDialogue.ts new file mode 100644 index 00000000..27163a47 --- /dev/null +++ b/src/hosts/vscode/window/showOpenDialogue.ts @@ -0,0 +1,27 @@ +import * as vscode from "vscode" +import { ShowOpenDialogueRequest, SelectedResources } from "@/shared/proto/host/window" + +export async function showOpenDialogue(request: ShowOpenDialogueRequest): Promise { + const options: vscode.OpenDialogOptions = {} + + if (request.canSelectMany !== undefined) { + options.canSelectMany = request.canSelectMany + } + + if (request.openLabel !== undefined) { + options.openLabel = request.openLabel + } + + if (request.filters?.files) { + options.filters = { + Files: request.filters.files, + } + } + + const selectedResources = await vscode.window.showOpenDialog(options) + + // Convert back to path format + return SelectedResources.create({ + paths: selectedResources ? selectedResources.map((uri) => uri.fsPath) : [], + }) +} diff --git a/src/integrations/misc/process-files.ts b/src/integrations/misc/process-files.ts index 5f9b2269..829bc8ce 100644 --- a/src/integrations/misc/process-files.ts +++ b/src/integrations/misc/process-files.ts @@ -2,6 +2,8 @@ import * as vscode from "vscode" import fs from "fs/promises" import * as path from "path" import sizeOf from "image-size" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowOpenDialogueRequest } from "@/shared/proto/host/window" /** * Supports processing of images and other file types @@ -11,15 +13,17 @@ export async function selectFiles(imagesAllowed: boolean): Promise<{ images: str const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp"] // supported by anthropic and openrouter const OTHER_FILE_EXTENSIONS = ["xml", "json", "txt", "log", "md", "docx", "ipynb", "pdf", "xlsx", "csv"] - const options: vscode.OpenDialogOptions = { - canSelectMany: true, - openLabel: "Select", - filters: { - Files: imagesAllowed ? [...IMAGE_EXTENSIONS, ...OTHER_FILE_EXTENSIONS] : OTHER_FILE_EXTENSIONS, - }, - } + const showDialogueResponse = await getHostBridgeProvider().windowClient.showOpenDialogue( + ShowOpenDialogueRequest.create({ + canSelectMany: true, + openLabel: "Select", + filters: { + files: imagesAllowed ? [...IMAGE_EXTENSIONS, ...OTHER_FILE_EXTENSIONS] : OTHER_FILE_EXTENSIONS, + }, + }), + ) - const fileUris = await vscode.window.showOpenDialog(options) + const fileUris = showDialogueResponse.paths.map((path) => vscode.Uri.file(path)) if (!fileUris || fileUris.length === 0) { return { images: [], files: [] } diff --git a/standalone/runtime-files/vscode/vscode-stubs.js b/standalone/runtime-files/vscode/vscode-stubs.js index 4d4bcc57..b2123d1f 100644 --- a/standalone/runtime-files/vscode/vscode-stubs.js +++ b/standalone/runtime-files/vscode/vscode-stubs.js @@ -672,10 +672,6 @@ vscode.window.showWorkspaceFolderPick = function (options) { console.log("Called stubbed function: vscode.window.showWorkspaceFolderPick") return Promise.resolve(null) } -vscode.window.showOpenDialog = function (options) { - console.log("Called stubbed function: vscode.window.showOpenDialog") - return [] -} vscode.window.showSaveDialog = function (options) { console.log("Called stubbed function: vscode.window.showSaveDialog") return Promise.resolve(null) From 1842254c571590b1a1bf26ec8c205c91768d0490 Mon Sep 17 00:00:00 2001 From: tjandy98 <3953059+tjandy98@users.noreply.github.com> Date: Sun, 6 Jul 2025 01:10:00 +0800 Subject: [PATCH 14/43] Add support for Gemini 2.5 Pro and Flash models to SAP AI Core Provider (#4655) * Add support for Gemini 2.5 Pro and Flash models Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> * Create calm-ads-glow.md --------- Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> --- .changeset/calm-ads-glow.md | 5 ++ src/api/providers/sapaicore.ts | 133 +++++++++++++++++++++++++++++++++ src/shared/api.ts | 36 +++++++++ 3 files changed, 174 insertions(+) create mode 100644 .changeset/calm-ads-glow.md diff --git a/.changeset/calm-ads-glow.md b/.changeset/calm-ads-glow.md new file mode 100644 index 00000000..dc24339c --- /dev/null +++ b/.changeset/calm-ads-glow.md @@ -0,0 +1,5 @@ +--- +"claude-dev": minor +--- + +Add support for Gemini 2.5 Pro and Flash to SAP AI Core Provider diff --git a/src/api/providers/sapaicore.ts b/src/api/providers/sapaicore.ts index 93724aa4..69e58f94 100644 --- a/src/api/providers/sapaicore.ts +++ b/src/api/providers/sapaicore.ts @@ -133,6 +133,8 @@ export class SapAiCoreHandler implements ApiHandler { const openAIModels = ["gpt-4o", "gpt-4", "gpt-4o-mini", "o1", "gpt-4.1", "gpt-4.1-nano", "o3-mini", "o3", "o4-mini"] + const geminiModels = ["gemini-2.5-flash", "gemini-2.5-pro"] + let url: string let payload: any if (anthropicModels.includes(model.id)) { @@ -187,6 +189,9 @@ export class SapAiCoreHandler implements ApiHandler { delete payload.stream delete payload.stream_options } + } else if (geminiModels.includes(model.id)) { + url = `${this.options.sapAiCoreBaseUrl}/v2/inference/deployments/${deploymentId}/models/${model.id}:streamGenerateContent` + payload = this.convertToGeminiFormat(systemPrompt, messages) } else { throw new Error(`Unsupported model: ${model.id}`) } @@ -233,6 +238,8 @@ export class SapAiCoreHandler implements ApiHandler { model.id === "anthropic--claude-3.7-sonnet" ) { yield* this.streamCompletionSonnet37(response.data, model) + } else if (geminiModels.includes(model.id)) { + yield* this.streamCompletionGemini(response.data, model) } else { yield* this.streamCompletion(response.data, model) } @@ -461,6 +468,88 @@ export class SapAiCoreHandler implements ApiHandler { } } + private async *streamCompletionGemini( + stream: any, + model: { id: SapAiCoreModelId; info: ModelInfo }, + ): AsyncGenerator { + let promptTokens = 0 + let outputTokens = 0 + let cacheReadTokens = 0 + let thoughtsTokenCount = 0 + + try { + for await (const chunk of stream) { + const lines = chunk.toString().split("\n").filter(Boolean) + for (const line of lines) { + if (line.startsWith("data: ")) { + const jsonData = line.slice(6) + try { + const data = JSON.parse(jsonData) + const candidateForThoughts = data?.candidates?.[0] + const partsForThoughts = candidateForThoughts?.content?.parts + let thoughts = "" + + if (partsForThoughts) { + for (const part of partsForThoughts) { + const { thought, text } = part + if (thought && text) { + thoughts += text + "\n" + } + } + } + + if (thoughts.trim() !== "") { + yield { + type: "reasoning", + reasoning: thoughts.trim(), + } + } + + if (data.text) { + yield { + type: "text", + text: data.text, + } + } + + if (data.candidates && data.candidates[0]?.content?.parts) { + for (const part of data.candidates[0].content.parts) { + if (part.text && !part.thought) { + // Only non-thought text + yield { + type: "text", + text: part.text, + } + } + } + } + + if (data.usageMetadata) { + promptTokens = data.usageMetadata.promptTokenCount ?? promptTokens + outputTokens = data.usageMetadata.candidatesTokenCount ?? outputTokens + thoughtsTokenCount = data.usageMetadata.thoughtsTokenCount ?? thoughtsTokenCount + cacheReadTokens = data.usageMetadata.cachedContentTokenCount ?? cacheReadTokens + + yield { + type: "usage", + inputTokens: promptTokens - cacheReadTokens, + outputTokens, + thoughtsTokenCount, + cacheReadTokens, + } + } + } catch (error) { + console.error("Failed to parse Gemini JSON data:", error) + } + } + } + } + } catch (error) { + console.error("Error streaming Gemini completion:", error) + throw error + } + } + createUserReadableRequest( userContent: Array< Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolUseBlockParam | Anthropic.ToolResultBlockParam @@ -495,6 +584,50 @@ export class SapAiCoreHandler implements ApiHandler { throw new Error(`Unsupported image format: ${format}`) } + private convertToGeminiFormat(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]) { + const contents = messages.map(this.convertAnthropicMessageToGemini) + + const payload = { + contents, + systemInstruction: { + parts: [ + { + text: systemPrompt, + }, + ], + }, + generationConfig: { + maxOutputTokens: this.getModel().info.maxTokens, + temperature: 0.0, + }, + } + + return payload + } + + private convertAnthropicMessageToGemini(message: Anthropic.Messages.MessageParam) { + const role = message.role === "assistant" ? "model" : "user" + const parts = [] + + if (typeof message.content === "string") { + parts.push({ text: message.content }) + } else if (Array.isArray(message.content)) { + for (const block of message.content) { + if (block.type === "text") { + parts.push({ text: block.text }) + } else if (block.type === "image") { + parts.push({ + inlineData: { + mimeType: block.source.media_type, + data: block.source.data, + }, + }) + } + } + } + + return { role, parts } + } private formatAnthropicMessages(messages: Anthropic.Messages.MessageParam[]): any[] { return messages.map((m) => { const contentBlocks: any[] = [] diff --git a/src/shared/api.ts b/src/shared/api.ts index 3026e3f8..8e7d983b 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -2374,6 +2374,42 @@ export const requestyDefaultModelInfo: ModelInfo = { export type SapAiCoreModelId = keyof typeof sapAiCoreModels export const sapAiCoreDefaultModelId: SapAiCoreModelId = "anthropic--claude-3.5-sonnet" export const sapAiCoreModels = { + "gemini-2.5-pro": { + maxTokens: 65536, + contextWindow: 1_048_576, + supportsImages: true, + supportsPromptCache: true, + inputPrice: 2.5, + outputPrice: 15, + cacheReadsPrice: 0.625, + tiers: [ + { + contextWindow: 200000, + inputPrice: 1.25, + outputPrice: 10, + cacheReadsPrice: 0.31, + }, + { + contextWindow: Infinity, + inputPrice: 2.5, + outputPrice: 15, + cacheReadsPrice: 0.625, + }, + ], + }, + "gemini-2.5-flash": { + maxTokens: 65536, + contextWindow: 1_048_576, + supportsImages: true, + supportsPromptCache: true, + inputPrice: 0.3, + outputPrice: 2.5, + cacheReadsPrice: 0.075, + thinkingConfig: { + maxBudget: 24576, + outputPrice: 3.5, + }, + }, "anthropic--claude-4-sonnet": { maxTokens: 8192, contextWindow: 200_000, From e84f2ff962f708a68390bc855cf9cd07228a3637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E5=A4=A9=E4=B8=80?= <120073078+faithleysath@users.noreply.github.com> Date: Sun, 6 Jul 2025 13:13:23 +0800 Subject: [PATCH 15/43] remove blur (#4664) --- webview-ui/src/components/history/HistoryPreview.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/webview-ui/src/components/history/HistoryPreview.tsx b/webview-ui/src/components/history/HistoryPreview.tsx index baabc17b..dc14e3b7 100644 --- a/webview-ui/src/components/history/HistoryPreview.tsx +++ b/webview-ui/src/components/history/HistoryPreview.tsx @@ -65,7 +65,6 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => { backgroundColor: "color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 30%, transparent)", border: "1px solid color-mix(in srgb, var(--vscode-panel-border) 50%, transparent)", - backdropFilter: "blur(8px)", }} onClick={() => handleHistorySelect(item.id)}> {/* Subtle gradient overlay for extra depth */} @@ -153,7 +152,6 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => { fontSize: "var(--vscode-font-size)", backgroundColor: "color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 20%, transparent)", border: "1px solid color-mix(in srgb, var(--vscode-panel-border) 30%, transparent)", - backdropFilter: "blur(8px)", }}> No recent tasks From 9e761cd1f0076e96e94d28f92a3a8e49b8aee782 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Sun, 6 Jul 2025 11:41:16 -0500 Subject: [PATCH 16/43] lazily initialize provider sdks with error catching (#4661) --- src/api/providers/__tests__/ollama.test.ts | 9 ++-- src/api/providers/anthropic.ts | 29 ++++++++--- src/api/providers/cerebras.ts | 33 ++++++++---- src/api/providers/cline.ts | 36 +++++++++---- src/api/providers/deepseek.ts | 26 +++++++--- src/api/providers/doubao.ts | 26 +++++++--- src/api/providers/fireworks.ts | 26 +++++++--- src/api/providers/gemini.ts | 53 ++++++++++++------- src/api/providers/litellm.ts | 29 ++++++++--- src/api/providers/lmstudio.ts | 23 ++++++--- src/api/providers/mistral.ts | 24 +++++++-- src/api/providers/nebius.ts | 27 +++++++--- src/api/providers/ollama.ts | 17 +++++-- src/api/providers/openai-native.ts | 28 +++++++--- src/api/providers/openai.ts | 58 +++++++++++++-------- src/api/providers/openrouter.ts | 34 +++++++++---- src/api/providers/qwen.ts | 32 ++++++++---- src/api/providers/requesty.ts | 34 +++++++++---- src/api/providers/sambanova.ts | 26 +++++++--- src/api/providers/together.ts | 26 +++++++--- src/api/providers/vertex.ts | 59 ++++++++++++++++------ src/api/providers/xai.ts | 26 +++++++--- 22 files changed, 493 insertions(+), 188 deletions(-) diff --git a/src/api/providers/__tests__/ollama.test.ts b/src/api/providers/__tests__/ollama.test.ts index 40f16a29..14200eaa 100644 --- a/src/api/providers/__tests__/ollama.test.ts +++ b/src/api/providers/__tests__/ollama.test.ts @@ -45,8 +45,10 @@ describe("OllamaHandler", () => { this.skip() } this.timeout(5000) + // Ensure client is initialized + const client = (handler as any).ensureClient() // Mock the Ollama client's chat method - const chatStub = sinon.stub(handler["client"], "chat").resolves({ + const chatStub = sinon.stub(client, "chat").resolves({ [Symbol.asyncIterator]: async function* () { yield { message: { content: "Hello, world!" }, @@ -139,8 +141,9 @@ describe("OllamaHandler", () => { // Restore real timers for this test clock.restore() - // Mock the Ollama client's chat method to fail on first call and succeed on second - const chatStub = sinon.stub(handler["client"], "chat") + // Ensure client is initialized and mock the Ollama client's chat method to fail on first call and succeed on second + const client = (handler as any).ensureClient() + const chatStub = sinon.stub(client, "chat") // First call throws an error chatStub.onFirstCall().rejects(new Error("API Error")) diff --git a/src/api/providers/anthropic.ts b/src/api/providers/anthropic.ts index 64178a0e..88a2e0a4 100644 --- a/src/api/providers/anthropic.ts +++ b/src/api/providers/anthropic.ts @@ -7,18 +7,33 @@ import { ApiStream } from "../transform/stream" export class AnthropicHandler implements ApiHandler { private options: ApiHandlerOptions - private client: Anthropic + private client: Anthropic | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new Anthropic({ - apiKey: this.options.apiKey, - baseURL: this.options.anthropicBaseUrl || undefined, - }) + } + + private ensureClient(): Anthropic { + if (!this.client) { + if (!this.options.apiKey) { + throw new Error("Anthropic API key is required") + } + try { + this.client = new Anthropic({ + apiKey: this.options.apiKey, + baseURL: this.options.anthropicBaseUrl || undefined, + }) + } catch (error) { + throw new Error(`Error creating Anthropic client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() + const model = this.getModel() let stream: AnthropicStream const modelId = model.id @@ -44,7 +59,7 @@ export class AnthropicHandler implements ApiHandler { ) const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1 const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1 - stream = await this.client.messages.create( + stream = await client.messages.create( { model: modelId, thinking: reasoningOn ? { type: "enabled", budget_tokens: budget_tokens } : undefined, @@ -118,7 +133,7 @@ export class AnthropicHandler implements ApiHandler { break } default: { - stream = await this.client.messages.create({ + stream = await client.messages.create({ model: modelId, max_tokens: model.info.maxTokens || 8192, temperature: 0, diff --git a/src/api/providers/cerebras.ts b/src/api/providers/cerebras.ts index 1576ba45..e6085837 100644 --- a/src/api/providers/cerebras.ts +++ b/src/api/providers/cerebras.ts @@ -7,26 +7,37 @@ import { ApiStream } from "@api/transform/stream" export class CerebrasHandler implements ApiHandler { private options: ApiHandlerOptions - private client: Cerebras + private client: Cerebras | undefined constructor(options: ApiHandlerOptions) { this.options = options + } - // Clean and validate the API key - const cleanApiKey = this.options.cerebrasApiKey?.trim() + private ensureClient(): Cerebras { + if (!this.client) { + // Clean and validate the API key + const cleanApiKey = this.options.cerebrasApiKey?.trim() - if (!cleanApiKey) { - throw new Error("Cerebras API key is required") + if (!cleanApiKey) { + throw new Error("Cerebras API key is required") + } + + try { + this.client = new Cerebras({ + apiKey: cleanApiKey, + timeout: 30000, // 30 second timeout + }) + } catch (error) { + throw new Error(`Error creating Cerebras client: ${error.message}`) + } } - - this.client = new Cerebras({ - apiKey: cleanApiKey, - timeout: 30000, // 30 second timeout - }) + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() + // Convert Anthropic messages to Cerebras format const cerebrasMessages: Array<{ role: "system" | "user" | "assistant" @@ -81,7 +92,7 @@ export class CerebrasHandler implements ApiHandler { } try { - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: this.getModel().id, messages: cerebrasMessages, temperature: 0, diff --git a/src/api/providers/cline.ts b/src/api/providers/cline.ts index 18aea6c0..1c535182 100644 --- a/src/api/providers/cline.ts +++ b/src/api/providers/cline.ts @@ -10,28 +10,42 @@ import { withRetry } from "../retry" export class ClineHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined lastGenerationId?: string constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://api.cline.bot/v1", - apiKey: this.options.clineApiKey || "", - defaultHeaders: { - "HTTP-Referer": "https://cline.bot", // Optional, for including your app on cline.bot rankings. - "X-Title": "Cline", // Optional. Shows in rankings on cline.bot. - "X-Task-ID": this.options.taskId || "", // Include the task ID in the request headers - }, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.clineApiKey) { + throw new Error("You don't seem to be logged in to a Cline account.") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.cline.bot/v1", + apiKey: this.options.clineApiKey || "", + defaultHeaders: { + "HTTP-Referer": "https://cline.bot", // Optional, for including your app on cline.bot rankings. + "X-Title": "Cline", // Optional. Shows in rankings on cline.bot. + "X-Task-ID": this.options.taskId || "", // Include the task ID in the request headers + }, + }) + } catch (error) { + throw new Error(`Error creating Cline client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() this.lastGenerationId = undefined const stream = await createOpenRouterStream( - this.client, + client, systemPrompt, messages, this.getModel(), diff --git a/src/api/providers/deepseek.ts b/src/api/providers/deepseek.ts index 33e22ca9..e4ec9981 100644 --- a/src/api/providers/deepseek.ts +++ b/src/api/providers/deepseek.ts @@ -10,14 +10,27 @@ import { convertToR1Format } from "../transform/r1-format" export class DeepSeekHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://api.deepseek.com/v1", - apiKey: this.options.deepSeekApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.deepSeekApiKey) { + throw new Error("DeepSeek API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.deepseek.com/v1", + apiKey: this.options.deepSeekApiKey, + }) + } catch (error) { + throw new Error(`Error creating DeepSeek client: ${error.message}`) + } + } + return this.client } private async *yieldUsage(info: ModelInfo, usage: OpenAI.Completions.CompletionUsage | undefined): ApiStream { @@ -54,6 +67,7 @@ export class DeepSeekHandler implements ApiHandler { @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() const isDeepseekReasoner = model.id.includes("deepseek-reasoner") @@ -67,7 +81,7 @@ export class DeepSeekHandler implements ApiHandler { openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) } - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, max_completion_tokens: model.info.maxTokens, messages: openAiMessages, diff --git a/src/api/providers/doubao.ts b/src/api/providers/doubao.ts index e38f9ef0..79eb71d0 100644 --- a/src/api/providers/doubao.ts +++ b/src/api/providers/doubao.ts @@ -8,13 +8,26 @@ import { withRetry } from "../retry" export class DoubaoHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://ark.cn-beijing.volces.com/api/v3/", - apiKey: this.options.doubaoApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.doubaoApiKey) { + throw new Error("Doubao API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://ark.cn-beijing.volces.com/api/v3/", + apiKey: this.options.doubaoApiKey, + }) + } catch (error) { + throw new Error(`Error creating Doubao client: ${error.message}`) + } + } + return this.client } getModel(): { id: DoubaoModelId; info: ModelInfo } { @@ -31,12 +44,13 @@ export class DoubaoHandler implements ApiHandler { @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ { role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages), ] - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, max_completion_tokens: model.info.maxTokens, messages: openAiMessages, diff --git a/src/api/providers/fireworks.ts b/src/api/providers/fireworks.ts index 48d4b6a4..206bab54 100644 --- a/src/api/providers/fireworks.ts +++ b/src/api/providers/fireworks.ts @@ -15,18 +15,32 @@ import { ApiStream } from "../transform/stream" export class FireworksHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://api.fireworks.ai/inference/v1", - apiKey: this.options.fireworksApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.fireworksApiKey) { + throw new Error("Fireworks API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.fireworks.ai/inference/v1", + apiKey: this.options.fireworksApiKey, + }) + } catch (error) { + throw new Error(`Error creating Fireworks client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const modelId = this.options.fireworksModelId ?? "" const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ @@ -34,7 +48,7 @@ export class FireworksHandler implements ApiHandler { ...convertToOpenAiMessages(messages), ] - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: modelId, ...(this.options.fireworksModelMaxCompletionTokens ? { max_completion_tokens: this.options.fireworksModelMaxCompletionTokens } diff --git a/src/api/providers/gemini.ts b/src/api/providers/gemini.ts index db7cc2a6..774d37d6 100644 --- a/src/api/providers/gemini.ts +++ b/src/api/providers/gemini.ts @@ -38,30 +38,45 @@ interface GeminiHandlerOptions extends ApiHandlerOptions { */ export class GeminiHandler implements ApiHandler { private options: ApiHandlerOptions - private client: GoogleGenAI + private client: GoogleGenAI | undefined constructor(options: GeminiHandlerOptions) { // Store the options this.options = options + } - if (options.isVertex) { - // Initialize with Vertex AI configuration - const project = this.options.vertexProjectId ?? "not-provided" - const location = this.options.vertexRegion ?? "not-provided" + private ensureClient(): GoogleGenAI { + if (!this.client) { + const options = this.options as GeminiHandlerOptions - this.client = new GoogleGenAI({ - vertexai: true, - project, - location, - }) - } else { - // Initialize with standard API key - if (!options.geminiApiKey) { - throw new Error("API key is required for Google Gemini when not using Vertex AI") + if (options.isVertex) { + // Initialize with Vertex AI configuration + const project = this.options.vertexProjectId ?? "not-provided" + const location = this.options.vertexRegion ?? "not-provided" + + try { + this.client = new GoogleGenAI({ + vertexai: true, + project, + location, + }) + } catch (error) { + throw new Error(`Error creating Gemini Vertex AI client: ${error.message}`) + } + } else { + // Initialize with standard API key + if (!options.geminiApiKey) { + throw new Error("API key is required for Google Gemini when not using Vertex AI") + } + + try { + this.client = new GoogleGenAI({ apiKey: options.geminiApiKey }) + } catch (error) { + throw new Error(`Error creating Gemini client: ${error.message}`) + } } - - this.client = new GoogleGenAI({ apiKey: options.geminiApiKey }) } + return this.client } /** @@ -80,6 +95,7 @@ export class GeminiHandler implements ApiHandler { maxDelay: 15000, }) async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const { id: modelId, info } = this.getModel() const contents = messages.map(convertAnthropicMessageToGemini) @@ -117,7 +133,7 @@ export class GeminiHandler implements ApiHandler { let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined try { - const result = await this.client.models.generateContentStream({ + const result = await client.models.generateContentStream({ model: modelId, contents: contents, config: { @@ -351,6 +367,7 @@ export class GeminiHandler implements ApiHandler { */ async countTokens(content: Array): Promise { try { + const client = this.ensureClient() const { id: model } = this.getModel() // Convert content to Gemini format @@ -362,7 +379,7 @@ export class GeminiHandler implements ApiHandler { }) // Use Gemini's token counting API - const response = await this.client.models.countTokens({ + const response = await client.models.countTokens({ model, contents: [{ parts: geminiContent }], }) diff --git a/src/api/providers/litellm.ts b/src/api/providers/litellm.ts index 3e6eda39..d67f89b5 100644 --- a/src/api/providers/litellm.ts +++ b/src/api/providers/litellm.ts @@ -8,21 +8,35 @@ import { withRetry } from "../retry" export class LiteLlmHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: this.options.liteLlmBaseUrl || "http://localhost:4000", - apiKey: this.options.liteLlmApiKey || "noop", - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.liteLlmApiKey) { + throw new Error("LiteLLM API key is required") + } + try { + this.client = new OpenAI({ + baseURL: this.options.liteLlmBaseUrl || "http://localhost:4000", + apiKey: this.options.liteLlmApiKey || "noop", + }) + } catch (error) { + throw new Error(`Error creating LiteLLM client: ${error.message}`) + } + } + return this.client } async calculateCost(prompt_tokens: number, completion_tokens: number): Promise { // Reference: https://github.com/BerriAI/litellm/blob/122ee634f434014267af104814022af1d9a0882f/litellm/proxy/spend_tracking/spend_management_endpoints.py#L1473 + const client = this.ensureClient() const modelId = this.options.liteLlmModelId || liteLlmDefaultModelId try { - const response = await fetch(`${this.client.baseURL}/spend/calculate`, { + const response = await fetch(`${client.baseURL}/spend/calculate`, { method: "POST", headers: { "Content-Type": "application/json", @@ -54,6 +68,7 @@ export class LiteLlmHandler implements ApiHandler { @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const formattedMessages = convertToOpenAiMessages(messages) const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = { role: "system", @@ -101,7 +116,7 @@ export class LiteLlmHandler implements ApiHandler { return message }) - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: this.options.liteLlmModelId || liteLlmDefaultModelId, messages: [enhancedSystemMessage, ...enhancedMessages], temperature, diff --git a/src/api/providers/lmstudio.ts b/src/api/providers/lmstudio.ts index 5483a5b3..6c2d0c52 100644 --- a/src/api/providers/lmstudio.ts +++ b/src/api/providers/lmstudio.ts @@ -8,25 +8,36 @@ import { withRetry } from "../retry" export class LmStudioHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: (this.options.lmStudioBaseUrl || "http://localhost:1234") + "/v1", - apiKey: "noop", - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + try { + this.client = new OpenAI({ + baseURL: (this.options.lmStudioBaseUrl || "http://localhost:1234") + "/v1", + apiKey: "noop", + }) + } catch (error) { + throw new Error(`Error creating LM Studio client: ${error.message}`) + } + } + return this.client } @withRetry({ retryAllErrors: true }) async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ { role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages), ] try { - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: this.getModel().id, messages: openAiMessages, stream: true, diff --git a/src/api/providers/mistral.ts b/src/api/providers/mistral.ts index b1ece0d9..b7aaf83e 100644 --- a/src/api/providers/mistral.ts +++ b/src/api/providers/mistral.ts @@ -8,18 +8,32 @@ import { ApiStream } from "../transform/stream" export class MistralHandler implements ApiHandler { private options: ApiHandlerOptions - private client: Mistral + private client: Mistral | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new Mistral({ - apiKey: this.options.mistralApiKey, - }) + } + + private ensureClient(): Mistral { + if (!this.client) { + if (!this.options.mistralApiKey) { + throw new Error("Mistral API key is required") + } + try { + this.client = new Mistral({ + apiKey: this.options.mistralApiKey, + }) + } catch (error) { + throw new Error(`Error creating Mistral client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { - const stream = await this.client.chat + const client = this.ensureClient() + const stream = await client.chat .stream({ model: this.getModel().id, // max_completion_tokens: this.getModel().info.maxTokens, diff --git a/src/api/providers/nebius.ts b/src/api/providers/nebius.ts index ad3b694f..d28bf9c9 100644 --- a/src/api/providers/nebius.ts +++ b/src/api/providers/nebius.ts @@ -8,24 +8,37 @@ import { convertToR1Format } from "../transform/r1-format" import { nebiusDefaultModelId, nebiusModels, type ModelInfo, type ApiHandlerOptions, type NebiusModelId } from "../../shared/api" export class NebiusHandler implements ApiHandler { - private client: OpenAI + private client: OpenAI | undefined - constructor(private readonly options: ApiHandlerOptions) { - this.client = new OpenAI({ - baseURL: "https://api.studio.nebius.ai/v1", - apiKey: this.options.nebiusApiKey, - }) + constructor(private readonly options: ApiHandlerOptions) {} + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.nebiusApiKey) { + throw new Error("Nebius API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.studio.nebius.ai/v1", + apiKey: this.options.nebiusApiKey, + }) + } catch (error) { + throw new Error(`Error creating Nebius client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = model.id.includes("DeepSeek-R1") ? convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) : [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)] - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, messages: openAiMessages, temperature: 0, diff --git a/src/api/providers/ollama.ts b/src/api/providers/ollama.ts index 3cfdf4b3..ebeacdbb 100644 --- a/src/api/providers/ollama.ts +++ b/src/api/providers/ollama.ts @@ -8,15 +8,26 @@ import { withRetry } from "../retry" export class OllamaHandler implements ApiHandler { private options: ApiHandlerOptions - private client: Ollama + private client: Ollama | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new Ollama({ host: this.options.ollamaBaseUrl || "http://localhost:11434" }) + } + + private ensureClient(): Ollama { + if (!this.client) { + try { + this.client = new Ollama({ host: this.options.ollamaBaseUrl || "http://localhost:11434" }) + } catch (error) { + throw new Error(`Error creating Ollama client: ${error.message}`) + } + } + return this.client } @withRetry({ retryAllErrors: true }) async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const ollamaMessages: Message[] = [{ role: "system", content: systemPrompt }, ...convertToOllamaMessages(messages)] try { @@ -27,7 +38,7 @@ export class OllamaHandler implements ApiHandler { }) // Create the actual API request promise - const apiPromise = this.client.chat({ + const apiPromise = client.chat({ model: this.getModel().id, messages: ollamaMessages, stream: true, diff --git a/src/api/providers/openai-native.ts b/src/api/providers/openai-native.ts index d1429944..3c5f85c6 100644 --- a/src/api/providers/openai-native.ts +++ b/src/api/providers/openai-native.ts @@ -10,13 +10,26 @@ import type { ChatCompletionReasoningEffort } from "openai/resources/chat/comple export class OpenAiNativeHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - apiKey: this.options.openAiNativeApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.openAiNativeApiKey) { + throw new Error("OpenAI API key is required") + } + try { + this.client = new OpenAI({ + apiKey: this.options.openAiNativeApiKey, + }) + } catch (error: any) { + throw new Error(`Error creating OpenAI client: ${error.message}`) + } + } + return this.client } private async *yieldUsage(info: ModelInfo, usage: OpenAI.Completions.CompletionUsage | undefined): ApiStream { @@ -38,6 +51,7 @@ export class OpenAiNativeHandler implements ApiHandler { @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() switch (model.id) { @@ -45,7 +59,7 @@ export class OpenAiNativeHandler implements ApiHandler { case "o1-preview": case "o1-mini": { // o1 doesn't support streaming, non-1 temp, or system prompt - const response = await this.client.chat.completions.create({ + const response = await client.chat.completions.create({ model: model.id, messages: [{ role: "user", content: systemPrompt }, ...convertToOpenAiMessages(messages)], }) @@ -61,7 +75,7 @@ export class OpenAiNativeHandler implements ApiHandler { case "o4-mini": case "o3": case "o3-mini": { - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, messages: [{ role: "developer", content: systemPrompt }, ...convertToOpenAiMessages(messages)], stream: true, @@ -85,7 +99,7 @@ export class OpenAiNativeHandler implements ApiHandler { break } default: { - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, // max_completion_tokens: this.getModel().info.maxTokens, temperature: 0, diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index 3af8c9dc..f93a8fde 100644 --- a/src/api/providers/openai.ts +++ b/src/api/providers/openai.ts @@ -10,35 +10,49 @@ import type { ChatCompletionReasoningEffort } from "openai/resources/chat/comple export class OpenAiHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - // Azure API shape slightly differs from the core API shape: https://github.com/openai/openai-node?tab=readme-ov-file#microsoft-azure-openai - // Use azureApiVersion to determine if this is an Azure endpoint, since the URL may not always contain 'azure.com' - if ( - this.options.azureApiVersion || - ((this.options.openAiBaseUrl?.toLowerCase().includes("azure.com") || - this.options.openAiBaseUrl?.toLowerCase().includes("azure.us")) && - !this.options.openAiModelId?.toLowerCase().includes("deepseek")) - ) { - this.client = new AzureOpenAI({ - baseURL: this.options.openAiBaseUrl, - apiKey: this.options.openAiApiKey, - apiVersion: this.options.azureApiVersion || azureOpenAiDefaultApiVersion, - defaultHeaders: this.options.openAiHeaders, - }) - } else { - this.client = new OpenAI({ - baseURL: this.options.openAiBaseUrl, - apiKey: this.options.openAiApiKey, - defaultHeaders: this.options.openAiHeaders, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.openAiApiKey) { + throw new Error("OpenAI API key is required") + } + try { + // Azure API shape slightly differs from the core API shape: https://github.com/openai/openai-node?tab=readme-ov-file#microsoft-azure-openai + // Use azureApiVersion to determine if this is an Azure endpoint, since the URL may not always contain 'azure.com' + if ( + this.options.azureApiVersion || + ((this.options.openAiBaseUrl?.toLowerCase().includes("azure.com") || + this.options.openAiBaseUrl?.toLowerCase().includes("azure.us")) && + !this.options.openAiModelId?.toLowerCase().includes("deepseek")) + ) { + this.client = new AzureOpenAI({ + baseURL: this.options.openAiBaseUrl, + apiKey: this.options.openAiApiKey, + apiVersion: this.options.azureApiVersion || azureOpenAiDefaultApiVersion, + defaultHeaders: this.options.openAiHeaders, + }) + } else { + this.client = new OpenAI({ + baseURL: this.options.openAiBaseUrl, + apiKey: this.options.openAiApiKey, + defaultHeaders: this.options.openAiHeaders, + }) + } + } catch (error: any) { + throw new Error(`Error creating OpenAI client: ${error.message}`) + } } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const modelId = this.options.openAiModelId ?? "" const isDeepseekReasoner = modelId.includes("deepseek-reasoner") const isR1FormatRequired = this.options.openAiModelInfo?.isR1FormatRequired ?? false @@ -68,7 +82,7 @@ export class OpenAiHandler implements ApiHandler { reasoningEffort = (this.options.reasoningEffort as ChatCompletionReasoningEffort) || "medium" } - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: modelId, messages: openAiMessages, temperature, diff --git a/src/api/providers/openrouter.ts b/src/api/providers/openrouter.ts index 6476b308..4fbd64ad 100644 --- a/src/api/providers/openrouter.ts +++ b/src/api/providers/openrouter.ts @@ -11,27 +11,41 @@ import { OpenRouterErrorResponse } from "./types" export class OpenRouterHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined lastGenerationId?: string constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://openrouter.ai/api/v1", - apiKey: this.options.openRouterApiKey, - defaultHeaders: { - "HTTP-Referer": "https://cline.bot", // Optional, for including your app on openrouter.ai rankings. - "X-Title": "Cline", // Optional. Shows in rankings on openrouter.ai. - }, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.openRouterApiKey) { + throw new Error("OpenRouter API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://openrouter.ai/api/v1", + apiKey: this.options.openRouterApiKey, + defaultHeaders: { + "HTTP-Referer": "https://cline.bot", // Optional, for including your app on openrouter.ai rankings. + "X-Title": "Cline", // Optional. Shows in rankings on openrouter.ai. + }, + }) + } catch (error: any) { + throw new Error(`Error creating OpenRouter client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() this.lastGenerationId = undefined const stream = await createOpenRouterStream( - this.client, + client, systemPrompt, messages, this.getModel(), diff --git a/src/api/providers/qwen.ts b/src/api/providers/qwen.ts index 34dd1c9b..ac47d9d4 100644 --- a/src/api/providers/qwen.ts +++ b/src/api/providers/qwen.ts @@ -18,17 +18,30 @@ import { withRetry } from "../retry" export class QwenHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: - this.options.qwenApiLine === "china" - ? "https://dashscope.aliyuncs.com/compatible-mode/v1" - : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", - apiKey: this.options.qwenApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.qwenApiKey) { + throw new Error("Alibaba API key is required") + } + try { + this.client = new OpenAI({ + baseURL: + this.options.qwenApiLine === "china" + ? "https://dashscope.aliyuncs.com/compatible-mode/v1" + : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", + apiKey: this.options.qwenApiKey, + }) + } catch (error: any) { + throw new Error(`Error creating Alibaba client: ${error.message}`) + } + } + return this.client } getModel(): { id: MainlandQwenModelId | InternationalQwenModelId; info: ModelInfo } { @@ -51,6 +64,7 @@ export class QwenHandler implements ApiHandler { @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() const isDeepseekReasoner = model.id.includes("deepseek-r1") const isReasoningModelFamily = model.id.includes("qwen3") || ["qwen-plus-latest", "qwen-turbo-latest"].includes(model.id) @@ -76,7 +90,7 @@ export class QwenHandler implements ApiHandler { temperature = undefined } - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, max_completion_tokens: model.info.maxTokens, messages: openAiMessages, diff --git a/src/api/providers/requesty.ts b/src/api/providers/requesty.ts index 21bc9a64..a4888132 100644 --- a/src/api/providers/requesty.ts +++ b/src/api/providers/requesty.ts @@ -19,22 +19,36 @@ interface RequestyUsage extends OpenAI.CompletionUsage { export class RequestyHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://router.requesty.ai/v1", - apiKey: this.options.requestyApiKey, - defaultHeaders: { - "HTTP-Referer": "https://cline.bot", - "X-Title": "Cline", - }, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.requestyApiKey) { + throw new Error("Requesty API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://router.requesty.ai/v1", + apiKey: this.options.requestyApiKey, + defaultHeaders: { + "HTTP-Referer": "https://cline.bot", + "X-Title": "Cline", + }, + }) + } catch (error: any) { + throw new Error(`Error creating Requesty client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ @@ -57,7 +71,7 @@ export class RequestyHandler implements ApiHandler { : {} // @ts-ignore-next-line - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: model.id, max_tokens: model.info.maxTokens || undefined, messages: openAiMessages, diff --git a/src/api/providers/sambanova.ts b/src/api/providers/sambanova.ts index 8e172b8d..e53e90cb 100644 --- a/src/api/providers/sambanova.ts +++ b/src/api/providers/sambanova.ts @@ -9,18 +9,32 @@ import { convertToR1Format } from "@api/transform/r1-format" export class SambanovaHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://api.sambanova.ai/v1", - apiKey: this.options.sambanovaApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.sambanovaApiKey) { + throw new Error("SambaNova API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.sambanova.ai/v1", + apiKey: this.options.sambanovaApiKey, + }) + } catch (error: any) { + throw new Error(`Error creating SambaNova client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const model = this.getModel() let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ @@ -34,7 +48,7 @@ export class SambanovaHandler implements ApiHandler { openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) } - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: this.getModel().id, messages: openAiMessages, temperature: 0, diff --git a/src/api/providers/together.ts b/src/api/providers/together.ts index 8b4b5f27..132afba8 100644 --- a/src/api/providers/together.ts +++ b/src/api/providers/together.ts @@ -9,18 +9,32 @@ import { convertToR1Format } from "@api/transform/r1-format" export class TogetherHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://api.together.xyz/v1", - apiKey: this.options.togetherApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.togetherApiKey) { + throw new Error("Together API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.together.xyz/v1", + apiKey: this.options.togetherApiKey, + }) + } catch (error: any) { + throw new Error(`Error creating Together client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const modelId = this.options.togetherModelId ?? "" const isDeepseekReasoner = modelId.includes("deepseek-reasoner") @@ -33,7 +47,7 @@ export class TogetherHandler implements ApiHandler { openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) } - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: modelId, messages: openAiMessages, temperature: 0, diff --git a/src/api/providers/vertex.ts b/src/api/providers/vertex.ts index 8e97a10d..b421d703 100644 --- a/src/api/providers/vertex.ts +++ b/src/api/providers/vertex.ts @@ -7,25 +7,49 @@ import { ApiStream } from "@api/transform/stream" import { GeminiHandler } from "./gemini" export class VertexHandler implements ApiHandler { - private geminiHandler: GeminiHandler - private clientAnthropic: AnthropicVertex + private geminiHandler: GeminiHandler | undefined + private clientAnthropic: AnthropicVertex | undefined private options: ApiHandlerOptions constructor(options: ApiHandlerOptions) { this.options = options + } - // Create a GeminiHandler with isVertex flag for Gemini models - this.geminiHandler = new GeminiHandler({ - ...options, - isVertex: true, - }) + private ensureGeminiHandler(): GeminiHandler { + if (!this.geminiHandler) { + try { + // Create a GeminiHandler with isVertex flag for Gemini models + this.geminiHandler = new GeminiHandler({ + ...this.options, + isVertex: true, + }) + } catch (error: any) { + throw new Error(`Error creating Vertex AI Gemini handler: ${error.message}`) + } + } + return this.geminiHandler + } - // Initialize Anthropic client for Claude models - this.clientAnthropic = new AnthropicVertex({ - projectId: this.options.vertexProjectId, - // https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude#regions - region: this.options.vertexRegion, - }) + private ensureAnthropicClient(): AnthropicVertex { + if (!this.clientAnthropic) { + if (!this.options.vertexProjectId) { + throw new Error("Vertex AI project ID is required") + } + if (!this.options.vertexRegion) { + throw new Error("Vertex AI region is required") + } + try { + // Initialize Anthropic client for Claude models + this.clientAnthropic = new AnthropicVertex({ + projectId: this.options.vertexProjectId, + // https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude#regions + region: this.options.vertexRegion, + }) + } catch (error: any) { + throw new Error(`Error creating Vertex AI Anthropic client: ${error.message}`) + } + } + return this.clientAnthropic } @withRetry() @@ -35,10 +59,13 @@ export class VertexHandler implements ApiHandler { // For Gemini models, use the GeminiHandler if (!modelId.includes("claude")) { - yield* this.geminiHandler.createMessage(systemPrompt, messages) + const geminiHandler = this.ensureGeminiHandler() + yield* geminiHandler.createMessage(systemPrompt, messages) return } + const clientAnthropic = this.ensureAnthropicClient() + // Claude implementation let budget_tokens = this.options.thinkingBudgetTokens || 0 const reasoningOn = @@ -63,7 +90,7 @@ export class VertexHandler implements ApiHandler { ) const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1 const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1 - stream = await this.clientAnthropic.beta.messages.create( + stream = await clientAnthropic.beta.messages.create( { model: modelId, max_tokens: model.info.maxTokens || 8192, @@ -125,7 +152,7 @@ export class VertexHandler implements ApiHandler { break } default: { - stream = await this.clientAnthropic.beta.messages.create({ + stream = await clientAnthropic.beta.messages.create({ model: modelId, max_tokens: model.info.maxTokens || 8192, temperature: 0, diff --git a/src/api/providers/xai.ts b/src/api/providers/xai.ts index 1781ca76..4af7b7b5 100644 --- a/src/api/providers/xai.ts +++ b/src/api/providers/xai.ts @@ -9,18 +9,32 @@ import { withRetry } from "../retry" export class XAIHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI + private client: OpenAI | undefined constructor(options: ApiHandlerOptions) { this.options = options - this.client = new OpenAI({ - baseURL: "https://api.x.ai/v1", - apiKey: this.options.xaiApiKey, - }) + } + + private ensureClient(): OpenAI { + if (!this.client) { + if (!this.options.xaiApiKey) { + throw new Error("xAI API key is required") + } + try { + this.client = new OpenAI({ + baseURL: "https://api.x.ai/v1", + apiKey: this.options.xaiApiKey, + }) + } catch (error: any) { + throw new Error(`Error creating xAI client: ${error.message}`) + } + } + return this.client } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const client = this.ensureClient() const modelId = this.getModel().id // ensure reasoning effort is either "low" or "high" for grok-3-mini let reasoningEffort: ChatCompletionReasoningEffort | undefined @@ -30,7 +44,7 @@ export class XAIHandler implements ApiHandler { reasoningEffort = undefined } } - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: modelId, max_completion_tokens: this.getModel().info.maxTokens, temperature: 0, From 5f90018ab5c3e3187a20a8900aacb0c73a6e9464 Mon Sep 17 00:00:00 2001 From: Ara Date: Sun, 6 Jul 2025 12:05:30 -0600 Subject: [PATCH 17/43] Revert "remove blur (#4664)" (#4677) --- webview-ui/src/components/history/HistoryPreview.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webview-ui/src/components/history/HistoryPreview.tsx b/webview-ui/src/components/history/HistoryPreview.tsx index dc14e3b7..baabc17b 100644 --- a/webview-ui/src/components/history/HistoryPreview.tsx +++ b/webview-ui/src/components/history/HistoryPreview.tsx @@ -65,6 +65,7 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => { backgroundColor: "color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 30%, transparent)", border: "1px solid color-mix(in srgb, var(--vscode-panel-border) 50%, transparent)", + backdropFilter: "blur(8px)", }} onClick={() => handleHistorySelect(item.id)}> {/* Subtle gradient overlay for extra depth */} @@ -152,6 +153,7 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => { fontSize: "var(--vscode-font-size)", backgroundColor: "color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 20%, transparent)", border: "1px solid color-mix(in srgb, var(--vscode-panel-border) 30%, transparent)", + backdropFilter: "blur(8px)", }}> No recent tasks From 4beaa2a086871e0c276aacbe24db539e5fc51f79 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Mon, 7 Jul 2025 13:16:08 -0500 Subject: [PATCH 18/43] sync local search state after timeout (#4698) --- .../settings/OpenRouterModelPicker.tsx | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index eac9ace7..5f344c84 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -64,6 +64,7 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } const { handleFieldsChange } = useApiConfigurationHandlers() const { apiConfiguration, openRouterModels, refreshOpenRouterModels } = useExtensionState() const [searchTerm, setSearchTerm] = useState(apiConfiguration?.openRouterModelId || openRouterDefaultModelId) + const [isSearchInputDirty, setIsSearchInputDirty] = useState(false) const [isDropdownVisible, setIsDropdownVisible] = useState(false) const [selectedIndex, setSelectedIndex] = useState(-1) const dropdownRef = useRef(null) @@ -87,6 +88,23 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } useMount(refreshOpenRouterModels) + // Sync external changes only when user isn't actively typing + useEffect(() => { + if (!isSearchInputDirty) { + const currentModelId = apiConfiguration?.openRouterModelId || openRouterDefaultModelId + setSearchTerm(currentModelId) + } + }, [apiConfiguration?.openRouterModelId, isSearchInputDirty]) + + // Reset dirty flag after user stops typing (1 second timeout) + useEffect(() => { + if (!isSearchInputDirty) return + const timeout = setTimeout(() => { + setIsSearchInputDirty(false) + }, 1000) + return () => clearTimeout(timeout) + }, [searchTerm, isSearchInputDirty]) + useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { @@ -243,6 +261,7 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } placeholder="Search and select a model..." value={searchTerm} onInput={(e) => { + setIsSearchInputDirty(true) handleModelChange((e.target as HTMLInputElement)?.value?.toLowerCase()) setIsDropdownVisible(true) }} From 7ab6189595e76d9d85a41af9d980ad09b1de217e Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Mon, 7 Jul 2025 15:14:48 -0500 Subject: [PATCH 19/43] mark welcomeViewCompleted as true after auth redirect (#4699) * mark welcomeViewCompleted as true after auth redirect * Create real-ravens-nail.md --------- Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com> --- .changeset/real-ravens-nail.md | 5 +++++ src/core/controller/index.ts | 3 +++ 2 files changed, 8 insertions(+) create mode 100644 .changeset/real-ravens-nail.md diff --git a/.changeset/real-ravens-nail.md b/.changeset/real-ravens-nail.md new file mode 100644 index 00000000..9f78714a --- /dev/null +++ b/.changeset/real-ravens-nail.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Fix logging in with cline not getting past welcome screen diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 0c143a38..37e80aca 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -472,6 +472,9 @@ export class Controller { const clineProvider: ApiProvider = "cline" await updateGlobalState(this.context, "apiProvider", clineProvider) + // Mark welcome view as completed since user has successfully logged in + await updateGlobalState(this.context, "welcomeViewCompleted", true) + // Update API configuration with the new provider and API key const { apiConfiguration } = await getAllExtensionState(this.context) const updatedConfig = { From ef02d6b0b2e0b47d8119f05645ebcb62e12ae27f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 7 Jul 2025 13:26:11 -0700 Subject: [PATCH 20/43] Changeset version bump (#4685) * changeset version bump * Updating CHANGELOG.md format * Update CHANGELOG.md * Update CHANGELOG.md * Update package.json --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: github-actions Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com> --- .changeset/calm-ads-glow.md | 5 ----- .changeset/real-ravens-nail.md | 5 ----- CHANGELOG.md | 5 +++++ package.json | 2 +- 4 files changed, 6 insertions(+), 11 deletions(-) delete mode 100644 .changeset/calm-ads-glow.md delete mode 100644 .changeset/real-ravens-nail.md diff --git a/.changeset/calm-ads-glow.md b/.changeset/calm-ads-glow.md deleted file mode 100644 index dc24339c..00000000 --- a/.changeset/calm-ads-glow.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": minor ---- - -Add support for Gemini 2.5 Pro and Flash to SAP AI Core Provider diff --git a/.changeset/real-ravens-nail.md b/.changeset/real-ravens-nail.md deleted file mode 100644 index 9f78714a..00000000 --- a/.changeset/real-ravens-nail.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Fix logging in with cline not getting past welcome screen diff --git a/CHANGELOG.md b/CHANGELOG.md index 73516bfb..b05c5fd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [3.18.4] + +- Add support for Gemini 2.5 Pro and Flash to SAP AI Core Provider +- Fix logging in with Cline account not getting past welcome screen + ## [3.18.3] - Improve Cerebras Qwen model performance by removing thinking tokens from model input (Thanks @kevint-cerebras!) diff --git a/package.json b/package.json index 63611a5d..2991d289 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.3", + "version": "3.18.4", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" From 4e27e0667083883b1cbe0b5683161c99016589bd Mon Sep 17 00:00:00 2001 From: schardosin Date: Mon, 7 Jul 2025 16:44:27 -0400 Subject: [PATCH 21/43] SAP AI Core small bug fix and reorder models (#4686) * small fix to avoid exception and removed log of returned data * reorganized sapaicore models to be grouped in logical groups * updated changese with changes in SAP AI Core * removed additional received data log sections --- .changeset/shy-waves-perform.md | 5 ++ src/api/providers/sapaicore.ts | 5 +- src/shared/api.ts | 100 ++++++++++++++++---------------- 3 files changed, 56 insertions(+), 54 deletions(-) create mode 100644 .changeset/shy-waves-perform.md diff --git a/.changeset/shy-waves-perform.md b/.changeset/shy-waves-perform.md new file mode 100644 index 00000000..b9cf230e --- /dev/null +++ b/.changeset/shy-waves-perform.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Reorder the models for SAP AI Core in a more organized and logical manner, grouping them by provider and model type diff --git a/src/api/providers/sapaicore.ts b/src/api/providers/sapaicore.ts index 69e58f94..d858f435 100644 --- a/src/api/providers/sapaicore.ts +++ b/src/api/providers/sapaicore.ts @@ -283,7 +283,6 @@ export class SapAiCoreHandler implements ApiHandler { const jsonData = line.slice(6) try { const data = JSON.parse(jsonData) - console.log("Received data:", data) if (data.type === "message_start") { usage.input_tokens = data.message.usage.input_tokens yield { @@ -346,7 +345,6 @@ export class SapAiCoreHandler implements ApiHandler { try { // Parse the incoming JSON data from the stream const data = JSON.parse(toStrictJson(jsonData)) - console.log("Received data:", data) // Handle metadata (token usage) if (data.metadata?.usage) { @@ -422,7 +420,6 @@ export class SapAiCoreHandler implements ApiHandler { const jsonData = line.slice(6) try { const data = JSON.parse(jsonData) - console.log("Received GPT data:", data) if (data.choices && data.choices.length > 0) { const choice = data.choices[0] @@ -446,7 +443,7 @@ export class SapAiCoreHandler implements ApiHandler { } } - if (data.choices && data.choices[0].finish_reason === "stop") { + if (data.choices?.[0]?.finish_reason === "stop") { // Final usage yield, if not already provided if (!data.usage) { yield { diff --git a/src/shared/api.ts b/src/shared/api.ts index 8e7d983b..60896add 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -2374,42 +2374,6 @@ export const requestyDefaultModelInfo: ModelInfo = { export type SapAiCoreModelId = keyof typeof sapAiCoreModels export const sapAiCoreDefaultModelId: SapAiCoreModelId = "anthropic--claude-3.5-sonnet" export const sapAiCoreModels = { - "gemini-2.5-pro": { - maxTokens: 65536, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: true, - inputPrice: 2.5, - outputPrice: 15, - cacheReadsPrice: 0.625, - tiers: [ - { - contextWindow: 200000, - inputPrice: 1.25, - outputPrice: 10, - cacheReadsPrice: 0.31, - }, - { - contextWindow: Infinity, - inputPrice: 2.5, - outputPrice: 15, - cacheReadsPrice: 0.625, - }, - ], - }, - "gemini-2.5-flash": { - maxTokens: 65536, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: true, - inputPrice: 0.3, - outputPrice: 2.5, - cacheReadsPrice: 0.075, - thinkingConfig: { - maxBudget: 24576, - outputPrice: 3.5, - }, - }, "anthropic--claude-4-sonnet": { maxTokens: 8192, contextWindow: 200_000, @@ -2466,21 +2430,41 @@ export const sapAiCoreModels = { inputPrice: 3.0, outputPrice: 15.0, }, - "gpt-4o": { - maxTokens: 4096, - contextWindow: 200_000, + "gemini-2.5-pro": { + maxTokens: 65536, + contextWindow: 1_048_576, supportsImages: true, - supportsPromptCache: false, - inputPrice: 3.0, - outputPrice: 15.0, + supportsPromptCache: true, + inputPrice: 2.5, + outputPrice: 15, + cacheReadsPrice: 0.625, + tiers: [ + { + contextWindow: 200000, + inputPrice: 1.25, + outputPrice: 10, + cacheReadsPrice: 0.31, + }, + { + contextWindow: Infinity, + inputPrice: 2.5, + outputPrice: 15, + cacheReadsPrice: 0.625, + }, + ], }, - "gpt-4o-mini": { - maxTokens: 4096, - contextWindow: 200_000, + "gemini-2.5-flash": { + maxTokens: 65536, + contextWindow: 1_048_576, supportsImages: true, - supportsPromptCache: false, - inputPrice: 3.0, - outputPrice: 15.0, + supportsPromptCache: true, + inputPrice: 0.3, + outputPrice: 2.5, + cacheReadsPrice: 0.075, + thinkingConfig: { + maxBudget: 24576, + outputPrice: 3.5, + }, }, "gpt-4": { maxTokens: 4096, @@ -2490,7 +2474,7 @@ export const sapAiCoreModels = { inputPrice: 3.0, outputPrice: 15.0, }, - o1: { + "gpt-4o": { maxTokens: 4096, contextWindow: 200_000, supportsImages: true, @@ -2498,7 +2482,7 @@ export const sapAiCoreModels = { inputPrice: 3.0, outputPrice: 15.0, }, - "o3-mini": { + "gpt-4o-mini": { maxTokens: 4096, contextWindow: 200_000, supportsImages: true, @@ -2524,6 +2508,14 @@ export const sapAiCoreModels = { outputPrice: 0.4, cacheReadsPrice: 0.025, }, + o1: { + maxTokens: 4096, + contextWindow: 200_000, + supportsImages: true, + supportsPromptCache: false, + inputPrice: 3.0, + outputPrice: 15.0, + }, o3: { maxTokens: 100_000, contextWindow: 200_000, @@ -2533,6 +2525,14 @@ export const sapAiCoreModels = { outputPrice: 40.0, cacheReadsPrice: 2.5, }, + "o3-mini": { + maxTokens: 4096, + contextWindow: 200_000, + supportsImages: true, + supportsPromptCache: false, + inputPrice: 3.0, + outputPrice: 15.0, + }, "o4-mini": { maxTokens: 100_000, contextWindow: 200_000, From f97ef745d92bc3dc2aa50c8278278ecde4216f7a Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 7 Jul 2025 14:23:26 -0700 Subject: [PATCH 22/43] Replace vscode.workspace.getWorkspaceFolder() with the host bridge (#4659) * Replace vscode.workspace.getWorkspaceFolder() with the host bridge Use the hostbridge getWorkspacePaths() and use the result to check for the workspaceFolder of the current file open in the IDE. * Organize imports * Update isLocatedInWorkspace() to check all the workspace directories, not just the first. Add utility function to check if a path is inside a directory instead of duplicating the logic. * Remove stubs for workspaceFolders that are not needed anymore. --- src/utils/path.ts | 71 ++++++++++++------- .../runtime-files/vscode/vscode-impls.js | 22 +----- .../runtime-files/vscode/vscode-stubs.js | 10 --- 3 files changed, 47 insertions(+), 56 deletions(-) diff --git a/src/utils/path.ts b/src/utils/path.ts index c4a223ee..3c4205a4 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -1,7 +1,7 @@ -import * as path from "path" -import os from "os" -import * as vscode from "vscode" import { getHostBridgeProvider } from "@/hosts/host-providers" +import os from "os" +import * as path from "path" +import * as vscode from "vscode" /* The Node.js 'path' module resolves and normalizes paths differently depending on the platform: @@ -103,9 +103,9 @@ export function getReadablePath(cwd: string, relPath?: string): string { } // Returns the path of the first workspace directory, or the defaultCwdPath if there is no workspace open. -export const getCwd = async (defaultCwdPath = ""): Promise => { - const workspaceFolders = await getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) - return workspaceFolders.paths.shift() || defaultCwdPath +export async function getCwd(defaultCwd = ""): Promise { + const workspacePaths = await getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) + return workspacePaths.paths.shift() || defaultCwd } export function getDesktopDir() { @@ -113,31 +113,50 @@ export function getDesktopDir() { } // Returns the workspace path of the file in the current editor. -// If there is no path, it returns the top level workspace directory. -export const getWorkspacePath = async (defaultCwdPath = "") => { - const currentFileUri = vscode.window.activeTextEditor?.document.uri - const cwdPath = await getCwd(defaultCwdPath) - if (currentFileUri) { - const workspaceFolder = vscode.workspace.getWorkspaceFolder(currentFileUri) - return workspaceFolder?.uri.fsPath || cwdPath +// If there is no open file, it returns the top level workspace directory. +export async function getWorkspacePath(defaultCwd = ""): Promise { + const currentFilePath = vscode.window.activeTextEditor?.document.uri.fsPath + if (!currentFilePath) { + return await getCwd(defaultCwd) } - return cwdPath + + const workspacePaths = (await getHostBridgeProvider().workspaceClient.getWorkspacePaths({})).paths + for (const workspacePath of workspacePaths) { + if (isLocatedInPath(workspacePath, currentFilePath)) { + return workspacePath + } + } + return await getCwd(defaultCwd) } -export const isLocatedInWorkspace = async (pathToCheck: string = ""): Promise => { - const workspacePath = await getWorkspacePath() +export async function isLocatedInWorkspace(pathToCheck: string = ""): Promise { + const workspacePaths = (await getHostBridgeProvider().workspaceClient.getWorkspacePaths({})).paths + for (const workspacePath of workspacePaths) { + const resolvedPath = path.resolve(workspacePath, pathToCheck) + if (isLocatedInPath(workspacePath, resolvedPath)) { + return true + } + } + return false +} +// Returns true if `pathToCheck` is located inside `dirPath`. +export function isLocatedInPath(dirPath: string, pathToCheck: string): boolean { + if (!dirPath || !pathToCheck) { + return false + } // Handle long paths in Windows - if (pathToCheck.startsWith("\\\\?\\") || workspacePath.startsWith("\\\\?\\")) { - return pathToCheck.startsWith(workspacePath) + if (dirPath.startsWith("\\\\?\\") || pathToCheck.startsWith("\\\\?\\")) { + return pathToCheck.startsWith(dirPath) } - // Normalize paths without resolving symlinks - const normalizedWorkspace = path.normalize(workspacePath) - const normalizedPath = path.normalize(path.resolve(workspacePath, pathToCheck)) - - // Use path.relative to check if the path is within the workspace - const relativePath = path.relative(normalizedWorkspace, normalizedPath) - - return !relativePath.startsWith("..") && !path.isAbsolute(relativePath) + const relativePath = path.relative(path.resolve(dirPath), path.resolve(pathToCheck)) + if (relativePath.startsWith("..")) { + return false + } + if (path.isAbsolute(relativePath)) { + // This can happen on windows when the two paths are on different drives. + return false + } + return true } diff --git a/standalone/runtime-files/vscode/vscode-impls.js b/standalone/runtime-files/vscode/vscode-impls.js index f872c71e..394b5303 100644 --- a/standalone/runtime-files/vscode/vscode-impls.js +++ b/standalone/runtime-files/vscode/vscode-impls.js @@ -498,17 +498,8 @@ Object.assign(vscode.workspace, { }, }, - // Add workspace folder configuration rootPath: process.cwd(), - workspaceFolders: [ - { - uri: vscode.Uri.file(process.cwd()), - name: path.basename(process.cwd()), - index: 0, - }, - ], name: path.basename(process.cwd()), - workspaceFile: vscode.Uri.file(path.join(process.cwd(), ".vscode", "workspace.json")), // Add other workspace methods as stubs getConfiguration: () => ({ @@ -516,14 +507,6 @@ Object.assign(vscode.workspace, { update: () => Promise.resolve(), has: () => false, }), - getWorkspaceFolder: (uri) => { - console.log("Called vscode.workspace.getWorkspaceFolder with:", uri) - // Return the first workspace folder for any URI in standalone mode - if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { - return vscode.workspace.workspaceFolders[0] - } - return undefined - }, createFileSystemWatcher: () => ({ onDidChange: () => ({ dispose: () => {} }), onDidCreate: () => ({ dispose: () => {} }), @@ -531,7 +514,6 @@ Object.assign(vscode.workspace, { dispose: () => {}, }), onDidChangeConfiguration: () => ({ dispose: () => {} }), - onDidChangeWorkspaceFolders: () => ({ dispose: () => {} }), onDidCreateFiles: createStub("vscode.workspace.onDidCreateFiles"), onDidDeleteFiles: createStub("vscode.workspace.onDidDeleteFiles"), onDidRenameFiles: createStub("vscode.workspace.onDidRenameFiles"), @@ -827,8 +809,6 @@ Object.assign(vscode.languages, { }), }) -console.log("Finished loading stub impls...") - // Export the terminal manager globally for Cline core to use global.standaloneTerminalManager = globalTerminalManager @@ -839,3 +819,5 @@ if (typeof global !== "undefined") { } module.exports = vscode + +console.log("Finished loading stub impls...") diff --git a/standalone/runtime-files/vscode/vscode-stubs.js b/standalone/runtime-files/vscode/vscode-stubs.js index b2123d1f..88ec5ac5 100644 --- a/standalone/runtime-files/vscode/vscode-stubs.js +++ b/standalone/runtime-files/vscode/vscode-stubs.js @@ -812,22 +812,12 @@ vscode.TextDocumentSaveReason = { Manual: 0, AfterDelay: 0, FocusOut: 0 } vscode.workspace = {} vscode.workspace.fs = createStub("vscode.workspace.fs") vscode.workspace.rootPath = createStub("vscode.workspace.rootPath") -vscode.workspace.workspaceFolders = [] vscode.workspace.name = createStub("vscode.workspace.name") vscode.workspace.workspaceFile = createStub("vscode.workspace.workspaceFile") -vscode.workspace.onDidChangeWorkspaceFolders = createStub("vscode.workspace.onDidChangeWorkspaceFolders") -vscode.workspace.getWorkspaceFolder = function (uri) { - console.log("Called stubbed function: vscode.workspace.getWorkspaceFolder") - return createStub("unknown") -} vscode.workspace.asRelativePath = function (pathOrUri, includeWorkspaceFolder) { console.log("Called stubbed function: vscode.workspace.asRelativePath") return "" } -vscode.workspace.updateWorkspaceFolders = function (start, deleteCount, workspaceFoldersToAdd) { - console.log("Called stubbed function: vscode.workspace.updateWorkspaceFolders") - return false -} vscode.workspace.createFileSystemWatcher = function (globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents) { console.log("Called stubbed function: vscode.workspace.createFileSystemWatcher") return createStub("unknown") From 3577c2efa9872489dde654a51b223dacf31d1a65 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 7 Jul 2025 14:27:19 -0700 Subject: [PATCH 23/43] Remove uri service from the host bridge. (#4660) It is being replaced with the npm module vscode-uri. --- proto/host/uri.proto | 36 -------------------- src/core/controller/file/getRelativePaths.ts | 13 ++----- src/core/controller/task/newTask.ts | 1 - src/hosts/host-provider-types.ts | 2 -- src/hosts/host-providers.ts | 1 - src/hosts/vscode/client/host-grpc-client.ts | 1 - src/hosts/vscode/uri/file.ts | 20 ----------- src/hosts/vscode/uri/joinPath.ts | 28 --------------- src/hosts/vscode/uri/parse.ts | 20 ----------- src/standalone/host-bridge-client-manager.ts | 4 --- 10 files changed, 2 insertions(+), 124 deletions(-) delete mode 100644 proto/host/uri.proto delete mode 100644 src/hosts/vscode/uri/file.ts delete mode 100644 src/hosts/vscode/uri/joinPath.ts delete mode 100644 src/hosts/vscode/uri/parse.ts diff --git a/proto/host/uri.proto b/proto/host/uri.proto deleted file mode 100644 index c05e2fe5..00000000 --- a/proto/host/uri.proto +++ /dev/null @@ -1,36 +0,0 @@ -syntax = "proto3"; - -package host; -option java_package = "bot.cline.host.proto"; -option java_multiple_files = true; - -import "common.proto"; - -// UriService provides methods for working with URIs in the IDE -service UriService { - // Create a new file URI from a file path - rpc file(cline.StringRequest) returns (Uri); - - // Join a URI with additional path segments - rpc joinPath(JoinPathRequest) returns (Uri); - - // Parse a string URI into a Uri object - rpc parse(cline.StringRequest) returns (Uri); -} - -// Uri represents a URI in the IDE -message Uri { - string scheme = 1; - string authority = 2; - string path = 3; - string query = 4; - string fragment = 5; - string fs_path = 6; -} - -// Request for joining path segments to a URI -message JoinPathRequest { - cline.Metadata metadata = 1; - Uri base = 2; - repeated string path_segments = 3; -} diff --git a/src/core/controller/file/getRelativePaths.ts b/src/core/controller/file/getRelativePaths.ts index bda41ca2..c606ae46 100644 --- a/src/core/controller/file/getRelativePaths.ts +++ b/src/core/controller/file/getRelativePaths.ts @@ -3,8 +3,6 @@ import { RelativePathsRequest, RelativePaths } from "@shared/proto/file" import { FileMethodHandler } from "./index" import * as vscode from "vscode" import * as path from "path" -import { StringRequest } from "@shared/proto/common" -import { getHostBridgeProvider } from "@hosts/host-providers" /** * Converts a list of URIs to workspace-relative paths @@ -13,20 +11,13 @@ import { getHostBridgeProvider } from "@hosts/host-providers" * @returns Response with resolved relative paths */ export const getRelativePaths: FileMethodHandler = async ( - controller: Controller, + _controller: Controller, request: RelativePathsRequest, ): Promise => { const resolvedPaths = await Promise.all( request.uris.map(async (uriString) => { try { - // Use the host URI service client instead of directly using vscode.Uri.parse - const parseResponse = await getHostBridgeProvider().uriServiceClient.parse( - StringRequest.create({ - value: uriString, - }), - ) - const fileUri = vscode.Uri.parse(`${parseResponse.scheme}://${parseResponse.authority}${parseResponse.path}`) - console.log("[DEBUG] UriServiceClient.parse:", fileUri) + const fileUri = vscode.Uri.parse(uriString, true) const relativePathToGet = vscode.workspace.asRelativePath(fileUri, false) // If the path is still absolute, it's outside the workspace diff --git a/src/core/controller/task/newTask.ts b/src/core/controller/task/newTask.ts index 15274264..48fb37e8 100644 --- a/src/core/controller/task/newTask.ts +++ b/src/core/controller/task/newTask.ts @@ -1,7 +1,6 @@ import { Controller } from ".." import { Empty } from "../../../shared/proto/common" import { NewTaskRequest } from "../../../shared/proto/task" -import { handleFileServiceRequest } from "../file" /** * Creates a new task with the given text and optional images diff --git a/src/hosts/host-provider-types.ts b/src/hosts/host-provider-types.ts index 8290518f..57603874 100644 --- a/src/hosts/host-provider-types.ts +++ b/src/hosts/host-provider-types.ts @@ -1,5 +1,4 @@ import { - UriServiceClientInterface, WatchServiceClientInterface, WorkspaceServiceClientInterface, EnvServiceClientInterface, @@ -10,7 +9,6 @@ import { * Interface for host bridge client providers */ export interface HostBridgeClientProvider { - uriServiceClient: UriServiceClientInterface watchServiceClient: WatchServiceClientInterface workspaceClient: WorkspaceServiceClientInterface envClient: EnvServiceClientInterface diff --git a/src/hosts/host-providers.ts b/src/hosts/host-providers.ts index fa07562c..29b6b7aa 100644 --- a/src/hosts/host-providers.ts +++ b/src/hosts/host-providers.ts @@ -1,7 +1,6 @@ import { WebviewProvider } from "@core/webview" import { HostBridgeClientProvider } from "./host-provider-types" import { WebviewProviderType } from "@/shared/webview/types" -import * as vscode from "vscode" /** * A function that creates WebviewProvider instances diff --git a/src/hosts/vscode/client/host-grpc-client.ts b/src/hosts/vscode/client/host-grpc-client.ts index 033e38b7..2ccba63e 100644 --- a/src/hosts/vscode/client/host-grpc-client.ts +++ b/src/hosts/vscode/client/host-grpc-client.ts @@ -3,7 +3,6 @@ import { HostBridgeClientProvider } from "@/hosts/host-provider-types" import * as host from "@shared/proto/index.host" export const vscodeHostBridgeClient: HostBridgeClientProvider = { - uriServiceClient: createGrpcClient(host.UriServiceDefinition), watchServiceClient: createGrpcClient(host.WatchServiceDefinition), workspaceClient: createGrpcClient(host.WorkspaceServiceDefinition), envClient: createGrpcClient(host.EnvServiceDefinition), diff --git a/src/hosts/vscode/uri/file.ts b/src/hosts/vscode/uri/file.ts deleted file mode 100644 index 425c2cff..00000000 --- a/src/hosts/vscode/uri/file.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as vscode from "vscode" -import { Uri } from "@shared/proto/host/uri" -import { StringRequest } from "@shared/proto/common" - -/** - * Creates a file URI from a file path - * @param request The request containing the file path - * @returns A URI object representing the file - */ -export async function file(request: StringRequest): Promise { - const uri = vscode.Uri.file(request.value) - return Uri.create({ - scheme: uri.scheme, - authority: uri.authority, - path: uri.path, - query: uri.query, - fragment: uri.fragment, - fsPath: uri.fsPath, - }) -} diff --git a/src/hosts/vscode/uri/joinPath.ts b/src/hosts/vscode/uri/joinPath.ts deleted file mode 100644 index e5dcc85b..00000000 --- a/src/hosts/vscode/uri/joinPath.ts +++ /dev/null @@ -1,28 +0,0 @@ -import * as vscode from "vscode" -import { JoinPathRequest, Uri } from "@shared/proto/host/uri" - -/** - * Joins a URI with additional path segments - * @param request The request containing the base URI and path segments - * @returns A new URI with the path segments joined - */ -export async function joinPath(request: JoinPathRequest): Promise { - // Convert proto Uri to vscode.Uri - if (!request.base) { - throw new Error("Base URI is required") - } - const baseUri = vscode.Uri.parse(`${request.base.scheme}://${request.base.authority}${request.base.path}`) - - // Join paths - const result = vscode.Uri.joinPath(baseUri, ...request.pathSegments) - - // Convert back to proto Uri - return Uri.create({ - scheme: result.scheme, - authority: result.authority, - path: result.path, - query: result.query, - fragment: result.fragment, - fsPath: result.fsPath, - }) -} diff --git a/src/hosts/vscode/uri/parse.ts b/src/hosts/vscode/uri/parse.ts deleted file mode 100644 index 359f02c7..00000000 --- a/src/hosts/vscode/uri/parse.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as vscode from "vscode" -import { Uri } from "@shared/proto/host/uri" -import { StringRequest } from "@shared/proto/common" - -/** - * Parses a string URI into a Uri object - * @param request The request containing the URI string - * @returns A URI object representing the parsed URI - */ -export async function parse(request: StringRequest): Promise { - const uri = vscode.Uri.parse(request.value) - return Uri.create({ - scheme: uri.scheme, - authority: uri.authority, - path: uri.path, - query: uri.query, - fragment: uri.fragment, - fsPath: uri.fsPath, - }) -} diff --git a/src/standalone/host-bridge-client-manager.ts b/src/standalone/host-bridge-client-manager.ts index 927bbc88..61d5e628 100644 --- a/src/standalone/host-bridge-client-manager.ts +++ b/src/standalone/host-bridge-client-manager.ts @@ -1,13 +1,11 @@ import { Channel, createChannel } from "nice-grpc" import { - UriServiceClientImpl, WatchServiceClientImpl, WorkspaceServiceClientImpl, EnvServiceClientImpl, WindowServiceClientImpl, } from "@generated/standalone/host-bridge-clients" import { - UriServiceClientInterface, WatchServiceClientInterface, WorkspaceServiceClientInterface, EnvServiceClientInterface, @@ -21,7 +19,6 @@ import { HostBridgeClientProvider } from "@/hosts/host-provider-types" */ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider { private channel: Channel - uriServiceClient: UriServiceClientInterface watchServiceClient: WatchServiceClientInterface workspaceClient: WorkspaceServiceClientInterface envClient: EnvServiceClientInterface @@ -31,7 +28,6 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider const address = process.env.HOST_BRIDGE_ADDRESS || "localhost:50052" this.channel = createChannel(address) - this.uriServiceClient = new UriServiceClientImpl(this.channel) this.watchServiceClient = new WatchServiceClientImpl(this.channel) this.workspaceClient = new WorkspaceServiceClientImpl(this.channel) this.envClient = new EnvServiceClientImpl(this.channel) From 6d2cf55fc528c6fb5be811ec36ee6235ec9efe6a Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Mon, 7 Jul 2025 16:58:49 -0500 Subject: [PATCH 24/43] migrate download MCP response to proto (#4682) --- proto/mcp.proto | 14 +++++- src/core/controller/mcp/downloadMcp.ts | 44 +++++++++++-------- src/shared/ExtensionMessage.ts | 33 +------------- .../tabs/marketplace/McpMarketplaceCard.tsx | 32 +++++++------- .../tabs/marketplace/McpMarketplaceView.tsx | 19 ++------ 5 files changed, 60 insertions(+), 82 deletions(-) diff --git a/proto/mcp.proto b/proto/mcp.proto index f656b275..00d8b249 100644 --- a/proto/mcp.proto +++ b/proto/mcp.proto @@ -10,7 +10,7 @@ service McpService { rpc toggleMcpServer(ToggleMcpServerRequest) returns (McpServers); rpc updateMcpTimeout(UpdateMcpTimeoutRequest) returns (McpServers); rpc addRemoteMcpServer(AddRemoteMcpServerRequest) returns (McpServers); - rpc downloadMcp(StringRequest) returns (Empty); + rpc downloadMcp(StringRequest) returns (McpDownloadResponse); rpc restartMcpServer(StringRequest) returns (McpServers); rpc deleteMcpServer(StringRequest) returns (McpServers); rpc toggleToolAutoApprove(ToggleToolAutoApproveRequest) returns (McpServers); @@ -119,3 +119,15 @@ message McpMarketplaceItem { message McpMarketplaceCatalog { repeated McpMarketplaceItem items = 1; } + +message McpDownloadResponse { + string mcp_id = 1; + string github_url = 2; + string name = 3; + string author = 4; + string description = 5; + string readme_content = 6; + string llms_installation_content = 7; + bool requires_api_key = 8; + optional string error = 9; +} diff --git a/src/core/controller/mcp/downloadMcp.ts b/src/core/controller/mcp/downloadMcp.ts index e3254d81..53279e43 100644 --- a/src/core/controller/mcp/downloadMcp.ts +++ b/src/core/controller/mcp/downloadMcp.ts @@ -1,6 +1,7 @@ import { Controller } from ".." -import { Empty, StringRequest } from "../../../shared/proto/common" -import { McpServer, McpDownloadResponse } from "@shared/mcp" +import { StringRequest } from "../../../shared/proto/common" +import { McpDownloadResponse } from "../../../shared/proto/mcp" +import { McpServer } from "@shared/mcp" import axios from "axios" import * as vscode from "vscode" import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" @@ -9,9 +10,9 @@ import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" * Download an MCP server from the marketplace * @param controller The controller instance * @param request The request containing the MCP ID - * @returns Empty response + * @returns MCP download response with details or error */ -export async function downloadMcp(controller: Controller, request: StringRequest): Promise { +export async function downloadMcp(controller: Controller, request: StringRequest): Promise { try { // Check if mcpId is provided if (!request.value) { @@ -54,12 +55,6 @@ export async function downloadMcp(controller: Controller, request: StringRequest throw new Error("Missing README content in MCP download response") } - // Send details to webview - await controller.postMessageToWebview({ - type: "mcpDownloadDetails", - mcpDownloadDetails: mcpDetails, - }) - // Create task with context from README and added guidelines for MCP server installation const task = `Set up the MCP server from ${mcpDetails.githubUrl} while adhering to these MCP server installation rules: - Start by loading the MCP documentation. @@ -80,8 +75,17 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont await controller.initTask(task) await sendChatButtonClickedEvent(controller.id) - // Return an empty response - the client only cares if the call succeeded - return Empty.create() + // Return the download details directly + return McpDownloadResponse.create({ + mcpId: mcpDetails.mcpId, + githubUrl: mcpDetails.githubUrl, + name: mcpDetails.name, + author: mcpDetails.author, + description: mcpDetails.description, + readmeContent: mcpDetails.readmeContent, + llmsInstallationContent: mcpDetails.llmsInstallationContent, + requiresApiKey: mcpDetails.requiresApiKey, + }) } catch (error) { console.error("Failed to download MCP:", error) let errorMessage = "Failed to download MCP" @@ -100,13 +104,17 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont errorMessage = error.message } - // Show error in both notification and marketplace UI - vscode.window.showErrorMessage(errorMessage) - await controller.postMessageToWebview({ - type: "mcpDownloadDetails", + // Return error in the response instead of throwing + return McpDownloadResponse.create({ + mcpId: "", + githubUrl: "", + name: "", + author: "", + description: "", + readmeContent: "", + llmsInstallationContent: "", + requiresApiKey: false, error: errorMessage, }) - - throw error } } diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index ed647fc0..fa02e938 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -14,37 +14,8 @@ import { UserInfo } from "./UserInfo" // webview will hold state export interface ExtensionMessage { - type: "action" | "state" | "selectedImages" | "mcpDownloadDetails" | "grpc_response" // New type for gRPC responses - text?: string - action?: "accountLogoutClicked" - state?: ExtensionState - images?: string[] - files?: string[] - ollamaModels?: string[] - lmStudioModels?: string[] - vsCodeLmModels?: { vendor?: string; family?: string; version?: string; id?: string }[] - openAiModels?: string[] - mcpServers?: McpServer[] - customToken?: string - mcpMarketplaceCatalog?: McpMarketplaceCatalog - error?: string - mcpDownloadDetails?: McpDownloadResponse - commits?: GitCommit[] - url?: string - isImage?: boolean - success?: boolean - endpoint?: string - isBundled?: boolean - isConnected?: boolean - isRemote?: boolean - host?: string - mentionsRequestId?: string - results?: Array<{ - path: string - type: "file" | "folder" - label?: string - }> - tab?: McpViewTab + type: "grpc_response" // New type for gRPC responses + grpc_response?: { message?: any // JSON serialized protobuf message request_id: string // Same ID as the request diff --git a/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx b/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx index 4f7fa090..8e61e08c 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx @@ -1,34 +1,23 @@ import { McpServiceClient } from "@/services/grpc-client" import { McpMarketplaceItem, McpServer } from "@shared/mcp" import { StringRequest } from "@shared/proto/common" -import { useCallback, useEffect, useMemo, useRef, useState } from "react" -import { useEvent } from "react-use" +import { useEffect, useMemo, useRef, useState } from "react" import styled from "styled-components" import { useExtensionState } from "@/context/ExtensionStateContext" interface McpMarketplaceCardProps { item: McpMarketplaceItem installedServers: McpServer[] + setError: (error: string | null) => void } -const McpMarketplaceCard = ({ item, installedServers }: McpMarketplaceCardProps) => { +const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplaceCardProps) => { const isInstalled = installedServers.some((server) => server.name === item.mcpId) const [isDownloading, setIsDownloading] = useState(false) const [isLoading, setIsLoading] = useState(false) const githubLinkRef = useRef(null) const { onRelinquishControl } = useExtensionState() - const handleMessage = useCallback((event: MessageEvent) => { - const message = event.data - switch (message.type) { - case "mcpDownloadDetails": - setIsDownloading(false) - break - } - }, []) - - useEvent("message", handleMessage) - useEffect(() => { return onRelinquishControl(() => { setIsLoading(false) @@ -119,10 +108,21 @@ const McpMarketplaceCard = ({ item, installedServers }: McpMarketplaceCardProps) if (!isInstalled && !isDownloading) { setIsDownloading(true) try { - await McpServiceClient.downloadMcp(StringRequest.create({ value: item.mcpId })) + const response = await McpServiceClient.downloadMcp( + StringRequest.create({ value: item.mcpId }), + ) + if (response.error) { + console.error("MCP download failed:", response.error) + setError(response.error) + } else { + console.log("MCP download successful:", response) + // Clear any previous errors on success + setError(null) + } } catch (error) { - setIsDownloading(false) console.error("Failed to download MCP:", error) + } finally { + setIsDownloading(false) } } }} diff --git a/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceView.tsx b/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceView.tsx index 5eaee8bf..8c179554 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceView.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceView.tsx @@ -59,23 +59,8 @@ const McpMarketplaceView = () => { }, [items, searchQuery, selectedCategory, sortBy]) useEffect(() => { - const handleMessage = (event: MessageEvent) => { - const message = event.data - if (message.type === "mcpDownloadDetails") { - if (message.error) { - setError(message.error) - } - } - } - - window.addEventListener("message", handleMessage) - // Fetch marketplace catalog on initial load fetchMarketplace() - - return () => { - window.removeEventListener("message", handleMessage) - } }, []) useEffect(() => { @@ -290,7 +275,9 @@ const McpMarketplaceView = () => { : "No MCP servers found in the marketplace"} ) : ( - filteredItems.map((item) => ) + filteredItems.map((item) => ( + + )) )} From 0262e13ac48bbbc29f6c76b6b9a72e7e2ed2eb4b Mon Sep 17 00:00:00 2001 From: Bee <68532117+abeatrix@users.noreply.github.com> Date: Mon, 7 Jul 2025 16:24:06 -0700 Subject: [PATCH 25/43] Capture token usage for conversation turns in telementry (#4703) Adds capture of token usage data for conversation turns in the telemetry service. This includes tokensIn, tokensOut, cacheWriteTokens, cacheReadTokens, and totalCost. The changes involve: - Modifying the `captureConversationTurnEvent` method in `TelemetryService.ts` to accept and include token usage data in the captured event properties. - Updating the `Task` class in `src/core/task/index.ts` to pass token usage information when capturing conversation turn events. This ensures that token usage is tracked for both regular and cached responses. - Refactor capture event to use object destructuring for easier readability Co-authored-by: Beatrix Woo --- src/core/task/index.ts | 14 +++++++++ .../posthog/telemetry/TelemetryService.ts | 29 ++++++++++++------- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 2457c320..1c166b5b 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -2124,6 +2124,13 @@ export class Task { this.api.getModel().id, "assistant", true, + { + tokensIn: inputTokens, + tokensOut: outputTokens, + cacheWriteTokens, + cacheReadTokens, + totalCost, + }, ) // signals to provider that it can retrieve the saved messages from disk, as abortTask can not be awaited on in nature @@ -2297,6 +2304,13 @@ export class Task { this.api.getModel().id, "assistant", true, + { + tokensIn: inputTokens, + tokensOut: outputTokens, + cacheWriteTokens, + cacheReadTokens, + totalCost, + }, ) await this.messageStateHandler.addToApiConversationHistory({ diff --git a/src/services/posthog/telemetry/TelemetryService.ts b/src/services/posthog/telemetry/TelemetryService.ts index 089cafdc..549bff58 100644 --- a/src/services/posthog/telemetry/TelemetryService.ts +++ b/src/services/posthog/telemetry/TelemetryService.ts @@ -202,26 +202,23 @@ class TelemetryService { const propertiesWithVersion = this.addProperties(event.properties) + const capturedEvent = { + event: event.event, + properties: propertiesWithVersion, + } + if (collect && taskId) { const existingTask = this.collectedTasks.find((task) => task.taskId === taskId) if (existingTask) { - existingTask.collection.push({ - event: event.event, - properties: propertiesWithVersion, - }) + existingTask.collection.push(capturedEvent) } else { this.collectedTasks.push({ taskId, - collection: [ - { - event: event.event, - properties: propertiesWithVersion, - }, - ], + collection: [capturedEvent], }) } } else { - this.client.capture({ distinctId: this.distinctId, event: event.event, properties: propertiesWithVersion }) + this.client.capture({ ...capturedEvent, distinctId: this.distinctId }) } } @@ -288,6 +285,8 @@ class TelemetryService { * @param provider The API provider (e.g., OpenAI, Anthropic) * @param model The specific model used (e.g., GPT-4, Claude) * @param source The source of the message ("user" | "model"). Used to track message patterns and identify when users need to correct the model's responses. + * @param collect If true, collect event instead of sending + * @param tokenUsage Optional token usage data */ public captureConversationTurnEvent( taskId: string, @@ -295,6 +294,13 @@ class TelemetryService { model: string = "unknown", source: "user" | "assistant", collect: boolean = false, + tokenUsage: { + tokensIn?: number + tokensOut?: number + cacheWriteTokens?: number + cacheReadTokens?: number + totalCost?: number + } = {}, ) { // Ensure required parameters are provided if (!taskId || !provider || !model || !source) { @@ -308,6 +314,7 @@ class TelemetryService { model, source, timestamp: new Date().toISOString(), // Add timestamp for message sequencing + ...tokenUsage, } this.capture( From cce8f09ae5d29868ca950f158a11effd32f45f87 Mon Sep 17 00:00:00 2001 From: Ara Date: Mon, 7 Jul 2025 19:19:50 -0600 Subject: [PATCH 26/43] Fixing bug on accepting tool response (#4675) --- .../chat/chat-view/hooks/useMessageHandlers.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts index afb46274..273b17fb 100644 --- a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts +++ b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts @@ -120,7 +120,14 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat // If there's no input content, just approve the action if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { // Send as a regular message so it appears in the conversation - await handleSendMessage(trimmedInput || "", images || [], files || []) + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "yesButtonClicked", + text: trimmedInput, + images: images, + files: files, + }), + ) } else { // No input content, just approve the action await TaskServiceClient.askResponse( From 7e32314c0b7185091202652665838182cedc2f60 Mon Sep 17 00:00:00 2001 From: Ara Date: Mon, 7 Jul 2025 19:20:55 -0600 Subject: [PATCH 27/43] Optimize provider switching performance with batched storage operations (#4676) * Optimize provider switching performance with batched storage operations * Optimize provider switching performance with batched storage operations --- .changeset/purple-rings-hide.md | 5 + src/core/storage/state.ts | 174 ++++++++++++++++++-------------- 2 files changed, 103 insertions(+), 76 deletions(-) create mode 100644 .changeset/purple-rings-hide.md diff --git a/.changeset/purple-rings-hide.md b/.changeset/purple-rings-hide.md new file mode 100644 index 00000000..5c8d2d35 --- /dev/null +++ b/.changeset/purple-rings-hide.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Optimizing provider switching performance with batched storage operations diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index 1c43651c..ec731536 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -28,6 +28,17 @@ export async function getGlobalState(context: vscode.ExtensionContext, key: Glob return await context.globalState.get(key) } +// Batched operations for performance optimization +export async function updateGlobalStateBatch(context: vscode.ExtensionContext, updates: Record) { + // Use Promise.all to batch the updates + await Promise.all(Object.entries(updates).map(([key, value]) => context.globalState.update(key as GlobalStateKey, value))) +} + +export async function updateSecretsBatch(context: vscode.ExtensionContext, updates: Record) { + // Use Promise.all to batch the secret updates + await Promise.all(Object.entries(updates).map(([key, value]) => storeSecret(context, key as SecretKey, value))) +} + // secrets export async function storeSecret(context: vscode.ExtensionContext, key: SecretKey, value?: string) { @@ -53,6 +64,7 @@ export async function getWorkspaceState(context: vscode.ExtensionContext, key: L } export async function getAllExtensionState(context: vscode.ExtensionContext) { + const firstBatchStart = performance.now() const [ isNewUser, welcomeViewCompleted, @@ -203,6 +215,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { const localClineRulesToggles = (await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles + const secondBatchStart = performance.now() const [ chatSettings, storedApiProvider, @@ -267,6 +280,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { getGlobalState(context, "sapAiCoreModelId") as Promise, ]) + const processingStart = performance.now() let apiProvider: ApiProvider if (storedApiProvider) { apiProvider = storedApiProvider @@ -491,84 +505,92 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a claudeCodePath, } = apiConfiguration - // Ephemeral model config updates - await updateGlobalState(context, "apiProvider", apiProvider) - await updateGlobalState(context, "apiModelId", apiModelId) - await updateGlobalState(context, "thinkingBudgetTokens", thinkingBudgetTokens) - await updateGlobalState(context, "reasoningEffort", reasoningEffort) - await updateGlobalState(context, "vsCodeLmModelSelector", vsCodeLmModelSelector) - await updateGlobalState(context, "awsBedrockCustomSelected", awsBedrockCustomSelected) - await updateGlobalState(context, "awsBedrockCustomModelBaseId", awsBedrockCustomModelBaseId) - await updateGlobalState(context, "openRouterModelId", openRouterModelId) - await updateGlobalState(context, "openRouterModelInfo", openRouterModelInfo) - await updateGlobalState(context, "openAiModelId", openAiModelId) - await updateGlobalState(context, "openAiModelInfo", openAiModelInfo) - await updateGlobalState(context, "ollamaModelId", ollamaModelId) - await updateGlobalState(context, "lmStudioModelId", lmStudioModelId) - await updateGlobalState(context, "liteLlmModelId", liteLlmModelId) - await updateGlobalState(context, "liteLlmModelInfo", liteLlmModelInfo) - await updateGlobalState(context, "requestyModelId", requestyModelId) - await updateGlobalState(context, "requestyModelInfo", requestyModelInfo) - await updateGlobalState(context, "togetherModelId", togetherModelId) - await updateGlobalState(context, "fireworksModelId", fireworksModelId) - await updateGlobalState(context, "sapAiCoreModelId", sapAiCoreModelId) + // OPTIMIZED: Batch all global state updates into 2 operations instead of 47 + const batchedGlobalUpdates = { + // Ephemeral model config updates (20 keys) + apiProvider, + apiModelId, + thinkingBudgetTokens, + reasoningEffort, + vsCodeLmModelSelector, + awsBedrockCustomSelected, + awsBedrockCustomModelBaseId, + openRouterModelId, + openRouterModelInfo, + openAiModelId, + openAiModelInfo, + ollamaModelId, + lmStudioModelId, + liteLlmModelId, + liteLlmModelInfo, + requestyModelId, + requestyModelInfo, + togetherModelId, + fireworksModelId, + sapAiCoreModelId, - // Global state updates - await updateGlobalState(context, "awsRegion", awsRegion) - await updateGlobalState(context, "awsUseCrossRegionInference", awsUseCrossRegionInference) - await updateGlobalState(context, "awsBedrockUsePromptCache", awsBedrockUsePromptCache) - await updateGlobalState(context, "awsBedrockEndpoint", awsBedrockEndpoint) - await updateGlobalState(context, "awsProfile", awsProfile) - await updateGlobalState(context, "awsUseProfile", awsUseProfile) - await updateGlobalState(context, "vertexProjectId", vertexProjectId) - await updateGlobalState(context, "vertexRegion", vertexRegion) - await updateGlobalState(context, "openAiBaseUrl", openAiBaseUrl) - await updateGlobalState(context, "openAiHeaders", openAiHeaders || {}) - await updateGlobalState(context, "ollamaBaseUrl", ollamaBaseUrl) - await updateGlobalState(context, "ollamaApiOptionsCtxNum", ollamaApiOptionsCtxNum) - await updateGlobalState(context, "lmStudioBaseUrl", lmStudioBaseUrl) - await updateGlobalState(context, "anthropicBaseUrl", anthropicBaseUrl) - await updateGlobalState(context, "geminiBaseUrl", geminiBaseUrl) - await updateGlobalState(context, "azureApiVersion", azureApiVersion) - await updateGlobalState(context, "openRouterProviderSorting", openRouterProviderSorting) - await updateGlobalState(context, "liteLlmBaseUrl", liteLlmBaseUrl) - await updateGlobalState(context, "liteLlmUsePromptCache", liteLlmUsePromptCache) - await updateGlobalState(context, "qwenApiLine", qwenApiLine) - await updateGlobalState(context, "asksageApiUrl", asksageApiUrl) - await updateGlobalState(context, "favoritedModelIds", favoritedModelIds) - await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs) - await updateGlobalState(context, "fireworksModelMaxCompletionTokens", fireworksModelMaxCompletionTokens) - await updateGlobalState(context, "fireworksModelMaxTokens", fireworksModelMaxTokens) - await updateGlobalState(context, "sapAiCoreBaseUrl", sapAiCoreBaseUrl) - await updateGlobalState(context, "sapAiCoreTokenUrl", sapAiCoreTokenUrl) - await updateGlobalState(context, "sapAiResourceGroup", sapAiResourceGroup) - await updateGlobalState(context, "claudeCodePath", claudeCodePath) + // Global state updates (27 keys) + awsRegion, + awsUseCrossRegionInference, + awsBedrockUsePromptCache, + awsBedrockEndpoint, + awsProfile, + awsUseProfile, + vertexProjectId, + vertexRegion, + openAiBaseUrl, + openAiHeaders: openAiHeaders || {}, + ollamaBaseUrl, + ollamaApiOptionsCtxNum, + lmStudioBaseUrl, + anthropicBaseUrl, + geminiBaseUrl, + azureApiVersion, + openRouterProviderSorting, + liteLlmBaseUrl, + liteLlmUsePromptCache, + qwenApiLine, + asksageApiUrl, + favoritedModelIds, + requestTimeoutMs: apiConfiguration.requestTimeoutMs, + fireworksModelMaxCompletionTokens, + fireworksModelMaxTokens, + sapAiCoreBaseUrl, + sapAiCoreTokenUrl, + sapAiResourceGroup, + claudeCodePath, + } - // Secret updates - await storeSecret(context, "apiKey", apiKey) - await storeSecret(context, "openRouterApiKey", openRouterApiKey) - await storeSecret(context, "clineApiKey", clineApiKey) - await storeSecret(context, "awsAccessKey", awsAccessKey) - await storeSecret(context, "awsSecretKey", awsSecretKey) - await storeSecret(context, "awsSessionToken", awsSessionToken) - await storeSecret(context, "openAiApiKey", openAiApiKey) - await storeSecret(context, "geminiApiKey", geminiApiKey) - await storeSecret(context, "openAiNativeApiKey", openAiNativeApiKey) - await storeSecret(context, "deepSeekApiKey", deepSeekApiKey) - await storeSecret(context, "requestyApiKey", requestyApiKey) - await storeSecret(context, "togetherApiKey", togetherApiKey) - await storeSecret(context, "qwenApiKey", qwenApiKey) - await storeSecret(context, "doubaoApiKey", doubaoApiKey) - await storeSecret(context, "mistralApiKey", mistralApiKey) - await storeSecret(context, "liteLlmApiKey", liteLlmApiKey) - await storeSecret(context, "fireworksApiKey", fireworksApiKey) - await storeSecret(context, "asksageApiKey", asksageApiKey) - await storeSecret(context, "xaiApiKey", xaiApiKey) - await storeSecret(context, "sambanovaApiKey", sambanovaApiKey) - await storeSecret(context, "cerebrasApiKey", cerebrasApiKey) - await storeSecret(context, "nebiusApiKey", nebiusApiKey) - await storeSecret(context, "sapAiCoreClientId", sapAiCoreClientId) - await storeSecret(context, "sapAiCoreClientSecret", sapAiCoreClientSecret) + // OPTIMIZED: Batch all secret updates into 1 operation instead of 23 + const batchedSecretUpdates = { + apiKey, + openRouterApiKey, + clineApiKey, + awsAccessKey, + awsSecretKey, + awsSessionToken, + openAiApiKey, + geminiApiKey, + openAiNativeApiKey, + deepSeekApiKey, + requestyApiKey, + togetherApiKey, + qwenApiKey, + doubaoApiKey, + mistralApiKey, + liteLlmApiKey, + fireworksApiKey, + asksageApiKey, + xaiApiKey, + sambanovaApiKey, + cerebrasApiKey, + nebiusApiKey, + sapAiCoreClientId, + sapAiCoreClientSecret, + } + + // Execute batched operations in parallel for maximum performance + await Promise.all([updateGlobalStateBatch(context, batchedGlobalUpdates), updateSecretsBatch(context, batchedSecretUpdates)]) } export async function resetWorkspaceState(context: vscode.ExtensionContext) { From d453eed582cbcbb05c2f9e82da62126edaab4dd3 Mon Sep 17 00:00:00 2001 From: Ara Date: Mon, 7 Jul 2025 19:23:41 -0600 Subject: [PATCH 28/43] feat: Globally persist plan/act mode across sessions and ensure proper workspace level persistance of chatsettings(for language) (#4646) * feat: Persist plan/act mode across sessions - Add mode persistence to global state storage - Load saved mode on controller initialization - Update state keys to include 'mode' as a valid global state key - Ensures user's selected mode (plan/act) is maintained between VS Code sessions * Split chat settings storage between global and workspace state - Move mode setting to global state for cross-workspace persistence - Store other chat settings in workspace state for project-specific configuration - Update state retrieval logic to merge global mode with workspace settings - Add chatSettings to LocalStateKey type definitions * Code Cleanup * Code Cleanup * Get the chatsettings back to global * Get the chatsettings back to global * Get the chatsettings back to global --------- Co-authored-by: Cline Evaluation --- .changeset/olive-weeks-wave.md | 5 +++++ src/core/controller/index.ts | 25 ++++++++++++++------- src/core/controller/state/updateSettings.ts | 11 ++++++++- src/core/storage/state-keys.ts | 1 + src/core/storage/state.ts | 5 ++++- 5 files changed, 37 insertions(+), 10 deletions(-) create mode 100644 .changeset/olive-weeks-wave.md diff --git a/.changeset/olive-weeks-wave.md b/.changeset/olive-weeks-wave.md new file mode 100644 index 00000000..6bed75af --- /dev/null +++ b/.changeset/olive-weeks-wave.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +persist plan and act between sessions diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 37e80aca..1a2340a0 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -54,7 +54,6 @@ export class Controller { private postMessage: (message: ExtensionMessage) => Thenable | undefined private disposables: vscode.Disposable[] = [] - private mode: "plan" | "act" = "plan" // In-memory plan/act mode state task?: Task workspaceTracker: WorkspaceTracker mcpHub: McpHub @@ -89,6 +88,10 @@ export class Controller { }) } + private async getCurrentMode(): Promise<"plan" | "act"> { + return ((await getGlobalState(this.context, "mode")) as "plan" | "act" | undefined) || "act" + } + /* VSCode extensions use the disposable pattern to clean up resources when the sidebar/editor tab is closed by the user or system. This applies to event listening, commands, interacting with the UI, etc. - https://vscode-docs.readthedocs.io/en/stable/extensions/patterns-and-principles/ @@ -141,10 +144,13 @@ export class Controller { taskHistory, } = await getAllExtensionState(this.context) - // Reconstruct ChatSettings with in-memory mode and stored preferences + // Get current mode using helper function + const currentMode = await this.getCurrentMode() + + // Reconstruct ChatSettings with mode from global state and stored preferences const chatSettings: ChatSettings = { ...storedChatSettings, // Spread stored preferences (preferredLanguage, openAIReasoningEffort) - mode: this.mode, // Use in-memory mode (override any stored mode) + mode: currentMode, // Use mode from global state } const NEW_USER_TASK_COUNT_THRESHOLD = 10 @@ -239,8 +245,8 @@ export class Controller { async togglePlanActModeWithChatSettings(chatSettings: ChatSettings, chatContent?: ChatContent): Promise { const didSwitchToActMode = chatSettings.mode === "act" - // Store mode in-memory only - this.mode = chatSettings.mode + // Store mode to global state + await updateGlobalState(this.context, "mode", chatSettings.mode) // Capture mode switch telemetry | Capture regardless of if we know the taskId telemetryService.captureModeSwitch(this.task?.taskId ?? "0", chatSettings.mode) @@ -394,7 +400,7 @@ export class Controller { } } - // Save only non-mode properties to workspace storage + // Save only non-mode properties to global storage const { mode, ...persistentChatSettings }: { mode: string } & StoredChatSettings = chatSettings await updateGlobalState(this.context, "chatSettings", persistentChatSettings) await this.postStateToWebview() @@ -837,10 +843,13 @@ export class Controller { terminalOutputLineLimit, } = await getAllExtensionState(this.context) - // Reconstruct ChatSettings with in-memory mode and stored preferences + // Get current mode using helper function + const currentMode = await this.getCurrentMode() + + // Reconstruct ChatSettings with mode from global state and stored preferences const chatSettings: ChatSettings = { ...storedChatSettings, // Spread stored preferences (preferredLanguage, openAIReasoningEffort) - mode: this.mode, // Use in-memory mode (override any stored mode) + mode: currentMode, // Use mode from global state } const localClineRulesToggles = diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts index bc5ec8ee..d20f5a7b 100644 --- a/src/core/controller/state/updateSettings.ts +++ b/src/core/controller/state/updateSettings.ts @@ -58,7 +58,16 @@ export async function updateSettings(controller: Controller, request: UpdateSett // Update chat settings if (request.chatSettings) { const chatSettings = convertProtoChatSettingsToChatSettings(request.chatSettings) - await controller.context.workspaceState.update("chatSettings", chatSettings) + + // Store mode to global state + if (chatSettings.mode !== undefined) { + await controller.context.globalState.update("mode", chatSettings.mode) + } + + // Store chat settings (excluding mode) to global state + const { mode, ...globalChatSettings } = chatSettings + await controller.context.globalState.update("chatSettings", globalChatSettings) + if (controller.task) { controller.task.chatSettings = chatSettings } diff --git a/src/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index 0f1d5753..94493331 100644 --- a/src/core/storage/state-keys.ts +++ b/src/core/storage/state-keys.ts @@ -80,6 +80,7 @@ export type GlobalStateKey = | "claudeCodePath" // Settings around plan/act and ephemeral model configuration | "chatSettings" + | "mode" // Current active model configuration (per workspace) | "apiProvider" | "apiModelId" diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index ec731536..13dc2bd2 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -218,6 +218,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { const secondBatchStart = performance.now() const [ chatSettings, + currentMode, storedApiProvider, apiModelId, thinkingBudgetTokens, @@ -249,6 +250,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { sapAiCoreModelId, ] = await Promise.all([ getGlobalState(context, "chatSettings") as Promise, + getGlobalState(context, "mode") as Promise<"plan" | "act" | undefined>, getGlobalState(context, "apiProvider") as Promise, getGlobalState(context, "apiModelId") as Promise, getGlobalState(context, "thinkingBudgetTokens") as Promise, @@ -403,7 +405,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { browserSettings: { ...DEFAULT_BROWSER_SETTINGS, ...browserSettings }, // this will ensure that older versions of browserSettings (e.g. before remoteBrowserEnabled was added) are merged with the default values (false for remoteBrowserEnabled) chatSettings: { ...DEFAULT_CHAT_SETTINGS, // Apply defaults first - ...(chatSettings || {}), // Spread fetched chatSettings, which includes preferredLanguage, and openAIReasoningEffort + ...(chatSettings || {}), // Spread fetched global chatSettings, which includes preferredLanguage, and openAIReasoningEffort + mode: currentMode || "act", // Merge mode from global state }, userInfo, previousModeApiProvider, From d30e4d0194556b11140e586e6b93123b0b88b5dc Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 7 Jul 2025 19:12:41 -0700 Subject: [PATCH 29/43] v3.18.5 Release Notes (#4704) * changeset version bump * Updating CHANGELOG.md format * Update CHANGELOG.md for version 3.18.5 --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: github-actions Co-authored-by: Cline Evaluation --- .changeset/olive-weeks-wave.md | 5 ----- .changeset/purple-rings-hide.md | 5 ----- .changeset/shy-waves-perform.md | 5 ----- CHANGELOG.md | 6 ++++++ package-lock.json | 4 ++-- package.json | 2 +- 6 files changed, 9 insertions(+), 18 deletions(-) delete mode 100644 .changeset/olive-weeks-wave.md delete mode 100644 .changeset/purple-rings-hide.md delete mode 100644 .changeset/shy-waves-perform.md diff --git a/.changeset/olive-weeks-wave.md b/.changeset/olive-weeks-wave.md deleted file mode 100644 index 6bed75af..00000000 --- a/.changeset/olive-weeks-wave.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -persist plan and act between sessions diff --git a/.changeset/purple-rings-hide.md b/.changeset/purple-rings-hide.md deleted file mode 100644 index 5c8d2d35..00000000 --- a/.changeset/purple-rings-hide.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Optimizing provider switching performance with batched storage operations diff --git a/.changeset/shy-waves-perform.md b/.changeset/shy-waves-perform.md deleted file mode 100644 index b9cf230e..00000000 --- a/.changeset/shy-waves-perform.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Reorder the models for SAP AI Core in a more organized and logical manner, grouping them by provider and model type diff --git a/CHANGELOG.md b/CHANGELOG.md index b05c5fd5..ab74baa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [3.18.5] + +- Fix Plan/Act mode persistence across sessions and multi-workspace conflicts +- Improve provider switching performance by 18x (from 550ms to 30ms) with batched storage operations +- Improve SAP AI Core provider model organization and fix exception handling (Thanks @schardosin!) + ## [3.18.4] - Add support for Gemini 2.5 Pro and Flash to SAP AI Core Provider diff --git a/package-lock.json b/package-lock.json index c196726a..37e74418 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.3", + "version": "3.18.5", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.3", + "version": "3.18.5", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index 2991d289..b5ef0f59 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.4", + "version": "3.18.5", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" From 0a6a565d4119be584bee22653bb5e6a390e67ba5 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 7 Jul 2025 19:40:14 -0700 Subject: [PATCH 30/43] Replace vscode.workspace.asRelativePath with the host bridge. (#4712) * Replace vscode.workspace.asRelativePath with the host bridge. Add a util function asRelativePath to path.ts that does the same thing as the vcode API (returns the path relative to the workspace directory). In the getRelativePaths protobus handler, don't allow @mentions for files outside the workspace, they do not work in cline, so just prevent them from being added at all. If the fs.stat fails for a file, don't @mention it either, if stat() fails it means the file doesn't exist or is unreadable. * Update src/core/controller/file/getRelativePaths.ts Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> * Update src/core/controller/file/getRelativePaths.ts Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> --------- Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> --- src/core/controller/file/getRelativePaths.ts | 67 ++++++++++---------- src/utils/path.ts | 10 +++ 2 files changed, 43 insertions(+), 34 deletions(-) diff --git a/src/core/controller/file/getRelativePaths.ts b/src/core/controller/file/getRelativePaths.ts index c606ae46..58e54353 100644 --- a/src/core/controller/file/getRelativePaths.ts +++ b/src/core/controller/file/getRelativePaths.ts @@ -1,8 +1,10 @@ -import { Controller } from ".." -import { RelativePathsRequest, RelativePaths } from "@shared/proto/file" -import { FileMethodHandler } from "./index" -import * as vscode from "vscode" +import { asRelativePath } from "@/utils/path" +import { RelativePaths, RelativePathsRequest } from "@shared/proto/file" +import { promises as fs } from "fs" import * as path from "path" +import { URI } from "vscode-uri" +import { Controller } from ".." +import { FileMethodHandler } from "./index" /** * Converts a list of URIs to workspace-relative paths @@ -14,37 +16,34 @@ export const getRelativePaths: FileMethodHandler = async ( _controller: Controller, request: RelativePathsRequest, ): Promise => { - const resolvedPaths = await Promise.all( - request.uris.map(async (uriString) => { - try { - const fileUri = vscode.Uri.parse(uriString, true) - const relativePathToGet = vscode.workspace.asRelativePath(fileUri, false) + const result = [] + for (const uriString of request.uris) { + try { + result.push(await getRelativePath(uriString)) + } catch (error) { + console.error(`Error calculating relative path for ${uriString}:`, error) + } + } + return RelativePaths.create({ paths: result }) +} - // If the path is still absolute, it's outside the workspace - if (path.isAbsolute(relativePathToGet)) { - console.warn(`Dropped file ${relativePathToGet} is outside the workspace. Sending original path.`) - return fileUri.fsPath.replace(/\\/g, "/") - } else { - let finalPath = "/" + relativePathToGet.replace(/\\/g, "/") - try { - const stat = await vscode.workspace.fs.stat(fileUri) - if (stat.type === vscode.FileType.Directory) { - finalPath += "/" - } - } catch (statError) { - console.error(`Error stating file ${fileUri.fsPath}:`, statError) - } - return finalPath - } - } catch (error) { - console.error(`Error calculating relative path for ${uriString}:`, error) - return null - } - }), - ) +async function getRelativePath(uriString: string): Promise { + const filePath = URI.parse(uriString, true).fsPath + const relativePath = await asRelativePath(filePath) - // Filter out any null values from errors - const validPaths = resolvedPaths.filter((path): path is string => path !== null) + // If the path is still absolute, it's outside the workspace + if (path.isAbsolute(relativePath)) { + throw new Error(`Dropped file ${relativePath} is outside the workspace.`) + } - return RelativePaths.create({ paths: validPaths }) + let result = "/" + relativePath.replace(/\\/g, "/") + if (await isDir(filePath)) { + result += "/" + } + return result +} + +async function isDir(filePath: string): Promise { + const stats = await fs.stat(filePath) + return stats.isDirectory() } diff --git a/src/utils/path.ts b/src/utils/path.ts index 3c4205a4..f62d231a 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -160,3 +160,13 @@ export function isLocatedInPath(dirPath: string, pathToCheck: string): boolean { } return true } + +export async function asRelativePath(filePath: string): Promise { + const workspacePaths = await getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) + for (const workspacePath of workspacePaths.paths) { + if (isLocatedInPath(workspacePath, filePath)) { + return path.relative(workspacePath, filePath) + } + } + return filePath +} From bc468707a6c83b473361e5dae297fa1cf75e0f58 Mon Sep 17 00:00:00 2001 From: tjandy98 <3953059+tjandy98@users.noreply.github.com> Date: Tue, 8 Jul 2025 12:09:41 +0800 Subject: [PATCH 31/43] Add header for SAP AI Core Tracking (#4696) * Add support for Gemini 2.5 Pro and Flash models Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> * Create calm-ads-glow.md * Update request header Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> Add ai-client-type header for tracking Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> Create little-lions-joke.md Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> update changeset Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> update Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> --------- Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com> --- .changeset/little-lions-joke.md | 5 +++++ src/api/providers/sapaicore.ts | 2 ++ 2 files changed, 7 insertions(+) create mode 100644 .changeset/little-lions-joke.md diff --git a/.changeset/little-lions-joke.md b/.changeset/little-lions-joke.md new file mode 100644 index 00000000..b4d90b4b --- /dev/null +++ b/.changeset/little-lions-joke.md @@ -0,0 +1,5 @@ +--- +"claude-dev": minor +--- + +Update request header to include `"ai-client-type": "Cline"` diff --git a/src/api/providers/sapaicore.ts b/src/api/providers/sapaicore.ts index d858f435..4a2d32ed 100644 --- a/src/api/providers/sapaicore.ts +++ b/src/api/providers/sapaicore.ts @@ -60,6 +60,7 @@ export class SapAiCoreHandler implements ApiHandler { Authorization: `Bearer ${token}`, "AI-Resource-Group": this.options.sapAiResourceGroup || "default", "Content-Type": "application/json", + "AI-Client-Type": "Cline", } const url = `${this.options.sapAiCoreBaseUrl}/v2/lm/deployments?$top=10000&$skip=0` @@ -116,6 +117,7 @@ export class SapAiCoreHandler implements ApiHandler { Authorization: `Bearer ${token}`, "AI-Resource-Group": this.options.sapAiResourceGroup || "default", "Content-Type": "application/json", + "AI-Client-Type": "Cline", } const model = this.getModel() From ff4bab22fbf16a968bc911b65c74ad8412eb39db Mon Sep 17 00:00:00 2001 From: canvrno <46584286+canvrno@users.noreply.github.com> Date: Tue, 8 Jul 2025 10:47:12 -0700 Subject: [PATCH 32/43] host bridge migration - openExternal (#4502) --- .changeset/gorgeous-apes-fry.md | 5 +++++ proto/host/env.proto | 3 +++ .../controller/account/accountLoginClicked.ts | 3 ++- src/core/controller/web/openInBrowser.ts | 4 ++-- src/core/mentions/index.ts | 3 ++- src/hosts/vscode/env/openExternal.ts | 8 ++++++++ src/integrations/editor/detect-omission.ts | 7 +++---- src/utils/env.ts | 15 +++++++++++++++ src/utils/github-url-utils.ts | 13 ++++++------- 9 files changed, 46 insertions(+), 15 deletions(-) create mode 100644 .changeset/gorgeous-apes-fry.md create mode 100644 src/hosts/vscode/env/openExternal.ts diff --git a/.changeset/gorgeous-apes-fry.md b/.changeset/gorgeous-apes-fry.md new file mode 100644 index 00000000..e35440ca --- /dev/null +++ b/.changeset/gorgeous-apes-fry.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +host bridge migration - openExternal diff --git a/proto/host/env.proto b/proto/host/env.proto index 9d769c1e..00248900 100644 --- a/proto/host/env.proto +++ b/proto/host/env.proto @@ -13,4 +13,7 @@ service EnvService { // Reads text from the system clipboard. rpc clipboardReadText(cline.EmptyRequest) returns (cline.String); + + // Opens a URL in the user's default browser or application. + rpc openExternal(cline.StringRequest) returns (cline.Empty); } diff --git a/src/core/controller/account/accountLoginClicked.ts b/src/core/controller/account/accountLoginClicked.ts index 11648c18..0938d1ff 100644 --- a/src/core/controller/account/accountLoginClicked.ts +++ b/src/core/controller/account/accountLoginClicked.ts @@ -3,6 +3,7 @@ import crypto from "crypto" import { Controller } from "../index" import { storeSecret } from "../../storage/state" import { EmptyRequest, String } from "../../../shared/proto/common" +import { openExternal } from "@utils/env" /** * Handles the user clicking the login link in the UI. @@ -26,7 +27,7 @@ export async function accountLoginClicked(controller: Controller, _: EmptyReques const authUrl = vscode.Uri.parse( `https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`, ) - await vscode.env.openExternal(authUrl) + await openExternal(authUrl.toString()) return String.create({ value: authUrl.toString(), }) diff --git a/src/core/controller/web/openInBrowser.ts b/src/core/controller/web/openInBrowser.ts index e31d86d6..24216ada 100644 --- a/src/core/controller/web/openInBrowser.ts +++ b/src/core/controller/web/openInBrowser.ts @@ -1,6 +1,6 @@ -import * as vscode from "vscode" import { Controller } from ".." import { Empty, StringRequest } from "../../../shared/proto/common" +import { openExternal } from "@utils/env" /** * Opens a URL in the user's default browser @@ -11,7 +11,7 @@ import { Empty, StringRequest } from "../../../shared/proto/common" export async function openInBrowser(controller: Controller, request: StringRequest): Promise { try { if (request.value) { - await vscode.env.openExternal(vscode.Uri.parse(request.value)) + await openExternal(request.value) } return Empty.create() } catch (error) { diff --git a/src/core/mentions/index.ts b/src/core/mentions/index.ts index 6a8bbb01..623248e4 100644 --- a/src/core/mentions/index.ts +++ b/src/core/mentions/index.ts @@ -12,6 +12,7 @@ import { getCommitInfo } from "@utils/git" import { getWorkingState } from "@utils/git" import { FileContextTracker } from "../context/context-tracking/FileContextTracker" import { getCwd } from "@/utils/path" +import { openExternal } from "@utils/env" export async function openMention(mention?: string): Promise { if (!mention) { @@ -36,7 +37,7 @@ export async function openMention(mention?: string): Promise { } else if (mention === "terminal") { vscode.commands.executeCommand("workbench.action.terminal.focus") } else if (mention.startsWith("http")) { - vscode.env.openExternal(vscode.Uri.parse(mention)) + await openExternal(mention) } } diff --git a/src/hosts/vscode/env/openExternal.ts b/src/hosts/vscode/env/openExternal.ts new file mode 100644 index 00000000..73a90e3a --- /dev/null +++ b/src/hosts/vscode/env/openExternal.ts @@ -0,0 +1,8 @@ +import { Empty, StringRequest } from "@/shared/proto/common" +import * as vscode from "vscode" + +export async function openExternal(request: StringRequest): Promise { + console.log("openExternal called with request:", request) + await vscode.env.openExternal(vscode.Uri.parse(request.value)) + return Empty.create() +} diff --git a/src/integrations/editor/detect-omission.ts b/src/integrations/editor/detect-omission.ts index 32de0aac..8d6afefb 100644 --- a/src/integrations/editor/detect-omission.ts +++ b/src/integrations/editor/detect-omission.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode" +import { openExternal } from "@utils/env" /** * Detects potential AI-generated code omissions in the given file content. @@ -47,10 +48,8 @@ export function showOmissionWarning(originalFileContent: string, newFileContent: ) .then((selection) => { if (selection === "Follow this guide to fix the issue") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://github.com/cline/cline/wiki/Troubleshooting-%E2%80%90-Cline-Deleting-Code-with-%22Rest-of-Code-Here%22-Comments", - ), + openExternal( + "https://github.com/cline/cline/wiki/Troubleshooting-%E2%80%90-Cline-Deleting-Code-with-%22Rest-of-Code-Here%22-Comments", ) } }) diff --git a/src/utils/env.ts b/src/utils/env.ts index 832f049b..15d55f77 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -30,3 +30,18 @@ export async function readTextFromClipboard(): Promise { throw new Error(`Failed to read from clipboard: ${errorMessage}`) } } + +/** + * Opens an external URL in the default browser + * @param url The URL to open + * @returns Promise that resolves when the operation is complete + * @throws Error if the operation fails + */ +export async function openExternal(url: string): Promise { + try { + await getHostBridgeProvider().envClient.openExternal(StringRequest.create({ value: url })) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error) + throw new Error(`Failed to open external URL: ${errorMessage}`) + } +} diff --git a/src/utils/github-url-utils.ts b/src/utils/github-url-utils.ts index 9ef4a96a..2e6f3727 100644 --- a/src/utils/github-url-utils.ts +++ b/src/utils/github-url-utils.ts @@ -17,7 +17,7 @@ import * as vscode from "vscode" import * as cp from "child_process" import * as os from "os" import * as util from "util" -import { writeTextToClipboard } from "@/utils/env" +import { writeTextToClipboard, openExternal } from "@/utils/env" /** * Creates a properly encoded GitHub issue URL. @@ -141,16 +141,15 @@ export async function openUrlInBrowser(url: string): Promise { } catch (error) { console.error(`OS commands failed: ${error}`) - // First fallback: Try VS Code's openExternal + // First fallback: Try openExternal utility // Note: This will likely have encoding issues per https://github.com/microsoft/vscode/issues/85930 // but we include it as a fallback in case OS commands completely fail try { - // The 'true' parameter might help preserve some encodings, but this is not guaranteed - await vscode.env.openExternal(vscode.Uri.parse(url, true)) - console.log("Opened URL with vscode.env.openExternal (note: URL encoding may be affected)") + await openExternal(url) + console.log("Opened URL with openExternal utility (note: URL encoding may be affected)") return - } catch (vscodeError) { - console.error(`Error with vscode.env.openExternal: ${vscodeError}`) + } catch (openExternalError) { + console.error(`Error with openExternal utility: ${openExternalError}`) // Last fallback: Show a message with instructions vscode.window From 265a56391a944061dc1914ab8d774bdbc6a50367 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Tue, 8 Jul 2025 10:49:56 -0700 Subject: [PATCH 33/43] Replace vscode.workspace.fs.stat with fs.stat (#4714) Use the util function that already exists isDirectory from utils/fs.ts Use the same function in getRelativePaths --- src/core/controller/file/getRelativePaths.ts | 9 ++------- src/integrations/workspace/WorkspaceTracker.ts | 6 +++--- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/core/controller/file/getRelativePaths.ts b/src/core/controller/file/getRelativePaths.ts index 58e54353..8dfb330b 100644 --- a/src/core/controller/file/getRelativePaths.ts +++ b/src/core/controller/file/getRelativePaths.ts @@ -1,10 +1,10 @@ import { asRelativePath } from "@/utils/path" import { RelativePaths, RelativePathsRequest } from "@shared/proto/file" -import { promises as fs } from "fs" import * as path from "path" import { URI } from "vscode-uri" import { Controller } from ".." import { FileMethodHandler } from "./index" +import { isDirectory } from "@/utils/fs" /** * Converts a list of URIs to workspace-relative paths @@ -37,13 +37,8 @@ async function getRelativePath(uriString: string): Promise { } let result = "/" + relativePath.replace(/\\/g, "/") - if (await isDir(filePath)) { + if (await isDirectory(filePath)) { result += "/" } return result } - -async function isDir(filePath: string): Promise { - const stats = await fs.stat(filePath) - return stats.isDirectory() -} diff --git a/src/integrations/workspace/WorkspaceTracker.ts b/src/integrations/workspace/WorkspaceTracker.ts index 7a589dbc..5127335b 100644 --- a/src/integrations/workspace/WorkspaceTracker.ts +++ b/src/integrations/workspace/WorkspaceTracker.ts @@ -3,6 +3,7 @@ import * as path from "path" import { listFiles } from "@services/glob/list-files" import { sendWorkspaceUpdateEvent } from "@core/controller/file/subscribeToWorkspaceUpdates" import { getCwd } from "@/utils/path" +import { isDirectory } from "@/utils/fs" // Note: this is not a drop-in replacement for listFiles at the start of tasks, since that will be done for Desktops when there is no workspace selected class WorkspaceTracker { @@ -114,9 +115,8 @@ class WorkspaceTracker { private async addFilePath(filePath: string): Promise { const normalizedPath = this.normalizeFilePath(filePath) try { - const stat = await vscode.workspace.fs.stat(vscode.Uri.file(normalizedPath)) - const isDirectory = (stat.type & vscode.FileType.Directory) !== 0 - const pathWithSlash = isDirectory && !normalizedPath.endsWith("/") ? normalizedPath + "/" : normalizedPath + const isDir = await isDirectory(normalizedPath) + const pathWithSlash = isDir && !normalizedPath.endsWith("/") ? normalizedPath + "/" : normalizedPath this.filePaths.add(pathWithSlash) return pathWithSlash } catch { From 386c78c114228aec7e8424d9826238f05e6ad288 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Tue, 8 Jul 2025 10:50:10 -0700 Subject: [PATCH 34/43] Update the no-vscode-postmessage eslint rule to check for any of the vscode SDK calls that have been replaced (#4715) * Update the no-vscode-postmessage eslint rule to check for all the vscode SDK calls that have been replaced. Expand the rule to check for all of the vscode SDK calls that have been switched to the host bridge or replaced with native functions. * Remove redundant messages --- .eslintrc.json | 1 + .../__tests__/no-direct-vscode-api.test.ts | 123 +++++++++++++ .../__tests__/no-vscode-postmessage.test.ts | 74 -------- eslint-rules/index.js | 6 +- eslint-rules/no-direct-vscode-api.js | 164 ++++++++++++++++++ eslint-rules/no-vscode-postmessage.js | 61 ------- webview-ui/.eslintrc.json | 2 +- 7 files changed, 292 insertions(+), 139 deletions(-) create mode 100644 eslint-rules/__tests__/no-direct-vscode-api.test.ts delete mode 100644 eslint-rules/__tests__/no-vscode-postmessage.test.ts create mode 100644 eslint-rules/no-direct-vscode-api.js delete mode 100644 eslint-rules/no-vscode-postmessage.js diff --git a/.eslintrc.json b/.eslintrc.json index ab454150..d1d568c6 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -22,6 +22,7 @@ "react-hooks/exhaustive-deps": "off", "eslint-rules/no-protobuf-object-literals": "error", "eslint-rules/no-grpc-client-object-literals": "error", + "eslint-rules/no-direct-vscode-api": "warn", "no-restricted-syntax": [ "error", { diff --git a/eslint-rules/__tests__/no-direct-vscode-api.test.ts b/eslint-rules/__tests__/no-direct-vscode-api.test.ts new file mode 100644 index 00000000..730f53b8 --- /dev/null +++ b/eslint-rules/__tests__/no-direct-vscode-api.test.ts @@ -0,0 +1,123 @@ +const { RuleTester: DirectApiRuleTester } = require("eslint") +const noDirectVscodeApiRule = require("../no-direct-vscode-api") + +const directApiRuleTester = new DirectApiRuleTester({ + parser: require.resolve("@typescript-eslint/parser"), + parserOptions: { + ecmaVersion: 2020, + sourceType: "module", + ecmaFeatures: { + jsx: true, + }, + }, +}) + +directApiRuleTester.run("no-direct-vscode-api", noDirectVscodeApiRule, { + valid: [ + // Should allow vscode.postMessage in grpc-client-base.ts + { + code: `vscode.postMessage({ type: "grpc_request", data: {} })`, + filename: "grpc-client-base.ts", + }, + { + code: `vscode.postMessage({ type: "grpc_request_cancel" })`, + filename: "/path/to/grpc-client-base.ts", + }, + // Should allow in exception directories + { + code: `vscode.workspace.workspaceFolders`, + filename: "/src/hosts/vscode/host-bridge.ts", + }, + { + code: `vscode.workspace.fs.stat(uri)`, + filename: "/standalone/runtime-files/helpers.ts", + }, + // Should allow other vscode API calls + { + code: `vscode.window.showInformationMessage("Hello")`, + filename: "test.ts", + }, + // Should allow postMessage calls on other objects + { + code: `window.postMessage({ type: "test" }, "*")`, + filename: "test.ts", + }, + // Should allow variables named vscode but not calling postMessage + { + code: `const vscode = { other: "method" }; vscode.other()`, + filename: "test.ts", + }, + ], + invalid: [ + // Should disallow vscode.postMessage in regular files + { + code: `vscode.postMessage({ type: "test", data: {} })`, + filename: "test.ts", + errors: [ + { + messageId: "useGrpcClient", + }, + ], + }, + // Should disallow vscode.postMessage in components + { + code: `vscode.postMessage({ type: "apiConfiguration", apiConfiguration })`, + filename: "ApiOptions.tsx", + errors: [ + { + messageId: "useGrpcClient", + }, + ], + }, + // Should disallow vscode.postMessage in test files + { + code: `vscode.postMessage({ type: "newTask", text: message.text })`, + filename: "test.test.ts", + errors: [ + { + messageId: "useGrpcClient", + }, + ], + }, + // Should disallow property access for disallowed APIs + { + code: `const folders = vscode.workspace.workspaceFolders;`, + filename: "workspace.ts", + errors: [ + { + messageId: "useHostBridge", + }, + ], + }, + // Should disallow method calls for disallowed APIs + { + code: `const relativePath = vscode.workspace.asRelativePath(filePath);`, + filename: "path-utils.ts", + errors: [ + { + messageId: "usePathUtils", + }, + ], + }, + // Should disallow nested property access + { + code: `const stats = await vscode.workspace.fs.stat(uri);`, + filename: "file-utils.ts", + errors: [ + { + messageId: "useFsUtils", + }, + ], + }, + // Should disallow getting a workspace folder + { + code: `const folder = vscode.workspace.getWorkspaceFolder(uri);`, + filename: "path-helper.ts", + errors: [ + { + messageId: "usePathUtils", + }, + ], + }, + ], +}) diff --git a/eslint-rules/__tests__/no-vscode-postmessage.test.ts b/eslint-rules/__tests__/no-vscode-postmessage.test.ts deleted file mode 100644 index 0db0dec2..00000000 --- a/eslint-rules/__tests__/no-vscode-postmessage.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -const { RuleTester: VscodeRuleTester } = require("eslint") -const vscodePostmessageRule = require("../no-vscode-postmessage") - -const vscodeRuleTester = new VscodeRuleTester({ - parser: require.resolve("@typescript-eslint/parser"), - parserOptions: { - ecmaVersion: 2020, - sourceType: "module", - ecmaFeatures: { - jsx: true, - }, - }, -}) - -vscodeRuleTester.run("no-vscode-postmessage", vscodePostmessageRule, { - valid: [ - // Should allow vscode.postMessage in grpc-client-base.ts - { - code: `vscode.postMessage({ type: "grpc_request", data: {} })`, - filename: "grpc-client-base.ts", - }, - { - code: `vscode.postMessage({ type: "grpc_request_cancel" })`, - filename: "/path/to/grpc-client-base.ts", - }, - // Should allow other vscode API calls - { - code: `vscode.window.showInformationMessage("Hello")`, - filename: "test.ts", - }, - // Should allow postMessage calls on other objects - { - code: `window.postMessage({ type: "test" }, "*")`, - filename: "test.ts", - }, - // Should allow variables named vscode but not calling postMessage - { - code: `const vscode = { other: "method" }; vscode.other()`, - filename: "test.ts", - }, - ], - invalid: [ - // Should ban vscode.postMessage in regular files - { - code: `vscode.postMessage({ type: "test", data: {} })`, - filename: "test.ts", - errors: [ - { - messageId: "useGrpcClient", - }, - ], - }, - // Should ban vscode.postMessage in components - { - code: `vscode.postMessage({ type: "apiConfiguration", apiConfiguration })`, - filename: "ApiOptions.tsx", - errors: [ - { - messageId: "useGrpcClient", - }, - ], - }, - // Should ban vscode.postMessage in test files - { - code: `vscode.postMessage({ type: "newTask", text: message.text })`, - filename: "test.test.ts", - errors: [ - { - messageId: "useGrpcClient", - }, - ], - }, - ], -}) diff --git a/eslint-rules/index.js b/eslint-rules/index.js index a7c8e72b..6952bccf 100644 --- a/eslint-rules/index.js +++ b/eslint-rules/index.js @@ -1,13 +1,13 @@ // eslint-rules/index.js const noProtobufObjectLiterals = require("./no-protobuf-object-literals") const noGrpcClientObjectLiterals = require("./no-grpc-client-object-literals") -const noVscodePostmessage = require("./no-vscode-postmessage") +const noDirectVscodeApi = require("./no-direct-vscode-api") module.exports = { rules: { "no-protobuf-object-literals": noProtobufObjectLiterals, "no-grpc-client-object-literals": noGrpcClientObjectLiterals, - "no-vscode-postmessage": noVscodePostmessage, + "no-direct-vscode-api": noDirectVscodeApi, }, configs: { recommended: { @@ -15,7 +15,7 @@ module.exports = { rules: { "local/no-protobuf-object-literals": "error", "local/no-grpc-client-object-literals": "error", - "local/no-vscode-postmessage": "error", + "local/no-direct-vscode-api": "warn", }, }, }, diff --git a/eslint-rules/no-direct-vscode-api.js b/eslint-rules/no-direct-vscode-api.js new file mode 100644 index 00000000..395106d8 --- /dev/null +++ b/eslint-rules/no-direct-vscode-api.js @@ -0,0 +1,164 @@ +const { ESLintUtils } = require("@typescript-eslint/utils") +const path = require("path") + +const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`) + +// Configuration of disallowed VSCode APIs and their recommended alternatives +const disallowedApis = { + "vscode.postMessage": { + messageId: "useGrpcClient", + }, + "vscode.workspace.fs.stat": { + messageId: "useFsUtils", + }, + "vscode.workspace.workspaceFolders": { + messageId: "useHostBridge", + }, + "vscode.workspace.asRelativePath": { + messageId: "usePathUtils", + }, + "vscode.workspace.getWorkspaceFolder": { + messageId: "usePathUtils", + }, +} + +module.exports = createRule({ + name: "no-direct-vscode-api", + meta: { + type: "problem", + docs: { + description: + "Disallow direct VSCode API usage in favor of Cline's abstraction layers, except in src/hosts/vscode and standalone/runtime-files directories", + recommended: "error", + }, + messages: { + useGrpcClient: + "Use gRPC service clients instead of vscode.postMessage().\n" + + "Example: AccountServiceClient.methodName(RequestType.create({...})) instead of vscode.postMessage({type: '...'}).\n" + + "Found: {{code}}", + useFsUtils: + "Use utilities in @/utils/fs instead of vscode.workspace.fs.stat.\n" + + "Example: import { isDirectory } from '@/utils/fs' or use the file system methods from the host bridge provider.\n" + + "Found: {{code}}", + useHostBridge: + "Use getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) instead of vscode.workspace.workspaceFolders.\n" + + "This provides a consistent abstraction across VSCode and standalone environments.\n" + + "Found: {{code}}", + usePathUtils: + "Use path utilities from @/utils/path instead of direct VSCode workspace path methods.\n" + + "This provides consistent path handling across different environments.\n" + + "Found: {{code}}", + }, + schema: [], + }, + defaultOptions: [], + + create(context) { + // Check if current file is in an exception directory or is grpc-client-base.ts + const filename = context.filename + const isGrpcClientBase = path.basename(filename) === "grpc-client-base.ts" + + // Skip checking files in src/hosts/vscode or standalone/runtime-files + const isExceptionDirectory = filename.includes("/src/hosts/vscode/") || filename.includes("/standalone/runtime-files/") + + // Pattern for checking memberExpressions like vscode.workspace.fs.stat + function checkMemberExpression(node) { + // Skip if this file is in an exception directory or is grpc-client-base.ts + if (isGrpcClientBase || isExceptionDirectory) { + return + } + + // For handling nested properties like vscode.workspace.fs.stat + function getFullPropertyPath(node) { + if (node.type !== "MemberExpression") { + return node.name || "" + } + + const objectPart = getFullPropertyPath(node.object) + const propertyPart = node.property.name || "" + + return objectPart ? `${objectPart}.${propertyPart}` : propertyPart + } + + // Check if the expression matches one of our disallowed patterns + if (node.object && node.object.type === "Identifier" && node.object.name === "vscode") { + const fullPath = `vscode.${node.property.name}` + checkDisallowedApi(fullPath, node) + } + // Handle nested expressions like vscode.workspace.fs.stat + else if (node.object && node.object.type === "MemberExpression") { + const fullPath = getFullPropertyPath(node) + + // Only proceed if it starts with vscode + if (fullPath.startsWith("vscode.")) { + checkDisallowedApi(fullPath, node) + } + } + } + + // Check if an expression matches a disallowed API and report if it does + function checkDisallowedApi(expressionPath, node) { + // Check exact matches + if (disallowedApis[expressionPath]) { + reportViolation(expressionPath, node) + return + } + + // Check prefix matches (for nested properties) + for (const disallowedApi in disallowedApis) { + // For direct property access like vscode.workspace.workspaceFolders + if (expressionPath === disallowedApi) { + reportViolation(disallowedApi, node) + return + } + + // For method calls like vscode.workspace.asRelativePath(...) + if (expressionPath.startsWith(`${disallowedApi}.`) || expressionPath.startsWith(`${disallowedApi}(`)) { + reportViolation(disallowedApi, node) + return + } + } + } + + // Report a violation with the appropriate message + function reportViolation(disallowedApi, node) { + const sourceCode = context.sourceCode + const config = disallowedApis[disallowedApi] + + // For method calls, get the whole call expression + let reportNode = node + let parentNode = sourceCode.getAncestors(node).pop() + if (parentNode && parentNode.type === "CallExpression" && parentNode.callee === node) { + reportNode = parentNode + } + + const callText = sourceCode.getText(reportNode).trim() + + context.report({ + node: reportNode, + messageId: config.messageId, + data: { + code: callText, + }, + }) + } + + return { + // Detect basic member expressions (e.g., vscode.postMessage) + MemberExpression(node) { + checkMemberExpression(node) + }, + + // Detect property access through destructuring + VariableDeclarator(node) { + // Skip if this file is in an exception directory or is grpc-client-base.ts + if (isGrpcClientBase || isExceptionDirectory) { + return + } + + // Destructuring pattern checks removed as developers don't use the API this way + // They always use direct imports: import * as vscode from "vscode" and direct access: vscode.thing.foo + }, + } + }, +}) diff --git a/eslint-rules/no-vscode-postmessage.js b/eslint-rules/no-vscode-postmessage.js deleted file mode 100644 index 83c24e5a..00000000 --- a/eslint-rules/no-vscode-postmessage.js +++ /dev/null @@ -1,61 +0,0 @@ -const { ESLintUtils } = require("@typescript-eslint/utils") -const path = require("path") - -const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`) - -module.exports = createRule({ - name: "no-vscode-postmessage", - meta: { - type: "problem", - docs: { - description: "Ban vscode.postMessage() calls in favor of gRPC service clients, except in grpc-client-base.ts", - recommended: "error", - }, - messages: { - useGrpcClient: - "Use gRPC service clients instead of vscode.postMessage().\n" + - "Example: AccountServiceClient.methodName(RequestType.create({...})) instead of vscode.postMessage({type: '...'}).\n" + - "Found: {{code}}", - }, - schema: [], - }, - defaultOptions: [], - - create(context) { - // Check if current file is grpc-client-base.ts (exception case) - const filename = context.filename - const isGrpcClientBase = path.basename(filename) === "grpc-client-base.ts" - - return { - // Detect vscode.postMessage calls - "CallExpression[callee.type='MemberExpression']"(node) { - // Skip if this is grpc-client-base.ts - if (isGrpcClientBase) { - return - } - - const callee = node.callee - - // Check for vscode.postMessage pattern - if ( - callee.object && - callee.object.type === "Identifier" && - callee.object.name === "vscode" && - callee.property && - callee.property.name === "postMessage" - ) { - const sourceCode = context.sourceCode - const callText = sourceCode.getText(node).trim() - - context.report({ - node, - messageId: "useGrpcClient", - data: { - code: callText, - }, - }) - } - }, - } - }, -}) diff --git a/webview-ui/.eslintrc.json b/webview-ui/.eslintrc.json index 4cd7edd2..2ee7221c 100644 --- a/webview-ui/.eslintrc.json +++ b/webview-ui/.eslintrc.json @@ -28,7 +28,7 @@ "no-extra-semi": "off", "eslint-rules/no-protobuf-object-literals": "error", "eslint-rules/no-grpc-client-object-literals": "error", - "eslint-rules/no-vscode-postmessage": "warn", + "eslint-rules/no-direct-vscode-api": "warn", "no-restricted-syntax": [ "error", { From 267170920a714b6c00eafff22c00aa117676a736 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Tue, 8 Jul 2025 11:16:49 -0700 Subject: [PATCH 35/43] Update the packaging script for the standalone app to include the same files as the extension in the zip (#4708) * Package the same files for the standalone app and the extension When packaging the standalone app use the same .vscodeignore that the vscode packager uses to decide which files to include. Exclude extra files from the vscode extension that aren't needed: dist-standalone, old_docs and eslint-rules. * Ignore the whole directory, not just the contents. * Don't package .DS_Store files * Update comment --- .vscodeignore | 4 + scripts/package-standalone.mjs | 157 ++++++++++++++++++--------------- 2 files changed, 91 insertions(+), 70 deletions(-) diff --git a/.vscodeignore b/.vscodeignore index f6d27022..29bf22d2 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -2,8 +2,10 @@ .vscode/** .vscode-test/** out/** +dist-standalone/** node_modules/** src/** +standalone/** .gitignore .yarnrc esbuild.js @@ -13,6 +15,7 @@ vsc-extension-quickstart.md **/*.map **/*.ts **/.vscode-test.* +eslint-rules/** # Custom demo.gif @@ -32,6 +35,7 @@ webview-ui/node_modules/** # Ignore docs docs/** +old_docs/** # Fix issue where codicons don't get packaged (https://github.com/microsoft/vscode-extension-samples/issues/692) !node_modules/@vscode/codicons/dist/codicon.css diff --git a/scripts/package-standalone.mjs b/scripts/package-standalone.mjs index 473399cb..620861fc 100644 --- a/scripts/package-standalone.mjs +++ b/scripts/package-standalone.mjs @@ -1,83 +1,100 @@ -import fs from "fs" -import path from "path" -import { glob } from "glob" import archiver from "archiver" -import { cp } from "fs/promises" import { execSync } from "child_process" - +import fs from "fs" +import { cp } from "fs/promises" +import { glob } from "glob" +import ignore from "ignore" +import path from "path" const BUILD_DIR = "dist-standalone" -const SOURCE_DIR = "standalone/runtime-files" +const RUNTIME_DEPS_DIR = "standalone/runtime-files" -await cp(SOURCE_DIR, BUILD_DIR, { recursive: true }) - -// Run npm install in the distribution directory -console.log("Running npm install in distribution directory...") -const cwd = process.cwd() -process.chdir(BUILD_DIR) -try { - execSync("npm install", { stdio: "inherit" }) - // Move the vscode directory into node_modules. - // It can't be installed using npm because it will create a symlink which is not portable. - fs.renameSync("vscode", path.join("node_modules", "vscode")) -} catch (error) { - console.error("Error during setup:", error) - process.exit(1) -} finally { - process.chdir(cwd) +async function main() { + await installNodeDependencies() + await zipDistribution() } -// Check for native .node modules. -const nativeModules = await glob("**/*.node", { cwd: BUILD_DIR, nodir: true }) -if (nativeModules.length > 0) { - console.error("Native node modules cannot be included in the standalone distribution:\n", nativeModules.join("\n")) - process.exit(1) +async function installNodeDependencies() { + await cpr(RUNTIME_DEPS_DIR, BUILD_DIR) + + console.log("Running npm install in distribution directory...") + const cwd = process.cwd() + process.chdir(BUILD_DIR) + + try { + execSync("npm install", { stdio: "inherit" }) + // Move the vscode directory into node_modules. + // It can't be installed using npm because it will create a symlink which cannot be unzipped correctly on windows. + fs.renameSync("vscode", path.join("node_modules", "vscode")) + } catch (error) { + console.error("Error during setup:", error) + process.exit(1) + } finally { + process.chdir(cwd) + } + + // Check for native .node modules. + const nativeModules = await glob("**/*.node", { cwd: BUILD_DIR, nodir: true }) + if (nativeModules.length > 0) { + console.error("Native node modules cannot be included in the standalone distribution:\n", nativeModules.join("\n")) + process.exit(1) + } } -// Zip the build directory (excluding any pre-existing output zip). -const zipPath = path.join(BUILD_DIR, "standalone.zip") -const output = fs.createWriteStream(zipPath) -const archive = archiver("zip", { zlib: { level: 3 } }) +async function zipDistribution() { + // Zip the build directory (excluding any pre-existing output zip). + const zipPath = path.join(BUILD_DIR, "standalone.zip") + const output = fs.createWriteStream(zipPath) + const archive = archiver("zip", { zlib: { level: 3 } }) + // Use the same ignore file that vscode uses when packaging the extension. + const vscodeignore = ignore().add(fs.readFileSync(".vscodeignore", "utf8")) -output.on("close", () => { - console.log(`Created ${zipPath} (${(archive.pointer() / 1024 / 1024).toFixed(1)} MB)`) -}) -archive.on("warning", (err) => { - console.warn(`Warning: ${err}`) -}) -archive.on("error", (err) => { - throw err -}) + output.on("close", () => { + console.log(`Created ${zipPath} (${(archive.pointer() / 1024 / 1024).toFixed(1)} MB)`) + }) + archive.on("warning", (err) => { + console.warn(`Warning: ${err}`) + }) + archive.on("error", (err) => { + throw err + }) -archive.pipe(output) -archive.glob("**/*", { - cwd: BUILD_DIR, - ignore: ["standalone.zip"], -}) + archive.pipe(output) + // Add all the files from the standalone build dir. + archive.glob("**/*", { + cwd: BUILD_DIR, + ignore: ["standalone.zip"], + }) -// Add the whole cline directory under "extension" -archive.directory(process.cwd(), "extension", (entry) => { - // Skip certain directories. - const exclude = [ - BUILD_DIR + "/", - "node_modules/", // node_modules nearly 1GB. - "webview-ui/node_modules/", // node_modules nearly 1GB. - ] - // These node modules are used at runtime as assets, they need to be included. - const include = ["node_modules/@vscode/", "webview-ui/node_modules/katex"] - const name = entry.name - - if (include.some((prefix) => name.startsWith(prefix))) { + // Add the whole cline directory under "extension" + archive.directory(process.cwd(), "extension", (entry) => { + if (entry.name.startsWith(".git")) { + return false + } + if (entry.name.endsWith(".DS_Store")) { + return false + } + if (entry.name === "dist" || entry.name.startsWith("dist" + path.sep)) { + // Don't include the vscode extension build dir. + return false + } + if (vscodeignore.ignores(entry.name)) { + // Exclude entries also ignored by the vscode packager. + return false + } return entry - } - if (exclude.some((prefix) => name.startsWith(prefix))) { - return false - } - if (name.match(/(^|\/)\./)) { - // exclude dot directories - return false - } - return entry -}) + }) -console.log("Zipping package...") -await archive.finalize() + console.log("Zipping package...") + await archive.finalize() +} + +/* cp -r */ +async function cpr(source, dest) { + await cp(source, dest, { + recursive: true, + preserveTimestamps: true, + dereference: false, // preserve symlinks instead of following them + }) +} + +await main() From 1e81d98abfe8de267d6703416d4c1f11600bc2c6 Mon Sep 17 00:00:00 2001 From: Bee <68532117+abeatrix@users.noreply.github.com> Date: Tue, 8 Jul 2025 15:05:11 -0700 Subject: [PATCH 36/43] Fix fresh install mode launch config (#4732) * Fix fresh install mode launch config Updates the launch configuration in `.vscode/launch.json` to include a temporary profile and user data directory. This fixes the issue where the launch config does not start in fresh install mode for extension development. This change prevents interference from existing settings and extensions. The `--user-data-dir=/tmp/cline/user` argument specifies a temporary directory for user data, while `--profile-temp` ensures a clean profile is used for each launch. Also, `--sync=off` is added to disable settings sync. * update name * tmp dir * Implement in-memory storage for temporary profiles Adds in-memory storage for global state, workspace state, and secrets when running in a temporary profile. This is determined by the `TEMP_PROFILE` environment variable being set to "true". When active, the `updateGlobalState`, `getGlobalState`, `updateGlobalStateBatch`, `updateSecretsBatch`, `storeSecret`, `getSecret`, `updateWorkspaceState`, and `getWorkspaceState` functions will use `Map` objects to store and retrieve data instead of VS Code's `globalState`, `secrets`, and `workspaceState` APIs. This ensures that no data is persisted to disk when using a temporary profile, providing a clean environment for testing and development. * Refactor tmp user directory for dev launch config This commit refactors the temporary user directory used in the development launch configuration. - Updates `.vscode/launch.json` to use `${workspaceFolder}/dist/tmp/user` for the `--user-data-dir` argument, ensuring the temporary profile is located within the workspace. - Adds `TEMP_PROFILE: "true"` to the environment variables in `.vscode/launch.json` to enable in-memory storage for temporary profiles. - Renames the `clean-sandbox` task in `.vscode/tasks.json` to `clean-tmp-user` and modifies its command to remove and recreate the `${workspaceFolder}/dist/tmp/user` directory. This ensures a clean environment for each launch. --------- Co-authored-by: abeatrix --- .vscode/launch.json | 7 +++--- .vscode/tasks.json | 4 ++-- src/core/storage/state.ts | 48 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 5 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index d22ed942..eb126021 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -23,19 +23,20 @@ "request": "launch", "runtimeExecutable": "${execPath}", "args": [ + "--user-data-dir=${workspaceFolder}/dist/tmp/user", "--profile-temp", - "--sync", - "off", + "--sync=off", "--disable-extensions", "--extensionDevelopmentPath=${workspaceFolder}", "${workspaceFolder}" ], "outFiles": ["${workspaceFolder}/dist/**/*.js"], - "preLaunchTask": "clean-sandbox", + "preLaunchTask": "clean-tmp-user", "internalConsoleOptions": "openOnSessionStart", "postDebugTask": "stop", "env": { "IS_DEV": "true", + "TEMP_PROFILE": "true", "DEV_WORKSPACE_FOLDER": "${workspaceFolder}" } }, diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 5e47a904..d461eaaa 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -233,10 +233,10 @@ "type": "shell" }, { - "label": "clean-sandbox", + "label": "clean-tmp-user", "type": "shell", "dependsOn": ["watch"], - "command": "rm -rf .vscode-dev" + "command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user" } ], "inputs": [ diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index 13dc2bd2..bd33a6b5 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -18,23 +18,53 @@ import { migrateEnableCheckpointsSetting, migrateMcpMarketplaceEnableSetting } f https://www.eliostruyf.com/devhack-code-extension-storage-options/ */ +const isTemporaryProfile = process.env.TEMP_PROFILE === "true" + +// In-memory storage for temporary profiles +const inMemoryGlobalState = new Map() +const inMemoryWorkspaceState = new Map() +const inMemorySecrets = new Map() + // global export async function updateGlobalState(context: vscode.ExtensionContext, key: GlobalStateKey, value: any) { + if (isTemporaryProfile) { + inMemoryGlobalState.set(key, value) + return + } await context.globalState.update(key, value) } export async function getGlobalState(context: vscode.ExtensionContext, key: GlobalStateKey) { + if (isTemporaryProfile) { + return inMemoryGlobalState.get(key) + } return await context.globalState.get(key) } // Batched operations for performance optimization export async function updateGlobalStateBatch(context: vscode.ExtensionContext, updates: Record) { + if (isTemporaryProfile) { + Object.entries(updates).forEach(([key, value]) => { + inMemoryGlobalState.set(key, value) + }) + return + } // Use Promise.all to batch the updates await Promise.all(Object.entries(updates).map(([key, value]) => context.globalState.update(key as GlobalStateKey, value))) } export async function updateSecretsBatch(context: vscode.ExtensionContext, updates: Record) { + if (isTemporaryProfile) { + Object.entries(updates).forEach(([key, value]) => { + if (value) { + inMemorySecrets.set(key, value) + } else { + inMemorySecrets.delete(key) + } + }) + return + } // Use Promise.all to batch the secret updates await Promise.all(Object.entries(updates).map(([key, value]) => storeSecret(context, key as SecretKey, value))) } @@ -42,6 +72,14 @@ export async function updateSecretsBatch(context: vscode.ExtensionContext, updat // secrets export async function storeSecret(context: vscode.ExtensionContext, key: SecretKey, value?: string) { + if (isTemporaryProfile) { + if (value) { + inMemorySecrets.set(key, value) + } else { + inMemorySecrets.delete(key) + } + return + } if (value) { await context.secrets.store(key, value) } else { @@ -50,16 +88,26 @@ export async function storeSecret(context: vscode.ExtensionContext, key: SecretK } export async function getSecret(context: vscode.ExtensionContext, key: SecretKey) { + if (isTemporaryProfile) { + return inMemorySecrets.get(key) + } return await context.secrets.get(key) } // workspace export async function updateWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey, value: any) { + if (isTemporaryProfile) { + inMemoryWorkspaceState.set(key, value) + return + } await context.workspaceState.update(key, value) } export async function getWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey) { + if (isTemporaryProfile) { + return inMemoryWorkspaceState.get(key) + } return await context.workspaceState.get(key) } From 6f8627bb5f42c1185717ba674c0298152e99ad52 Mon Sep 17 00:00:00 2001 From: Dennise Bartlett Date: Tue, 8 Jul 2025 15:59:08 -0700 Subject: [PATCH 37/43] Organization Accounts added to Extension. Refactor Auth components for Accounts * Working organization and personal inference, account switching, and usage/credit reporting. * Organization dropdown tweaks (#4710) * organization dropdown tweaks * reverted AuthService * Update Firebase Provider and Auth Service to support re-hydration of the user credentials * Add Github Auth Flow * Fix merge conflicts * Fix some dumb typing * recreate dropdown value when initialized (#4716) * added changeset * Update urls to production and handle some PR concerns * Get user credits when signing in (#4736) * get user balance when signing in instead of when there is no active org * swapped order of getUserCredits, made calls async * async changes continued, moved setIsLoading to finally --------- Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com> Co-authored-by: pashpashpash --- .changeset/three-gifts-add.md | 5 + proto/account.proto | 139 ++++--- proto/browser.proto | 3 +- proto/checkpoints.proto | 3 +- proto/file.proto | 3 +- proto/mcp.proto | 3 +- proto/models.proto | 5 +- proto/slash.proto | 3 +- proto/state.proto | 5 +- proto/task.proto | 3 +- proto/ui.proto | 3 +- proto/web.proto | 3 +- src/api/providers/cline.ts | 287 +++++++++----- .../controller/account/accountLoginClicked.ts | 24 +- .../account/accountLogoutClicked.ts | 3 + .../controller/account/authStateChanged.ts | 6 +- .../account/getOrganizationCredits.ts | 50 +++ ...chUserCreditsData.ts => getUserCredits.ts} | 9 +- .../account/getUserOrganizations.ts | 35 ++ .../controller/account/setUserOrganization.ts | 24 ++ .../account/subscribeToAuthCallback.ts | 59 --- .../account/subscribeToAuthStatusUpdate.ts | 5 + src/core/controller/index.ts | 35 +- src/core/storage/state-keys.ts | 2 +- src/core/storage/state-migrations.ts | 2 +- src/core/storage/state.ts | 15 +- src/extension.ts | 17 +- src/services/account/ClineAccountService.ts | 202 ++++++++-- src/services/auth/AuthService.ts | 364 ++++++++++++++++++ src/services/auth/config.ts | 10 - .../auth/providers/FirebaseAuthProvider.ts | 172 +++++++++ src/services/test/TestServer.ts | 5 +- src/shared/ClineAccount.ts | 71 +++- src/shared/ExtensionMessage.ts | 6 +- src/shared/UserInfo.ts | 2 +- src/shared/api.ts | 2 +- .../models/api-configuration-conversion.ts | 4 +- .../state/settings-conversion.ts | 4 +- src/test/suite/extension.test.js | 56 --- src/test/suite/index.js | 43 --- webview-ui/src/App.tsx | 1 - webview-ui/src/Providers.tsx | 6 +- .../src/components/account/AccountView.tsx | 188 ++++++--- .../account/CreditsHistoryTable.tsx | 19 +- .../settings/ClineAccountInfoCard.tsx | 8 +- webview-ui/src/context/ClineAuthContext.tsx | 84 ++++ .../src/context/ExtensionStateContext.tsx | 7 +- .../src/context/FirebaseAuthContext.tsx | 126 ------ webview-ui/src/services/grpc-client-base.js | 126 ++++++ .../src/services/grpc-client-base.js.map | 1 + webview-ui/src/services/grpc-client.js | 39 ++ webview-ui/src/services/grpc-client.js.map | 1 + webview-ui/src/utils/validate.ts | 2 +- webview-ui/src/utils/vscode.js | 71 ++++ webview-ui/src/utils/vscode.js.map | 1 + 55 files changed, 1731 insertions(+), 641 deletions(-) create mode 100644 .changeset/three-gifts-add.md create mode 100644 src/core/controller/account/getOrganizationCredits.ts rename src/core/controller/account/{fetchUserCreditsData.ts => getUserCredits.ts} (70%) create mode 100644 src/core/controller/account/getUserOrganizations.ts create mode 100644 src/core/controller/account/setUserOrganization.ts delete mode 100644 src/core/controller/account/subscribeToAuthCallback.ts create mode 100644 src/core/controller/account/subscribeToAuthStatusUpdate.ts create mode 100644 src/services/auth/AuthService.ts delete mode 100644 src/services/auth/config.ts create mode 100644 src/services/auth/providers/FirebaseAuthProvider.ts delete mode 100644 src/test/suite/extension.test.js delete mode 100644 src/test/suite/index.js create mode 100644 webview-ui/src/context/ClineAuthContext.tsx delete mode 100644 webview-ui/src/context/FirebaseAuthContext.tsx create mode 100644 webview-ui/src/services/grpc-client-base.js create mode 100644 webview-ui/src/services/grpc-client-base.js.map create mode 100644 webview-ui/src/services/grpc-client.js create mode 100644 webview-ui/src/services/grpc-client.js.map create mode 100644 webview-ui/src/utils/vscode.js create mode 100644 webview-ui/src/utils/vscode.js.map diff --git a/.changeset/three-gifts-add.md b/.changeset/three-gifts-add.md new file mode 100644 index 00000000..16cdac02 --- /dev/null +++ b/.changeset/three-gifts-add.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Add organization and personal account management with credit reporting and account switching diff --git a/proto/account.proto b/proto/account.proto index 85c0842d..d0a72bf1 100644 --- a/proto/account.proto +++ b/proto/account.proto @@ -1,76 +1,129 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - // Service for account-related operations service AccountService { - // Handles the user clicking the login link in the UI. - // Generates a secure nonce for state validation, stores it in secrets, - // and opens the authentication URL in the external browser. - rpc accountLoginClicked(EmptyRequest) returns (String); + // Handles the user clicking the login link in the UI. + // Generates a secure nonce for state validation, stores it in secrets, + // and opens the authentication URL in the external browser. + rpc accountLoginClicked(EmptyRequest) returns (String); - // Handles the user clicking the logout button in the UI. - // Clears API keys and user state. - rpc accountLogoutClicked(EmptyRequest) returns (Empty); + // Handles the user clicking the logout button in the UI. + // Clears API keys and user state. + rpc accountLogoutClicked(EmptyRequest) returns (Empty); - // Subscribe to auth callback events (when authentication tokens are received) - rpc subscribeToAuthCallback(EmptyRequest) returns (stream String); + // Subscribe to auth status update events (when authentication state changes) + rpc subscribeToAuthStatusUpdate(EmptyRequest) + returns (stream AuthState); - // Handles authentication state changes from the Firebase context. - // Updates the user info in global state and returns the updated value. - rpc authStateChanged(AuthStateChangedRequest) returns (AuthStateChanged); + // Handles authentication state changes from the Firebase context. + // Updates the user info in global state and returns the updated value. + rpc authStateChanged(AuthStateChangedRequest) + returns (AuthState); - // Fetches all user credits data (balance, usage transactions, payment transactions) - rpc fetchUserCreditsData(EmptyRequest) returns (UserCreditsData); + // Fetches all user credits data + // (balance, usage transactions, payment transactions) + rpc getUserCredits(EmptyRequest) returns (UserCreditsData); + + rpc getOrganizationCredits(GetOrganizationCreditsRequest) returns (OrganizationCreditsData); + + // Fetches all user organizations data + // Returns a list of UserOrganization objects + rpc getUserOrganizations(EmptyRequest) returns (UserOrganizationsResponse); + + rpc setUserOrganization(UserOrganizationUpdateRequest) returns (Empty); } message AuthStateChangedRequest { - Metadata metadata = 1; - UserInfo user = 2; + Metadata metadata = 1; + UserInfo user = 2; } -message AuthStateChanged { - optional UserInfo user = 1; +message AuthState { + optional UserInfo user = 1; } +// User's information message UserInfo { - optional string display_name = 1; - optional string email = 2; - optional string photo_url = 3; + string uid = 1; + optional string display_name = 2; + optional string email = 3; + optional string photo_url = 4; +} + +message UserOrganization { + bool active = 1; + string member_id = 2; + string name = 3; + string organization_id = 4; + repeated string roles = 5; // ["admin", "member", "owner"] +} + +message UserOrganizationsResponse { + repeated UserOrganization organizations = 1; +} + +message UserOrganizationUpdateRequest { + optional string organization_id = 1; } -// Response containing all user credits data message UserCreditsData { - UserCreditsBalance balance = 1; - repeated UsageTransaction usage_transactions = 2; - repeated PaymentTransaction payment_transactions = 3; + UserCreditsBalance balance = 1; + repeated UsageTransaction usage_transactions = 2; + repeated PaymentTransaction payment_transactions = 3; +} + +message GetOrganizationCreditsRequest { + string organization_id = 1; +} + +message OrganizationCreditsData { + UserCreditsBalance balance = 1; + string organization_id = 2; + repeated OrganizationUsageTransaction usage_transactions = 3; } -// User's current credit balance message UserCreditsBalance { - double current_balance = 1; + double current_balance = 1; } -// Usage transaction record message UsageTransaction { - string spent_at = 1; - string creator_id = 2; - double credits = 3; - string model_provider = 4; - string model = 5; - int32 prompt_tokens = 6; - int32 completion_tokens = 7; - int32 total_tokens = 8; + string ai_inference_provider_name = 1; + string ai_model_name = 2; + string ai_model_type_name = 3; + int32 completion_tokens = 4; + double cost_usd = 5; + string created_at = 6; + double credits_used = 7; + string generation_id = 8; + string organization_id = 9; + int32 prompt_tokens = 10; + int32 total_tokens = 11; + string user_id = 12; } -// Payment transaction record message PaymentTransaction { - string paid_at = 1; - string creator_id = 2; - int32 amount_cents = 3; - double credits = 4; + string paid_at = 1; + string creator_id = 2; + int32 amount_cents = 3; + double credits = 4; } + +message OrganizationUsageTransaction { + string ai_inference_provider_name = 1; + string ai_model_name = 2; + string ai_model_type_name = 3; + int32 completion_tokens = 4; + double cost_usd = 5; + string created_at = 6; + double credits_used = 7; + string generation_id = 8; + string organization_id = 9; + int32 prompt_tokens = 10; + int32 total_tokens = 11; + string user_id = 12; +} \ No newline at end of file diff --git a/proto/browser.proto b/proto/browser.proto index cef58729..1aeaddb0 100644 --- a/proto/browser.proto +++ b/proto/browser.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - service BrowserService { rpc getBrowserConnectionInfo(EmptyRequest) returns (BrowserConnectionInfo); rpc testBrowserConnection(StringRequest) returns (BrowserConnection); diff --git a/proto/checkpoints.proto b/proto/checkpoints.proto index d4e88833..894fd340 100644 --- a/proto/checkpoints.proto +++ b/proto/checkpoints.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - service CheckpointsService { rpc checkpointDiff(Int64Request) returns (Empty); rpc checkpointRestore(CheckpointRestoreRequest) returns (Empty); diff --git a/proto/file.proto b/proto/file.proto index f61638aa..5ae83104 100644 --- a/proto/file.proto +++ b/proto/file.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - // Service for file-related operations service FileService { // Copies text to clipboard diff --git a/proto/mcp.proto b/proto/mcp.proto index 00d8b249..a0e21dc1 100644 --- a/proto/mcp.proto +++ b/proto/mcp.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - service McpService { rpc toggleMcpServer(ToggleMcpServerRequest) returns (McpServers); rpc updateMcpTimeout(UpdateMcpTimeoutRequest) returns (McpServers); diff --git a/proto/models.proto b/proto/models.proto index 5f60fdbf..328d8425 100644 --- a/proto/models.proto +++ b/proto/models.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - // Service for model-related operations service ModelsService { // Fetches available models from Ollama @@ -165,7 +164,7 @@ message ModelsApiConfiguration { // From ApiHandlerOptions (excluding onRetryAttempt function) optional string api_model_id = 1; optional string api_key = 2; - optional string cline_api_key = 3; + optional string cline_account_id = 3; optional string task_id = 4; optional string lite_llm_base_url = 5; optional string lite_llm_model_id = 6; diff --git a/proto/slash.proto b/proto/slash.proto index db0590a6..70badcd5 100644 --- a/proto/slash.proto +++ b/proto/slash.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - // SlashService provides methods for managing slash service SlashService { // Sends button click message diff --git a/proto/state.proto b/proto/state.proto index b9dccb34..f34adafd 100644 --- a/proto/state.proto +++ b/proto/state.proto @@ -1,10 +1,9 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - service StateService { rpc getLatestState(EmptyRequest) returns (State); rpc updateTerminalConnectionTimeout(Int64Request) returns (Int64); @@ -126,7 +125,7 @@ message ApiConfiguration { optional string api_base_url = 4; // Provider-specific API keys - optional string cline_api_key = 5; + optional string cline_account_id = 5; optional string openrouter_api_key = 6; optional string anthropic_base_url = 7; optional string openai_api_key = 8; diff --git a/proto/task.proto b/proto/task.proto index 0949cd17..aa4f6219 100644 --- a/proto/task.proto +++ b/proto/task.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - service TaskService { // Cancels the currently running task rpc cancelTask(EmptyRequest) returns (Empty); diff --git a/proto/ui.proto b/proto/ui.proto index 48a7f47a..ffe86232 100644 --- a/proto/ui.proto +++ b/proto/ui.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - // Enum for webview provider types enum WebviewProviderType { SIDEBAR = 0; diff --git a/proto/web.proto b/proto/web.proto index 0df3b6e8..e87e7c77 100644 --- a/proto/web.proto +++ b/proto/web.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline; +import "common.proto"; option java_package = "bot.cline.proto"; option java_multiple_files = true; -import "common.proto"; - service WebService { rpc checkIsImageUrl(StringRequest) returns (IsImageUrl); rpc fetchOpenGraphData(StringRequest) returns (OpenGraphData); diff --git a/src/api/providers/cline.ts b/src/api/providers/cline.ts index 1c535182..3ba0a70d 100644 --- a/src/api/providers/cline.ts +++ b/src/api/providers/cline.ts @@ -1,157 +1,234 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" import { ApiHandler } from "../" +import { ClineAccountService } from "@/services/account/ClineAccountService" import { ApiHandlerOptions, ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api" import { createOpenRouterStream } from "../transform/openrouter-stream" import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" -import axios from "axios" +import axios, { AxiosRequestConfig, AxiosResponse } from "axios" import { OpenRouterErrorResponse } from "./types" import { withRetry } from "../retry" +import { AuthService } from "@/services/auth/AuthService" export class ClineHandler implements ApiHandler { private options: ApiHandlerOptions - private client: OpenAI | undefined + private clineAccountService = ClineAccountService.getInstance() + private _authService: AuthService + // TODO: replace this with a global API Host + private readonly _baseUrl = "https://api.cline.bot" + // private readonly _baseUrl = "https://core-api.staging.int.cline.bot" + // private readonly _baseUrl = "http://localhost:7777" lastGenerationId?: string + private counter = 0 constructor(options: ApiHandlerOptions) { this.options = options - } - - private ensureClient(): OpenAI { - if (!this.client) { - if (!this.options.clineApiKey) { - throw new Error("You don't seem to be logged in to a Cline account.") - } - try { - this.client = new OpenAI({ - baseURL: "https://api.cline.bot/v1", - apiKey: this.options.clineApiKey || "", - defaultHeaders: { - "HTTP-Referer": "https://cline.bot", // Optional, for including your app on cline.bot rankings. - "X-Title": "Cline", // Optional. Shows in rankings on cline.bot. - "X-Task-ID": this.options.taskId || "", // Include the task ID in the request headers - }, - }) - } catch (error) { - throw new Error(`Error creating Cline client: ${error.message}`) - } - } - return this.client + this._authService = AuthService.getInstance() } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { - const client = this.ensureClient() + const clineAccountAuthToken = await this._authService.getAuthToken() + this.lastGenerationId = undefined - const stream = await createOpenRouterStream( - client, - systemPrompt, - messages, - this.getModel(), - this.options.reasoningEffort, - this.options.thinkingBudgetTokens, - this.options.openRouterProviderSorting, + const requestConfig: AxiosRequestConfig = { + headers: { + "HTTP-Referer": "https://cline.bot", // Optional, for including your app on cline.bot rankings. + "X-Title": "Cline", // Optional. Shows in rankings on cline.bot. + "X-Task-ID": this.options.taskId || "", // Include the task ID in the request headers + Authorization: `Bearer ${clineAccountAuthToken}`, + }, + timeout: 15_000, // Set a timeout for requests to avoid hanging + } + + const me = await this.clineAccountService.fetchMe() + console.log( + "SwitchAuthToken: Active Organization", + me?.organizations.filter((org) => org.active)[0]?.name || "No active organization", ) let didOutputUsage: boolean = false - for await (const chunk of stream) { - // openrouter returns an error object instead of the openai sdk throwing an error - if ("error" in chunk) { - const error = chunk.error as OpenRouterErrorResponse["error"] - console.error(`Cline API Error: ${error?.code} - ${error?.message}`) - // Include metadata in the error message if available - const metadataStr = error.metadata ? `\nMetadata: ${JSON.stringify(error.metadata, null, 2)}` : "" - throw new Error(`Cline API Error ${error.code}: ${error.message}${metadataStr}`) + const url = `${this._baseUrl}/api/v1/chat/completions` + try { + const response = await axios.post( + url, + { + model: this.getModel().id, + messages: [ + { + role: "system", + content: systemPrompt, + }, + ...messages, + ], + stream: false, + // reasoning_effort: this.options.reasoningEffort || "low", + // thinking_budget_tokens: this.options.thinkingBudgetTokens || 0, + // open_router_provider_sorting: this.options.openRouterProviderSorting || "default", + }, + requestConfig, + ) + + if (!response.data || !response.data.data) { + throw new Error(`Request to ${url} failed with status ${response.status}`) } - if (!this.lastGenerationId && chunk.id) { - this.lastGenerationId = chunk.id + if (!response.data.data.choices || response.data.data.choices.length === 0) { + throw new Error(`No choices returned from Cline API: ${JSON.stringify(response.data)}`) } - // Check for mid-stream error via finish_reason - const choice = chunk.choices?.[0] - // OpenRouter may return finish_reason = "error" with error details - if ((choice?.finish_reason as string) === "error") { - const choiceWithError = choice as any - if (choiceWithError.error) { - const error = choiceWithError.error - console.error(`Cline Mid-Stream Error: ${error.code || error.type || "Unknown"} - ${error.message}`) - throw new Error(`Cline Mid-Stream Error: ${error.code || error.type || "Unknown"} - ${error.message}`) - } else { - throw new Error("Cline Mid-Stream Error: Stream terminated with error status but no error details provided") + for (const choice of response.data.data.choices) { + if (choice.finish_reason === "error") { + const error = choice.error || { code: "Unknown", message: "No error details provided" } + console.error(`Cline API Error: ${error.code} - ${error.message}`) + throw new Error(`Cline API Error: ${error.code} - ${error.message}`) } - } - - const delta = choice?.delta - if (delta?.content) { - yield { - type: "text", - text: delta.content, + if (choice.delta && choice.delta.content) { + yield { + type: "text", + text: choice.delta.content, + } } - } - - // Reasoning tokens are returned separately from the content - if ("reasoning" in delta && delta.reasoning) { - yield { - type: "reasoning", - // @ts-ignore-next-line - reasoning: delta.reasoning, + if (choice.delta && choice.delta.reasoning) { + yield { + type: "reasoning", + reasoning: choice.delta.reasoning, + } } - } - - if (!didOutputUsage && chunk.usage) { - // @ts-ignore-next-line - let totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0) - const modelId = this.getModel().id - const provider = modelId.split("/")[0] - - // If provider is x-ai, set totalCost to 0 (we're doing a promo) - if (provider === "x-ai") { - totalCost = 0 + if (choice.message && choice.message.content) { + yield { + type: "text", + text: choice.message.content, + } } - - if (modelId.includes("gemini")) { + if (choice.usage) { + const totalCost = choice.usage.cost || 0 yield { type: "usage", cacheWriteTokens: 0, - cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0, - inputTokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0), - outputTokens: chunk.usage.completion_tokens || 0, - // @ts-ignore-next-line - totalCost, - } - } else { - yield { - type: "usage", - cacheWriteTokens: 0, - cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0, - inputTokens: chunk.usage.prompt_tokens || 0, - outputTokens: chunk.usage.completion_tokens || 0, - // @ts-ignore-next-line + cacheReadTokens: choice.usage.cached_tokens || 0, + inputTokens: choice.usage.prompt_tokens || 0, + outputTokens: choice.usage.completion_tokens || 0, totalCost, } } + } + + if (response.data.data.usage) { didOutputUsage = true + yield { + type: "usage", + cacheWriteTokens: 0, + cacheReadTokens: response.data.data.usage.prompt_tokens_details?.cached_tokens || 0, + inputTokens: response.data.data.usage.prompt_tokens || 0, + outputTokens: response.data.data.usage.completion_tokens || 0, + totalCost: response.data.data.usage.cost || 0, + } } - } - // Fallback to generation endpoint if usage chunk not returned - if (!didOutputUsage) { - const apiStreamUsage = await this.getApiStreamUsage() - if (apiStreamUsage) { - yield apiStreamUsage + // for await (const chunk of stream) { + // // openrouter returns an error object instead of the openai sdk throwing an error + // if ("error" in chunk) { + // const error = chunk.error as OpenRouterErrorResponse["error"] + // console.error(`Cline API Error: ${error?.code} - ${error?.message}`) + // // Include metadata in the error message if available + // const metadataStr = error.metadata ? `\nMetadata: ${JSON.stringify(error.metadata, null, 2)}` : "" + // throw new Error(`Cline API Error ${error.code}: ${error.message}${metadataStr}`) + // } + // if (!this.lastGenerationId && chunk.id) { + // this.lastGenerationId = chunk.id + // } + + // // Check for mid-stream error via finish_reason + // const choice = chunk.choices?.[0] + // // OpenRouter may return finish_reason = "error" with error details + // if ((choice?.finish_reason as string) === "error") { + // const choiceWithError = choice as any + // if (choiceWithError.error) { + // const error = choiceWithError.error + // console.error(`Cline Mid-Stream Error: ${error.code || error.type || "Unknown"} - ${error.message}`) + // throw new Error(`Cline Mid-Stream Error: ${error.code || error.type || "Unknown"} - ${error.message}`) + // } else { + // throw new Error("Cline Mid-Stream Error: Stream terminated with error status but no error details provided") + // } + // } + + // const delta = choice?.delta + // if (delta?.content) { + // yield { + // type: "text", + // text: delta.content, + // } + // } + + // // Reasoning tokens are returned separately from the content + // if ("reasoning" in delta && delta.reasoning) { + // yield { + // type: "reasoning", + // // @ts-ignore-next-line + // reasoning: delta.reasoning, + // } + // } + + // if (!didOutputUsage && chunk.usage) { + // // @ts-ignore-next-line + // let totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0) + // const modelId = this.getModel().id + // const provider = modelId.split("/")[0] + + // // If provider is x-ai, set totalCost to 0 (we're doing a promo) + // if (provider === "x-ai") { + // totalCost = 0 + // } + + // if (modelId.includes("gemini")) { + // yield { + // type: "usage", + // cacheWriteTokens: 0, + // cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0, + // inputTokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0), + // outputTokens: chunk.usage.completion_tokens || 0, + // // @ts-ignore-next-line + // totalCost, + // } + // } else { + // yield { + // type: "usage", + // cacheWriteTokens: 0, + // cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0, + // inputTokens: chunk.usage.prompt_tokens || 0, + // outputTokens: chunk.usage.completion_tokens || 0, + // // @ts-ignore-next-line + // totalCost, + // } + // } + // didOutputUsage = true + // } + // } + + // Fallback to generation endpoint if usage chunk not returned + if (!didOutputUsage) { + console.warn("Cline API did not return usage chunk, fetching from generation endpoint") + // const apiStreamUsage = await this.getApiStreamUsage() + // if (apiStreamUsage) { + // yield apiStreamUsage + // } } + } catch (error) { + console.error("Cline API Error:", error) } } async getApiStreamUsage(): Promise { if (this.lastGenerationId) { try { - const response = await axios.get(`https://api.cline.bot/v1/generation?id=${this.lastGenerationId}`, { + // TODO: replace this with firebase auth + // TODO: use global API Host + + const response = await axios.get(`${this.clineAccountService.baseUrl}/generation?id=${this.lastGenerationId}`, { headers: { - Authorization: `Bearer ${this.options.clineApiKey}`, + Authorization: `Bearer ${this.options.clineAccountId}`, }, timeout: 15_000, // this request hangs sometimes }) diff --git a/src/core/controller/account/accountLoginClicked.ts b/src/core/controller/account/accountLoginClicked.ts index 0938d1ff..d0284b4f 100644 --- a/src/core/controller/account/accountLoginClicked.ts +++ b/src/core/controller/account/accountLoginClicked.ts @@ -1,10 +1,10 @@ -import * as vscode from "vscode" -import crypto from "crypto" import { Controller } from "../index" -import { storeSecret } from "../../storage/state" +import { AuthService } from "@/services/auth/AuthService" import { EmptyRequest, String } from "../../../shared/proto/common" import { openExternal } from "@utils/env" +const authService = AuthService.getInstance() + /** * Handles the user clicking the login link in the UI. * Generates a secure nonce for state validation, stores it in secrets, @@ -14,21 +14,5 @@ import { openExternal } from "@utils/env" * @returns The login URL as a string. */ export async function accountLoginClicked(controller: Controller, _: EmptyRequest): Promise { - // Generate nonce for state validation - const nonce = crypto.randomBytes(32).toString("hex") - await storeSecret(controller.context, "authNonce", nonce) - - // Open browser for authentication with state param - console.log("Login button clicked in account page") - console.log("Opening auth page with state param") - - const uriScheme = vscode.env.uriScheme - - const authUrl = vscode.Uri.parse( - `https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`, - ) - await openExternal(authUrl.toString()) - return String.create({ - value: authUrl.toString(), - }) + return await authService.createAuthRequest() } diff --git a/src/core/controller/account/accountLogoutClicked.ts b/src/core/controller/account/accountLogoutClicked.ts index 523b7eed..9938953d 100644 --- a/src/core/controller/account/accountLogoutClicked.ts +++ b/src/core/controller/account/accountLogoutClicked.ts @@ -1,7 +1,9 @@ +import { AuthService } from "@/services/auth/AuthService" import { Empty } from "../../../shared/proto/common" import type { EmptyRequest } from "../../../shared/proto/common" import type { Controller } from "../index" +const authService = AuthService.getInstance() /** * Handles the account logout action * @param controller The controller instance @@ -10,5 +12,6 @@ import type { Controller } from "../index" */ export async function accountLogoutClicked(controller: Controller, _request: EmptyRequest): Promise { await controller.handleSignOut() + await authService.handleDeauth() return Empty.create({}) } diff --git a/src/core/controller/account/authStateChanged.ts b/src/core/controller/account/authStateChanged.ts index c3b67240..f7a97320 100644 --- a/src/core/controller/account/authStateChanged.ts +++ b/src/core/controller/account/authStateChanged.ts @@ -1,4 +1,4 @@ -import { AuthStateChangedRequest, AuthStateChanged } from "@shared/proto/account" +import { AuthStateChangedRequest, AuthState } from "@shared/proto/account" import type { Controller } from "../index" import { updateGlobalState } from "../../storage/state" @@ -9,13 +9,13 @@ import { updateGlobalState } from "../../storage/state" * @param request The auth state change request * @returns The updated user info */ -export async function authStateChanged(controller: Controller, request: AuthStateChangedRequest): Promise { +export async function authStateChanged(controller: Controller, request: AuthStateChangedRequest): Promise { try { // Store the user info directly in global state await updateGlobalState(controller.context, "userInfo", request.user) // Return the same user info - return AuthStateChanged.create({ user: request.user }) + return AuthState.create({ user: request.user }) } catch (error) { console.error(`Failed to update auth state: ${error}`) throw error diff --git a/src/core/controller/account/getOrganizationCredits.ts b/src/core/controller/account/getOrganizationCredits.ts new file mode 100644 index 00000000..b7249da4 --- /dev/null +++ b/src/core/controller/account/getOrganizationCredits.ts @@ -0,0 +1,50 @@ +import type { Controller } from "../index" +import { GetOrganizationCreditsRequest, OrganizationCreditsData, OrganizationUsageTransaction } from "@shared/proto/account" + +/** + * Handles fetching all organization credits data (balance, usage, payments) + * @param controller The controller instance + * @param request Organization credits request + * @returns Organization credits data response + */ +export async function getOrganizationCredits( + controller: Controller, + request: GetOrganizationCreditsRequest, +): Promise { + try { + if (!controller.accountService) { + throw new Error("Account service not available") + } + + // Call the individual RPC variants in parallel + const [balanceData, usageTransactions] = await Promise.all([ + controller.accountService.fetchOrganizationCreditsRPC(request.organizationId), + controller.accountService.fetchOrganizationUsageTransactionsRPC(request.organizationId), + ]) + + return OrganizationCreditsData.create({ + balance: balanceData ? { currentBalance: balanceData.balance / 100 } : { currentBalance: 0 }, + organizationId: balanceData?.organizationId || "", + usageTransactions: + usageTransactions?.map((tx) => + OrganizationUsageTransaction.create({ + aiInferenceProviderName: tx.aiInferenceProviderName, + aiModelName: tx.aiModelName, + aiModelTypeName: tx.aiModelTypeName, + completionTokens: tx.completionTokens, + costUsd: tx.costUsd, + createdAt: tx.createdAt, + creditsUsed: tx.creditsUsed, + generationId: tx.generationId, + organizationId: tx.organizationId, + promptTokens: tx.promptTokens, + totalTokens: tx.totalTokens, + userId: tx.userId, + }), + ) || [], + }) + } catch (error) { + console.error(`Failed to fetch organization credits data: ${error}`) + throw error + } +} diff --git a/src/core/controller/account/fetchUserCreditsData.ts b/src/core/controller/account/getUserCredits.ts similarity index 70% rename from src/core/controller/account/fetchUserCreditsData.ts rename to src/core/controller/account/getUserCredits.ts index e4922d31..8c395973 100644 --- a/src/core/controller/account/fetchUserCreditsData.ts +++ b/src/core/controller/account/getUserCredits.ts @@ -8,7 +8,7 @@ import { UserCreditsData } from "@shared/proto/account" * @param request Empty request * @returns User credits data response */ -export async function fetchUserCreditsData(controller: Controller, request: EmptyRequest): Promise { +export async function getUserCredits(controller: Controller, request: EmptyRequest): Promise { try { if (!controller.accountService) { throw new Error("Account service not available") @@ -21,11 +21,10 @@ export async function fetchUserCreditsData(controller: Controller, request: Empt controller.accountService.fetchPaymentTransactionsRPC(), ]) - // Since generated types match exactly, no conversion needed! return UserCreditsData.create({ - balance: balance ? { currentBalance: balance.currentBalance } : { currentBalance: 0 }, - usageTransactions: usageTransactions || [], - paymentTransactions: paymentTransactions || [], + balance: balance ? { currentBalance: balance.balance / 100 } : { currentBalance: 0 }, + usageTransactions: usageTransactions, + paymentTransactions: paymentTransactions, }) } catch (error) { console.error(`Failed to fetch user credits data: ${error}`) diff --git a/src/core/controller/account/getUserOrganizations.ts b/src/core/controller/account/getUserOrganizations.ts new file mode 100644 index 00000000..c471bd45 --- /dev/null +++ b/src/core/controller/account/getUserOrganizations.ts @@ -0,0 +1,35 @@ +import type { Controller } from "../index" +import type { EmptyRequest } from "@shared/proto/common" +import { UserOrganization, UserOrganizationsResponse } from "@shared/proto/account" + +/** + * Handles fetching all user credits data (balance, usage, payments) + * @param controller The controller instance + * @param request Empty request + * @returns User credits data response + */ +export async function getUserOrganizations(controller: Controller, request: EmptyRequest): Promise { + try { + if (!controller.accountService) { + throw new Error("Account service not available") + } + + // Fetch user organizations from the account service + const organizations = await controller.accountService.fetchUserOrganizationsRPC() + + return UserOrganizationsResponse.create({ + organizations: + organizations?.map((org) => + UserOrganization.create({ + active: org.active, + memberId: org.memberId, + name: org.name, + organizationId: org.organizationId, + roles: org.roles ? [...org.roles] : [], + }), + ) || [], + }) + } catch (error) { + throw error + } +} diff --git a/src/core/controller/account/setUserOrganization.ts b/src/core/controller/account/setUserOrganization.ts new file mode 100644 index 00000000..3036314c --- /dev/null +++ b/src/core/controller/account/setUserOrganization.ts @@ -0,0 +1,24 @@ +import type { Controller } from "../index" +import { Empty } from "@shared/proto/common" +import { UserOrganizationUpdateRequest } from "@shared/proto/account" + +/** + * Handles setting the user's active organization + * @param controller The controller instance + * @param request UserOrganization to set as active + * @returns Empty response + */ +export async function setUserOrganization(controller: Controller, request: UserOrganizationUpdateRequest): Promise { + try { + if (!controller.accountService) { + throw new Error("Account service not available") + } + + // Switch to the specified organization using the account service + await controller.accountService.switchAccount(request.organizationId) + + return Empty.create({}) + } catch (error) { + throw error + } +} diff --git a/src/core/controller/account/subscribeToAuthCallback.ts b/src/core/controller/account/subscribeToAuthCallback.ts deleted file mode 100644 index 3e62bff7..00000000 --- a/src/core/controller/account/subscribeToAuthCallback.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Controller } from "../index" -import { EmptyRequest } from "../../../shared/proto/common" -import { String as ProtoString } from "../../../shared/proto/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" - -// Keep track of active authCallback subscriptions -const activeAuthCallbackSubscriptions = new Set() - -/** - * Subscribe to authCallback events - * @param controller The controller instance - * @param request The empty request - * @param responseStream The streaming response handler - * @param requestId The ID of the request (passed by the gRPC handler) - */ -export async function subscribeToAuthCallback( - controller: Controller, - request: EmptyRequest, - responseStream: StreamingResponseHandler, - requestId?: string, -): Promise { - // Add this subscription to the active subscriptions - activeAuthCallbackSubscriptions.add(responseStream) - - // Register cleanup when the connection is closed - const cleanup = () => { - activeAuthCallbackSubscriptions.delete(responseStream) - } - - // Register the cleanup function with the request registry if we have a requestId - if (requestId) { - getRequestRegistry().registerRequest(requestId, cleanup, { type: "authCallback_subscription" }, responseStream) - } -} - -/** - * Send an authCallback event to all active subscribers - * @param customToken The custom token for authentication - */ -export async function sendAuthCallbackEvent(customToken: string): Promise { - // Send the event to all active subscribers - const promises = Array.from(activeAuthCallbackSubscriptions).map(async (responseStream) => { - try { - const event: ProtoString = { - value: customToken, - } - await responseStream( - event, - false, // Not the last message - ) - } catch (error) { - console.error("Error sending authCallback event:", error) - // Remove the subscription if there was an error - activeAuthCallbackSubscriptions.delete(responseStream) - } - }) - - await Promise.all(promises) -} diff --git a/src/core/controller/account/subscribeToAuthStatusUpdate.ts b/src/core/controller/account/subscribeToAuthStatusUpdate.ts new file mode 100644 index 00000000..02be4385 --- /dev/null +++ b/src/core/controller/account/subscribeToAuthStatusUpdate.ts @@ -0,0 +1,5 @@ +import { AuthService } from "../../../services/auth/AuthService" + +const authService = AuthService.getInstance() +export const subscribeToAuthStatusUpdate = authService.subscribeToAuthStatusUpdate.bind(authService) +export const sendAuthStatusUpdateEvent = authService.sendAuthStatusUpdate.bind(authService) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 1a2340a0..8b860355 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -30,18 +30,17 @@ import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalF import { getAllExtensionState, getGlobalState, - getSecret, getWorkspaceState, storeSecret, updateGlobalState, updateWorkspaceState, } from "../storage/state" import { Task } from "../task" -import { sendAuthCallbackEvent } from "./account/subscribeToAuthCallback" import { handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler" -import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" import { sendStateUpdate } from "./state/subscribeToState" import { sendAddToInputEvent } from "./ui/subscribeToAddToInput" +import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" +import { AuthService } from "@/services/auth/AuthService" /* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts @@ -58,6 +57,7 @@ export class Controller { workspaceTracker: WorkspaceTracker mcpHub: McpHub accountService: ClineAccountService + authService: AuthService latestAnnouncementId = "june-25-2025_16:11:00" // update to some unique identifier when we add a new announcement constructor( @@ -77,10 +77,9 @@ export class Controller { (msg) => this.postMessageToWebview(msg), this.context.extension?.packageJSON?.version ?? "1.0.0", ) - this.accountService = new ClineAccountService(async () => { - const { apiConfiguration } = await this.getStateToPostToWebview() - return apiConfiguration?.clineApiKey - }) + this.accountService = ClineAccountService.getInstance() + this.authService = AuthService.getInstance(context) + this.authService.restoreAuthToken() // Clean up legacy checkpoints cleanupLegacyCheckpoints(this.context.globalStorageUri.fsPath, this.outputChannel).catch((error) => { @@ -114,7 +113,8 @@ export class Controller { // Auth methods async handleSignOut() { try { - await storeSecret(this.context, "clineApiKey", undefined) + // TODO: update to clineAccountId and then move clineApiKey to a clear function. + await storeSecret(this.context, "clineAccountId", undefined) await updateGlobalState(this.context, "userInfo", undefined) await updateGlobalState(this.context, "apiProvider", "openrouter") await this.postStateToWebview() @@ -457,23 +457,18 @@ export class Controller { } // Auth - public async validateAuthState(state: string | null): Promise { - const storedNonce = await getSecret(this.context, "authNonce") + const storedNonce = this.authService.authNonce if (!state || state !== storedNonce) { return false } - await storeSecret(this.context, "authNonce", undefined) // Clear after use + this.authService.resetAuthNonce() // Clear the nonce after validation return true } - async handleAuthCallback(customToken: string, apiKey: string) { + async handleAuthCallback(customToken: string, provider: string | null = null) { try { - // Store API key for API calls - await storeSecret(this.context, "clineApiKey", apiKey) - - // Send custom token to webview for Firebase auth - await sendAuthCallbackEvent(customToken) + await this.authService.handleAuthCallback(customToken, provider ? provider : "google") const clineProvider: ApiProvider = "cline" await updateGlobalState(this.context, "apiProvider", clineProvider) @@ -481,12 +476,10 @@ export class Controller { // Mark welcome view as completed since user has successfully logged in await updateGlobalState(this.context, "welcomeViewCompleted", true) - // Update API configuration with the new provider and API key const { apiConfiguration } = await getAllExtensionState(this.context) const updatedConfig = { ...apiConfiguration, apiProvider: clineProvider, - clineApiKey: apiKey, } if (this.task) { @@ -494,7 +487,6 @@ export class Controller { } await this.postStateToWebview() - // vscode.window.showInformationMessage("Successfully logged in to Cline") } catch (error) { console.error("Failed to handle auth callback:", error) vscode.window.showErrorMessage("Failed to log in to Cline") @@ -504,7 +496,6 @@ export class Controller { } // MCP Marketplace - private async fetchMcpMarketplaceFromApi(silent: boolean = false): Promise { try { const response = await axios.get("https://api.cline.bot/v1/mcp/marketplace", { @@ -1076,6 +1067,4 @@ Commit message:` vscode.window.showErrorMessage(`Failed to generate commit message: ${errorMessage}`) } } - - // dev } diff --git a/src/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index 94493331..0b98c179 100644 --- a/src/core/storage/state-keys.ts +++ b/src/core/storage/state-keys.ts @@ -1,6 +1,6 @@ export type SecretKey = | "apiKey" - | "clineApiKey" + | "clineAccountId" | "openRouterApiKey" | "awsAccessKey" | "awsSecretKey" diff --git a/src/core/storage/state-migrations.ts b/src/core/storage/state-migrations.ts index e434df52..3ca0a296 100644 --- a/src/core/storage/state-migrations.ts +++ b/src/core/storage/state-migrations.ts @@ -202,7 +202,7 @@ export async function migrateWelcomeViewCompleted(context: vscode.ExtensionConte config.doubaoApiKey, config.mistralApiKey, config.vsCodeLmModelSelector, - config.clineApiKey, + config.clineAccountId, config.asksageApiKey, config.xaiApiKey, config.sambanovaApiKey, diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index bd33a6b5..6f4259b6 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -26,7 +26,6 @@ const inMemoryWorkspaceState = new Map() const inMemorySecrets = new Map() // global - export async function updateGlobalState(context: vscode.ExtensionContext, key: GlobalStateKey, value: any) { if (isTemporaryProfile) { inMemoryGlobalState.set(key, value) @@ -70,7 +69,6 @@ export async function updateSecretsBatch(context: vscode.ExtensionContext, updat } // secrets - export async function storeSecret(context: vscode.ExtensionContext, key: SecretKey, value?: string) { if (isTemporaryProfile) { if (value) { @@ -95,7 +93,6 @@ export async function getSecret(context: vscode.ExtensionContext, key: SecretKey } // workspace - export async function updateWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey, value: any) { if (isTemporaryProfile) { inMemoryWorkspaceState.set(key, value) @@ -118,7 +115,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { welcomeViewCompleted, apiKey, openRouterApiKey, - clineApiKey, + clineAccountId, awsAccessKey, awsSecretKey, awsSessionToken, @@ -191,7 +188,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { getGlobalState(context, "welcomeViewCompleted") as Promise, getSecret(context, "apiKey") as Promise, getSecret(context, "openRouterApiKey") as Promise, - getSecret(context, "clineApiKey") as Promise, + getSecret(context, "clineAccountId") as Promise, getSecret(context, "awsAccessKey") as Promise, getSecret(context, "awsSecretKey") as Promise, getSecret(context, "awsSessionToken") as Promise, @@ -373,7 +370,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { apiModelId, apiKey, openRouterApiKey, - clineApiKey, + clineAccountId, claudeCodePath, awsAccessKey, awsSecretKey, @@ -538,7 +535,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a xaiApiKey, thinkingBudgetTokens, reasoningEffort, - clineApiKey, + clineAccountId, sambanovaApiKey, cerebrasApiKey, nebiusApiKey, @@ -616,7 +613,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a const batchedSecretUpdates = { apiKey, openRouterApiKey, - clineApiKey, + clineAccountId, awsAccessKey, awsSecretKey, awsSessionToken, @@ -670,7 +667,7 @@ export async function resetGlobalState(context: vscode.ExtensionContext) { "qwenApiKey", "doubaoApiKey", "mistralApiKey", - "clineApiKey", + "clineAccountId", "liteLlmApiKey", "fireworksApiKey", "asksageApiKey", diff --git a/src/extension.ts b/src/extension.ts index 43cc8a38..a799629c 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -35,6 +35,7 @@ import * as hostProviders from "@hosts/host-providers" import { vscodeHostBridgeClient } from "@/hosts/vscode/client/host-grpc-client" import { VscodeWebviewProvider } from "./core/webview/VscodeWebviewProvider" import { ExtensionContext } from "vscode" +import { AuthService } from "./services/auth/AuthService" import { writeTextToClipboard, readTextFromClipboard } from "@/utils/env" /* @@ -293,24 +294,28 @@ export async function activate(context: vscode.ExtensionContext) { break } case "/auth": { - const token = query.get("token") + const authService = AuthService.getInstance() + console.log("Auth callback received:", uri.toString()) + + const token = query.get("idToken") const state = query.get("state") - const apiKey = query.get("apiKey") + const provider = query.get("provider") console.log("Auth callback received:", { token: token, state: state, - apiKey: apiKey, + provider: provider, }) // Validate state parameter - if (!(await visibleWebview?.controller.validateAuthState(state))) { + if (!(authService.authNonce === state)) { vscode.window.showErrorMessage("Invalid auth state") return } - if (token && apiKey) { - await visibleWebview?.controller.handleAuthCallback(token, apiKey) + if (token) { + await visibleWebview?.controller.handleAuthCallback(token, provider) + // await authService.handleAuthCallback(token) } break } diff --git a/src/services/account/ClineAccountService.ts b/src/services/account/ClineAccountService.ts index c87ebf5a..4007dd05 100644 --- a/src/services/account/ClineAccountService.ts +++ b/src/services/account/ClineAccountService.ts @@ -1,13 +1,43 @@ import axios, { AxiosRequestConfig, AxiosResponse } from "axios" -import type { BalanceResponse, PaymentTransaction, UsageTransaction } from "@shared/ClineAccount" -import { ExtensionMessage } from "@shared/ExtensionMessage" +import type { + BalanceResponse, + OrganizationBalanceResponse, + OrganizationUsageTransaction, + PaymentTransaction, + UsageTransaction, + UserResponse, +} from "@shared/ClineAccount" +import { AuthService } from "../auth/AuthService" export class ClineAccountService { - private readonly baseUrl = "https://api.cline.bot/v1" - private getClineApiKey: () => Promise + private static instance: ClineAccountService + private _authService: AuthService + // TODO: replace this with a global API Host + private readonly _baseUrl = "https://api.cline.bot" + // private readonly _baseUrl = "https://core-api.staging.int.cline.bot" + // private readonly _baseUrl = "http://localhost:7777" - constructor(getClineApiKey: () => Promise) { - this.getClineApiKey = getClineApiKey + constructor() { + this._authService = AuthService.getInstance() + } + + /** + * Returns the singleton instance of ClineAccountService + * @returns Singleton instance of ClineAccountService + */ + public static getInstance(): ClineAccountService { + if (!ClineAccountService.instance) { + ClineAccountService.instance = new ClineAccountService() + } + return ClineAccountService.instance + } + + /** + * Returns the base URL for the Cline API + * @returns The base URL as a string + */ + get baseUrl(): string { + return this._baseUrl } /** @@ -18,29 +48,38 @@ export class ClineAccountService { * @throws Error if the API key is not found or the request fails */ private async authenticatedRequest(endpoint: string, config: AxiosRequestConfig = {}): Promise { - const clineApiKey = await this.getClineApiKey() + const url = `${this._baseUrl}${endpoint}` - if (!clineApiKey) { - throw new Error("Cline API key not found") - } + const clineAccountAuthToken = await this._authService.getAuthToken() - const url = `${this.baseUrl}${endpoint}` const requestConfig: AxiosRequestConfig = { ...config, headers: { - Authorization: `Bearer ${clineApiKey}`, + Authorization: `Bearer ${clineAccountAuthToken}`, "Content-Type": "application/json", ...config.headers, }, } - - const response: AxiosResponse = await axios.get(url, requestConfig) - - if (!response.data) { + const response: AxiosResponse<{ data?: T; error: string; success: boolean }> = await axios.request({ + url, + method: "GET", + ...requestConfig, + }) + const status = response.status + if (status < 200 || status >= 300) { + throw new Error(`Request to ${endpoint} failed with status ${status}`) + } + if (response.statusText !== "No Content" && (!response.data || !response.data.data)) { throw new Error(`Invalid response from ${endpoint} API`) } - - return response.data + if (typeof response.data === "object" && !response.data.success) { + throw new Error(`API error: ${response.data.error}`) + } + if (response.statusText === "No Content") { + return {} as T // Return empty object if no content + } else { + return response.data.data as T + } } /** @@ -49,7 +88,12 @@ export class ClineAccountService { */ async fetchBalanceRPC(): Promise { try { - const data = await this.authenticatedRequest("/user/credits/balance") + const me = await this.fetchMe() + if (!me || !me.id) { + console.error("Failed to fetch user ID for usage transactions") + return undefined + } + const data = await this.authenticatedRequest(`/api/v1/users/${me.id}/balance`) return data } catch (error) { console.error("Failed to fetch balance (RPC):", error) @@ -63,8 +107,13 @@ export class ClineAccountService { */ async fetchUsageTransactionsRPC(): Promise { try { - const data = await this.authenticatedRequest<{ usageTransactions: UsageTransaction[] }>("/user/credits/usage") - return data.usageTransactions + const me = await this.fetchMe() + if (!me || !me.id) { + console.error("Failed to fetch user ID for usage transactions") + return undefined + } + const data = await this.authenticatedRequest<{ items: UsageTransaction[] }>(`/api/v1/users/${me.id}/usages`) + return data.items } catch (error) { console.error("Failed to fetch usage transactions (RPC):", error) return undefined @@ -77,11 +126,120 @@ export class ClineAccountService { */ async fetchPaymentTransactionsRPC(): Promise { try { - const data = await this.authenticatedRequest<{ paymentTransactions: PaymentTransaction[] }>("/user/credits/payments") + const me = await this.fetchMe() + if (!me || !me.id) { + console.error("Failed to fetch user ID for usage transactions") + return undefined + } + const data = await this.authenticatedRequest<{ paymentTransactions: PaymentTransaction[] }>( + `/api/v1/users/${me.id}/payments`, + ) return data.paymentTransactions } catch (error) { console.error("Failed to fetch payment transactions (RPC):", error) return undefined } } + + /** + * Fetches the current user data + * @returns UserResponse or undefined if failed + */ + async fetchMe(): Promise { + try { + const data = await this.authenticatedRequest(`/api/v1/users/me`) + return data + } catch (error) { + console.error("Failed to fetch user data (RPC):", error) + return undefined + } + } + + /** + * Fetches the current user's organizations + * @returns UserResponse["organizations"] or undefined if failed + */ + async fetchUserOrganizationsRPC(): Promise { + try { + const me = await this.fetchMe() + if (!me || !me.organizations) { + console.error("Failed to fetch user organizations") + return undefined + } + return me.organizations + } catch (error) { + console.error("Failed to fetch user organizations (RPC):", error) + return undefined + } + } + + /** + * Fetches the current user's organization credits + * @returns {Promise} A promise that resolves to the active organization balance. + */ + async fetchOrganizationCreditsRPC(organizationId: string): Promise { + try { + const data = await this.authenticatedRequest( + `/api/v1/organizations/${organizationId}/balance`, + ) + return data + } catch (error) { + console.error("Failed to fetch active organization balance (RPC):", error) + return undefined + } + } + + /** + * Fetches the current user's organization transactions + * @returns {Promise} A promise that resolves to the active organization transactions. + */ + async fetchOrganizationUsageTransactionsRPC(organizationId: string): Promise { + try { + const me = await this.fetchMe() + if (!me || !me.id) { + console.error("Failed to fetch user ID for active organization transactions") + return undefined + } + const memberId = me.organizations.find((org) => org.organizationId === organizationId)?.memberId + if (!memberId) { + console.error("Failed to find member ID for active organization transactions") + return undefined + } + const data = await this.authenticatedRequest<{ items: OrganizationUsageTransaction[] }>( + `/api/v1/organizations/${organizationId}/members/${memberId}/usages`, + ) + return data.items + } catch (error) { + console.error("Failed to fetch active organization transactions (RPC):", error) + return undefined + } + } + + /** + * Switches the active account to the specified organization or personal account. + * @param organizationId - Optional organization ID to switch to. If not provided, it will switch to the personal account. + * @returns {Promise} A promise that resolves when the account switch is complete. + * @throws {Error} If the account switch fails, an error will be thrown. + */ + async switchAccount(organizationId?: string): Promise { + // Call API to switch account + try { + // make XHR request to switch account + const response = await this.authenticatedRequest(`/api/v1/users/active-account`, { + method: "PUT", + headers: { + "Content-Type": "application/json", + }, + data: { + organizationId: organizationId || null, // Pass organization if provided + }, + }) + } catch (error) { + console.error("Error switching account:", error) + throw error + } finally { + // Request a new authentication token + await this._authService.refreshAuth() + } + } } diff --git a/src/services/auth/AuthService.ts b/src/services/auth/AuthService.ts new file mode 100644 index 00000000..ba8fc672 --- /dev/null +++ b/src/services/auth/AuthService.ts @@ -0,0 +1,364 @@ +import vscode from "vscode" +import crypto from "crypto" +import { EmptyRequest, String } from "../../shared/proto/common" +import { AuthState } from "../../shared/proto/account" +import { StreamingResponseHandler, getRequestRegistry } from "@/core/controller/grpc-handler" +import { FirebaseAuthProvider } from "./providers/FirebaseAuthProvider" +import { Controller } from "@/core/controller" +import { storeSecret } from "@/core/storage/state" + +const DefaultClineAccountURI = "https://app.cline.bot/auth" +// const DefaultClineAccountURI = "https://staging-app.cline.bot/auth" +// const DefaultClineAccountURI = "http://localhost:3000/auth" +let authProviders: any[] = [] + +type ServiceConfig = { + URI?: string + [key: string]: any +} + +const availableAuthProviders = { + firebase: FirebaseAuthProvider, + // Add other providers here as needed +} + +// TODO: Add logic to handle multiple webviews getting auth updates. + +export class AuthService { + private static instance: AuthService | null = null + private _config: ServiceConfig + private _authenticated: boolean = false + private _user: any = null + private _provider: any = null + private _authNonce: string | null = null + private _activeAuthStatusUpdateSubscriptions = new Set<[Controller, StreamingResponseHandler]>() + private _context: vscode.ExtensionContext + + /** + * Creates an instance of AuthService. + * @param config - Configuration for the service, including the URI for authentication. + * @param authProvider - Optional authentication provider to use. + * @param controller - Optional reference to the Controller instance. + */ + private constructor(context: vscode.ExtensionContext, config: ServiceConfig, authProvider?: any) { + const providerName = authProvider || "firebase" + this._config = Object.assign({ URI: DefaultClineAccountURI }, config) + + // Fetch AuthProviders + // TODO: Deliver this config from the backend securely + // ex. https://app.cline.bot/api/v1/auth/providers + + const authProvidersConfigs = [ + { + name: "firebase", + config: { + apiKey: "AIzaSyC5rx59Xt8UgwdU3PCfzUF7vCwmp9-K2vk", + authDomain: "cline-prod.firebaseapp.com", + projectId: "cline-prod", + storageBucket: "cline-prod.firebasestorage.app", + messagingSenderId: "941048379330", + appId: "1:941048379330:web:45058eedeefc5cdfcc485b", + }, + // Uncomment for staging environment + // config: { + // apiKey: "AIzaSyASSwkwX1kSO8vddjZkE5N19QU9cVQ0CIk", + // authDomain: "cline-staging.firebaseapp.com", + // projectId: "cline-staging", + // storageBucket: "cline-staging.firebasestorage.app", + // messagingSenderId: "853479478430", + // appId: "1:853479478430:web:2de0dba1c63c3262d4578f", + // }, + // Uncomment for local development environment + // config: { + // apiKey: "AIzaSyASSwkwX1kSO8vddjZkE5N19QU9cVQ0CIk", + // authDomain: "cline-staging.firebaseapp.com", + // projectId: "cline-staging", + // storageBucket: "cline-staging.firebasestorage.app", + // messagingSenderId: "853479478430", + // appId: "1:853479478430:web:2de0dba1c63c3262d4578f", + // }, + // config: { + // apiKey: "AIzaSyD8wtkd1I-EICuAg6xgAQpRdwYTvwxZG2w", + // authDomain: "cline-preview.firebaseapp.com", + // projectId: "cline-preview", + // } + }, + ] + + // Merge authProviders with availableAuthProviders + authProviders = authProvidersConfigs.map((provider) => { + const providerName = provider.name + const ProviderClass = availableAuthProviders[providerName as keyof typeof availableAuthProviders] + if (!ProviderClass) { + throw new Error(`Auth provider "${providerName}" is not available`) + } + return { + name: providerName, + config: provider.config, + provider: new ProviderClass(provider.config), + } + }) + + this._setProvider(authProviders.find((authProvider) => authProvider.name === providerName).name) + this._context = context + } + + /** + * Gets the singleton instance of AuthService. + * @param config - Configuration for the service, including the URI for authentication. + * @param authProvider - Optional authentication provider to use. + * @param controller - Optional reference to the Controller instance. + * @returns The singleton instance of AuthService. + */ + public static getInstance(context?: vscode.ExtensionContext, config?: ServiceConfig, authProvider?: any): AuthService { + if (!AuthService.instance) { + if (!context) { + console.warn("Extension context was not provided to AuthService.getInstance, using default context") + context = {} as vscode.ExtensionContext + } + AuthService.instance = new AuthService(context, config || {}, authProvider) + } + if (context) { + AuthService.instance.context = context + } + return AuthService.instance + } + + set context(context: vscode.ExtensionContext) { + this._context = context + } + + get authProvider(): any { + return this._provider + } + + set authProvider(providerName: string) { + this._setProvider(providerName) + } + + get authNonce(): string | null { + return this._authNonce + } + + async getAuthToken(): Promise { + if (!this._user) { + return null + } + + // TODO: This may need to be dependant on the auth provider + // Return the ID token from the user object + return this._provider.provider.getAuthToken(this._user) + } + + private _setProvider(providerName: string): void { + const providerConfig = authProviders.find((provider) => provider.name === providerName) + if (!providerConfig) { + throw new Error(`Auth provider "${providerName}" not found`) + } + + this._provider = providerConfig + } + + getInfo(): AuthState { + let user = null + if (this._user && this._authenticated) { + user = this._provider.provider.convertUserData(this._user) + } + + return AuthState.create({ + user: user, + }) + } + + /** + * Resets the auth nonce to null. + * This is typically called after a successful authentication. + */ + resetAuthNonce(): void { + this._authNonce = null + } + + async createAuthRequest(): Promise { + if (!this._authenticated) { + // Generate nonce for state validation + this._authNonce = crypto.randomBytes(32).toString("hex") + + const uriScheme = vscode.env.uriScheme + const authUrl = vscode.Uri.parse( + `${this._config.URI}?state=${encodeURIComponent(this._authNonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`, + ) + await vscode.env.openExternal(authUrl) + return String.create({ + value: authUrl.toString(), + }) + } else { + this.sendAuthStatusUpdate() + return String.create({ + value: "Already authenticated", + }) + } + } + + async handleDeauth(): Promise { + if (!this._provider) { + throw new Error("Auth provider is not set") + } + + try { + await this._provider.provider.signOut() + this._user = null + this._authenticated = false + this.sendAuthStatusUpdate() + } catch (error) { + console.error("Error signing out:", error) + throw error + } + } + + async handleAuthCallback(token: string, provider: string): Promise { + if (!this._provider) { + throw new Error("Auth provider is not set") + } + + try { + this._user = await this._provider.provider.signIn(this._context, token, provider) + this._authenticated = true + + await this.sendAuthStatusUpdate() + this.setupAutoRefreshAuth() + return this._user + } catch (error) { + console.error("Error signing in with custom token:", error) + throw error + } + } + + /** + * Clear the authentication token from the extension's storage. + * This is typically called when the user logs out. + */ + async clearAuthToken(): Promise { + await storeSecret(this._context, "clineAccountId", undefined) + } + + /** + * Restores the authentication token from the extension's storage. + * This is typically called when the extension is activated. + */ + async restoreAuthToken(): Promise { + if (!this._provider || !this._provider.provider) { + throw new Error("Auth provider is not set") + } + + try { + this._user = await this._provider.provider.restoreAuthCredential(this._context) + if (this._user) { + this._authenticated = true + await this.sendAuthStatusUpdate() + this.setupAutoRefreshAuth() + // Setup auto-refresh for the auth token + } else { + console.warn("No user found after restoring auth token") + this._authenticated = false + this._user = null + } + } catch (error) { + console.error("Error restoring auth token:", error) + this._authenticated = false + this._user = null + return + } + } + + /** + * Refreshes the authentication status and sends an update to all subscribers. + */ + async refreshAuth(): Promise { + if (!this._user) { + console.warn("No user is authenticated, skipping auth refresh") + return + } + + await this._provider.provider.refreshAuthToken() + this.sendAuthStatusUpdate() + } + + private setupAutoRefreshAuth(): void { + // Set timeoutDuration to refresh the auth token 5 minutes before it expires + const timeoutDuration = Math.floor(this._user.stsTokenManager.expirationTime - 5 * 60000 - Date.now()) // Milliseconds until 5 minutes before expiration + setTimeout(() => this._autoRefreshAuth(), timeoutDuration) + } + + private async _autoRefreshAuth(): Promise { + if (!this._user) { + console.warn("No user is authenticated, skipping auth refresh") + return + } + await this.refreshAuth() + this.setupAutoRefreshAuth() // Reschedule the next auto-refresh + } + + /** + * Subscribe to authStatusUpdate events + * @param controller The controller instance + * @param request The empty request + * @param responseStream The streaming response handler + * @param requestId The ID of the request (passed by the gRPC handler) + */ + async subscribeToAuthStatusUpdate( + controller: Controller, + request: EmptyRequest, + responseStream: StreamingResponseHandler, + requestId?: string, + ): Promise { + console.log("Subscribing to authStatusUpdate") + + // Add this subscription to the active subscriptions + this._activeAuthStatusUpdateSubscriptions.add([controller, responseStream]) + // Register cleanup when the connection is closed + const cleanup = () => { + this._activeAuthStatusUpdateSubscriptions.delete([controller, responseStream]) + } + // Register the cleanup function with the request registry if we have a requestId + if (requestId) { + getRequestRegistry().registerRequest(requestId, cleanup, { type: "authStatusUpdate_subscription" }, responseStream) + } + + // Send the current authentication status immediately + try { + await this.sendAuthStatusUpdate() + } catch (error) { + console.error("Error sending initial auth status:", error) + // Remove the subscription if there was an error + this._activeAuthStatusUpdateSubscriptions.delete([controller, responseStream]) + } + } + + /** + * Send an authStatusUpdate event to all active subscribers + */ + async sendAuthStatusUpdate(): Promise { + // Send the event to all active subscribers + const promises = Array.from(this._activeAuthStatusUpdateSubscriptions).map(async ([controller, responseStream]) => { + try { + const authInfo: AuthState = this.getInfo() + + await responseStream( + authInfo, + false, // Not the last message + ) + + // Update the state in the webview + if (controller) { + await controller.postStateToWebview() + } + } catch (error) { + console.error("Error sending authStatusUpdate event:", error) + // Remove the subscription if there was an error + this._activeAuthStatusUpdateSubscriptions.delete([controller, responseStream]) + } + }) + + await Promise.all(promises) + } +} diff --git a/src/services/auth/config.ts b/src/services/auth/config.ts deleted file mode 100644 index 86034075..00000000 --- a/src/services/auth/config.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Public Firebase config (safe for open source) -export const firebaseConfig = { - apiKey: "AIzaSyDcXAaanNgR2_T0dq2oOl5XyKPksYHppVo", - authDomain: "cline-bot.firebaseapp.com", - projectId: "cline-bot", - storageBucket: "cline-bot.firebasestorage.app", - messagingSenderId: "364369702101", - appId: "1:364369702101:web:0013885dcf20b43799c65c", - measurementId: "G-MDPRELSCD1", -} diff --git a/src/services/auth/providers/FirebaseAuthProvider.ts b/src/services/auth/providers/FirebaseAuthProvider.ts new file mode 100644 index 00000000..839764c0 --- /dev/null +++ b/src/services/auth/providers/FirebaseAuthProvider.ts @@ -0,0 +1,172 @@ +import { getSecret, storeSecret } from "@/core/storage/state" +import { ErrorService } from "@/services/error/ErrorService" +import { initializeApp } from "firebase/app" +import { + AuthCredential, + GoogleAuthProvider, + GithubAuthProvider, + OAuthCredential, + User, + UserCredential, + getAuth, + signInWithCredential, + signOut, +} from "firebase/auth" +import { ExtensionContext } from "vscode" + +export class FirebaseAuthProvider { + private _config: any + + constructor(config: any) { + this._config = config || {} + } + + get config(): any { + return this._config + } + + set config(value: any) { + this._config = value + } + + /** + * Gets the authentication token of the current user. + * @returns {Promise} A promise that resolves to the authentication token of the current user, or null if no user is signed in. + */ + async getAuthToken(): Promise { + const user = getAuth().currentUser + const idToken = user ? await user.getIdToken() : null + return idToken + } + + /** + * Gets the refresh token of the current user. + * @returns {Promise} A promise that resolves to the refresh token of the current user, or null if no user is signed in. + */ + async getRefreshToken(): Promise { + const user = getAuth().currentUser + const refreshToken = user ? user.refreshToken : null + return refreshToken + } + + /** + * Refreshes the authentication token of the current user. + * @returns {Promise} A promise that resolves to the refreshed authentication token of the current user, or null if no user is signed in. + */ + async refreshAuthToken(): Promise { + const user = getAuth().currentUser + const idToken = user ? await user.getIdToken(true) : null + return idToken + } + + /** + * Converts Firebase User object to a generic user object. + * @param user - The Firebase User object. + * @returns {User} A generic user object. + */ + convertUserData(user: User) { + return { + uid: user.uid, + email: user.email, + displayName: user.displayName, + photoUrl: user.photoURL, + } + } + + /** + * Signs out the current user from Firebase. + * @returns {Promise} A promise that resolves when the user is signed out. + */ + async signOut(): Promise { + signOut(getAuth(initializeApp(Object.assign({}, this._config)))) + .then(() => { + console.log("User signed out successfully.") + }) + .catch((error) => { + ErrorService.logMessage("Firebase sign-out error", "error") + ErrorService.logException(error) + throw error + }) + } + + /** + * Stores the authentication token using a provided token. + * @param token - The authentication token to store. + * @returns {Promise} A promise that resolves with the authenticated user. + * @throws {Error} Throws an error if the storage fails. + */ + private async _storeAuthCredential(context: ExtensionContext, credential: AuthCredential): Promise { + try { + await storeSecret(context, "clineAccountId", JSON.stringify(credential.toJSON())) + } catch (error) { + ErrorService.logMessage("Firebase store token error", "error") + ErrorService.logException(error) + throw error + } + } + + /** + * Restores the authentication token using a provided token. + * @param token - The authentication token to restore. + * @returns {Promise} A promise that resolves with the authenticated user. + * @throws {Error} Throws an error if the restoration fails. + */ + async restoreAuthCredential(context: ExtensionContext): Promise { + const credentialJSON = await getSecret(context, "clineAccountId") + if (!credentialJSON) { + console.error("No stored authentication credential found.") + return null + } + try { + const credentialData: AuthCredential = OAuthCredential.fromJSON(credentialJSON) as AuthCredential + const userCredential = await this._signInWithCredential(credentialData) + return userCredential.user + } catch (error) { + ErrorService.logMessage("Firebase restore token error", "error") + ErrorService.logException(error) + throw error + } + } + + async _signInWithCredential(credential: AuthCredential): Promise { + const firebaseConfig = Object.assign({}, this._config) + const app = initializeApp(firebaseConfig) + const auth = getAuth(app) + try { + return await signInWithCredential(auth, credential) + } catch (error) { + ErrorService.logMessage("Firebase sign-in with credential error", "error") + ErrorService.logException(error) + throw error + } + } + + /** + * Signs in the user using Firebase authentication with a custom token. + * @returns {Promise} A promise that resolves with the authenticated user. + * @throws {Error} Throws an error if the sign-in fails. + */ + async signIn(context: ExtensionContext, token: string, provider: string): Promise { + try { + let credential + let userCredential + switch (provider) { + case "google": + credential = GoogleAuthProvider.credential(token) + break + case "github": + credential = GithubAuthProvider.credential(token) + break + default: + throw new Error(`Unsupported provider: ${provider}`) + } + this._storeAuthCredential(context, credential) + userCredential = await this._signInWithCredential(credential) + return userCredential.user + } catch (error) { + ErrorService.logMessage("Firebase sign-in error", "error") + ErrorService.logException(error) + throw error + } + } +} diff --git a/src/services/test/TestServer.ts b/src/services/test/TestServer.ts index c64e450c..9cbdeae7 100644 --- a/src/services/test/TestServer.ts +++ b/src/services/test/TestServer.ts @@ -252,6 +252,7 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server // Clear any existing task await visibleWebview.controller.clearTask() + // TODO: convert apiKey to clineAccountId // If API key is provided, update the API configuration if (apiKey) { Logger.log("API key provided, updating API configuration") @@ -263,11 +264,11 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server const updatedConfig = { ...apiConfiguration, apiProvider: "cline" as ApiProvider, - clineApiKey: apiKey, + clineAccountId: apiKey, } // Store the API key securely - await storeSecret(visibleWebview.controller.context, "clineApiKey", apiKey) + await storeSecret(visibleWebview.controller.context, "clineAccountId", apiKey) // Update the API configuration await updateApiConfiguration(visibleWebview.controller.context, updatedConfig) diff --git a/src/shared/ClineAccount.ts b/src/shared/ClineAccount.ts index 1cc9a288..5d1cd5d5 100644 --- a/src/shared/ClineAccount.ts +++ b/src/shared/ClineAccount.ts @@ -1,16 +1,45 @@ +export interface UserResponse { + id: string + email: string + displayName: string + photoUrl: string + createdAt: string + updatedAt: string + organizations: [ + { + active: boolean + memberId: string + name: string + organizationId: string + roles: ["admin" | "member" | "owner"] + }, + ] +} + export interface BalanceResponse { - currentBalance: number + balance: number + userId: string } export interface UsageTransaction { - spentAt: string - creatorId: string - credits: number - modelProvider: string - model: string - promptTokens: number + aiInferenceProviderName: string + aiModelName: string + aiModelTypeName: string completionTokens: number + costUsd: number + createdAt: string + creditsUsed: number + generationId: string + id: string + metadata: { + additionalProp1: string + additionalProp2: string + additionalProp3: string + } + organizationId: string + promptTokens: number totalTokens: number + userId: string } export interface PaymentTransaction { @@ -19,3 +48,31 @@ export interface PaymentTransaction { amountCents: number credits: number } + +export interface OrganizationBalanceResponse { + balance: number + organizationId: string +} + +export interface OrganizationUsageTransaction { + aiInferenceProviderName: string + aiModelName: string + aiModelTypeName: string + completionTokens: number + costUsd: number + createdAt: string + creditsUsed: number + generationId: string + id: string + memberDisplayName: string + memberEmail: string + metadata: { + additionalProp1: string + additionalProp2: string + additionalProp3: string + } + organizationId: string + promptTokens: number + totalTokens: number + userId: string +} diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index fa02e938..f902dae4 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -1,14 +1,10 @@ // type that represents json data that is sent from extension to webview, called ExtensionMessage and has 'type' enum which can be 'plusButtonClicked' or 'settingsButtonClicked' or 'hello' - -import { GitCommit } from "../utils/git" -import { ApiConfiguration, ModelInfo } from "./api" +import { ApiConfiguration } from "./api" import { AutoApprovalSettings } from "./AutoApprovalSettings" import { BrowserSettings } from "./BrowserSettings" import { ChatSettings } from "./ChatSettings" import { HistoryItem } from "./HistoryItem" -import { McpServer, McpMarketplaceCatalog, McpDownloadResponse, McpViewTab } from "./mcp" import { TelemetrySetting } from "./TelemetrySetting" -import type { BalanceResponse, UsageTransaction, PaymentTransaction } from "../shared/ClineAccount" import { ClineRulesToggles } from "./cline-rules" import { UserInfo } from "./UserInfo" diff --git a/src/shared/UserInfo.ts b/src/shared/UserInfo.ts index 309ea935..630b30e6 100644 --- a/src/shared/UserInfo.ts +++ b/src/shared/UserInfo.ts @@ -1,5 +1,5 @@ export interface UserInfo { displayName?: string email?: string - photoURL?: string + photoUrl?: string } diff --git a/src/shared/api.ts b/src/shared/api.ts index 60896add..1db8580b 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -31,7 +31,7 @@ export type ApiProvider = export interface ApiHandlerOptions { apiModelId?: string apiKey?: string // anthropic - clineApiKey?: string + clineAccountId?: string taskId?: string // Used to identify the task in API requests liteLlmBaseUrl?: string liteLlmModelId?: string diff --git a/src/shared/proto-conversions/models/api-configuration-conversion.ts b/src/shared/proto-conversions/models/api-configuration-conversion.ts index 595a983e..365c1252 100644 --- a/src/shared/proto-conversions/models/api-configuration-conversion.ts +++ b/src/shared/proto-conversions/models/api-configuration-conversion.ts @@ -308,7 +308,7 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA return { apiModelId: config.apiModelId, apiKey: config.apiKey, - clineApiKey: config.clineApiKey, + clineAccountId: config.clineAccountId, taskId: config.taskId, liteLlmBaseUrl: config.liteLlmBaseUrl, liteLlmModelId: config.liteLlmModelId, @@ -387,7 +387,7 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio return { apiModelId: protoConfig.apiModelId, apiKey: protoConfig.apiKey, - clineApiKey: protoConfig.clineApiKey, + clineAccountId: protoConfig.clineAccountId, taskId: protoConfig.taskId, liteLlmBaseUrl: protoConfig.liteLlmBaseUrl, liteLlmModelId: protoConfig.liteLlmModelId, diff --git a/src/shared/proto-conversions/state/settings-conversion.ts b/src/shared/proto-conversions/state/settings-conversion.ts index b2bfa191..054b550d 100644 --- a/src/shared/proto-conversions/state/settings-conversion.ts +++ b/src/shared/proto-conversions/state/settings-conversion.ts @@ -17,7 +17,7 @@ export function convertApiConfigurationToProtoApiConfiguration(config: ApiConfig apiKey: config.apiKey, // Provider-specific API keys - clineApiKey: config.clineApiKey, + clineAccountId: config.clineAccountId, openrouterApiKey: config.openRouterApiKey, anthropicBaseUrl: config.anthropicBaseUrl, openaiApiKey: config.openAiApiKey, @@ -137,7 +137,7 @@ export function convertProtoApiConfigurationToApiConfiguration(protoConfig: Prot apiKey: protoConfig.apiKey, // Provider-specific API keys - clineApiKey: protoConfig.clineApiKey, + clineAccountId: protoConfig.clineAccountId, openRouterApiKey: protoConfig.openrouterApiKey, anthropicBaseUrl: protoConfig.anthropicBaseUrl, openAiApiKey: protoConfig.openaiApiKey, diff --git a/src/test/suite/extension.test.js b/src/test/suite/extension.test.js deleted file mode 100644 index c76ca225..00000000 --- a/src/test/suite/extension.test.js +++ /dev/null @@ -1,56 +0,0 @@ -const { expect } = require("chai") -const vscode = require("vscode") - -describe("Extension Tests", function () { - this.timeout(60000) // Increased timeout for extension operations - - let originalGetConfiguration - - beforeEach(() => { - // Save original configuration - originalGetConfiguration = vscode.workspace.getConfiguration - // Setup mock configuration - const mockUpdate = async () => Promise.resolve() - const mockConfig = { - get: () => true, - update: mockUpdate, - } - vscode.workspace.getConfiguration = () => mockConfig - }) - - afterEach(() => { - // Restore original configuration - vscode.workspace.getConfiguration = originalGetConfiguration - }) - - it("should activate extension successfully", async () => { - // Get the extension - const extension = vscode.extensions.getExtension("saoudrizwan.claude-dev") - expect(extension).to.not.be.undefined - - // Activate the extension if not already activated - if (!extension.isActive) { - await extension.activate() - } - expect(extension.isActive).to.be.true - }) - - it("should open sidebar view", async () => { - // Execute the command to open sidebar - await vscode.commands.executeCommand("cline.plusButtonClicked") - - // Wait for sidebar to be visible - await new Promise((resolve) => setTimeout(resolve, 1000)) - - // Get all views - const views = vscode.window.visibleTextEditors - // Just verify the command executed without error - // The actual view verification is handled in the TypeScript tests - }) - - it("should handle basic commands", async () => { - // Test basic command execution - await vscode.commands.executeCommand("cline.historyButtonClicked") - // Success if no error thrown - }) -}) diff --git a/src/test/suite/index.js b/src/test/suite/index.js deleted file mode 100644 index 36dccbf9..00000000 --- a/src/test/suite/index.js +++ /dev/null @@ -1,43 +0,0 @@ -const path = require("path") -const Mocha = require("mocha") -const glob = require("glob") - -async function run() { - // Create the mocha test - const mocha = new Mocha({ - ui: "bdd", - color: true, - timeout: 60000, // Increased timeout for extension operations - }) - - const testsRoot = path.resolve(__dirname, ".") - - try { - // Find all test files - const files = await glob("*.test.js", { cwd: testsRoot }) - - // Add files to the test suite - files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f))) - - // Run the mocha test - return new Promise((resolve, reject) => { - try { - // Run the tests - mocha.run((failures) => { - if (failures > 0) { - reject(new Error(`${failures} tests failed.`)) - } else { - resolve() - } - }) - } catch (err) { - reject(err) - } - }) - } catch (err) { - console.error("Failed to run tests:", err) - throw err - } -} - -module.exports = { run } diff --git a/webview-ui/src/App.tsx b/webview-ui/src/App.tsx index 0ff8502a..213959ed 100644 --- a/webview-ui/src/App.tsx +++ b/webview-ui/src/App.tsx @@ -9,7 +9,6 @@ import { UiServiceClient } from "./services/grpc-client" import McpView from "./components/mcp/configuration/McpConfigurationView" import { Providers } from "./Providers" import { Boolean, EmptyRequest } from "@shared/proto/common" -import { WebviewProviderType } from "@shared/webview/types" const AppContent = () => { const { diff --git a/webview-ui/src/Providers.tsx b/webview-ui/src/Providers.tsx index 1fe38d68..a1ad8934 100644 --- a/webview-ui/src/Providers.tsx +++ b/webview-ui/src/Providers.tsx @@ -1,7 +1,7 @@ import { type ReactNode } from "react" import { ExtensionStateContextProvider } from "./context/ExtensionStateContext" -import { FirebaseAuthProvider } from "./context/FirebaseAuthContext" +import { ClineAuthProvider } from "./context/ClineAuthContext" import { HeroUIProvider } from "@heroui/react" import { CustomPostHogProvider } from "./CustomPostHogProvider" @@ -9,9 +9,9 @@ export function Providers({ children }: { children: ReactNode }) { return ( - + {children} - + ) diff --git a/webview-ui/src/components/account/AccountView.tsx b/webview-ui/src/components/account/AccountView.tsx index 836aac8a..414e6acb 100644 --- a/webview-ui/src/components/account/AccountView.tsx +++ b/webview-ui/src/components/account/AccountView.tsx @@ -1,7 +1,7 @@ -import { VSCodeButton, VSCodeDivider, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { VSCodeButton, VSCodeDivider, VSCodeLink, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" import { memo, useEffect, useState } from "react" -import { useFirebaseAuth } from "@/context/FirebaseAuthContext" -import { vscode } from "@/utils/vscode" +import { BadgeCent } from "lucide-react" +import { useClineAuth } from "@/context/ClineAuthContext" import VSCodeButtonLink from "../common/VSCodeButtonLink" import ClineLogoWhite from "../../assets/ClineLogoWhite" import CountUp from "react-countup" @@ -10,6 +10,13 @@ import { UsageTransaction, PaymentTransaction } from "@shared/ClineAccount" import { useExtensionState } from "@/context/ExtensionStateContext" import { AccountServiceClient } from "@/services/grpc-client" import { EmptyRequest } from "@shared/proto/common" +import { GetOrganizationCreditsRequest, UserOrganization, UserOrganizationUpdateRequest } from "@shared/proto/account" + +type VSCodeDropdownChangeEvent = Event & { + target: { + value: string + } +} type AccountViewProps = { onDone: () => void @@ -32,54 +39,134 @@ const AccountView = ({ onDone }: AccountViewProps) => { } export const ClineAccountView = () => { - const { user: firebaseUser, handleSignOut } = useFirebaseAuth() + const { clineUser, handleSignIn, handleSignOut } = useClineAuth() const { userInfo, apiConfiguration } = useExtensionState() - let user = apiConfiguration?.clineApiKey ? firebaseUser || userInfo : undefined + let user = apiConfiguration?.clineAccountId ? clineUser || userInfo : undefined const [balance, setBalance] = useState(0) + const [userOrganizations, setUserOrganizations] = useState([]) + const [activeOrganization, setActiveOrganization] = useState(null) + const [midOrgOptimisticUpdate, setMidOrgOptimisticUpdate] = useState(false) const [isLoading, setIsLoading] = useState(true) const [usageData, setUsageData] = useState([]) const [paymentsData, setPaymentsData] = useState([]) + async function getUserCredits() { + setIsLoading(true) + try { + const response = await AccountServiceClient.getUserCredits(EmptyRequest.create()) + setBalance(response.balance?.currentBalance || 0) + setUsageData(response.usageTransactions) + setPaymentsData(response.paymentTransactions) + } catch (error) { + console.error("Failed to fetch user credits data:", error) + setBalance(0) + setUsageData([]) + setPaymentsData([]) + } finally { + setIsLoading(false) + } + } + + async function getOrganizationCredits() { + setIsLoading(true) + if (!activeOrganization) { + await getUserCredits() + return + } + try { + const response = await AccountServiceClient.getOrganizationCredits( + GetOrganizationCreditsRequest.create({ + organizationId: activeOrganization.organizationId, + }), + ) + setBalance(response.balance?.currentBalance || 0) + setUsageData(response.usageTransactions) + setPaymentsData(response.paymentTransactions) + } catch (error) { + console.error("Failed to fetch organization credits data:", error) + setBalance(0) + setUsageData([]) + setPaymentsData([]) + } finally { + setIsLoading(false) + } + } + + async function getUserOrganizations() { + setIsLoading(true) + try { + const response = await AccountServiceClient.getUserOrganizations(EmptyRequest.create()) + setUserOrganizations(response.organizations || []) + setActiveOrganization(response.organizations.find((org: UserOrganization) => org.active) || null) + } catch (error) { + console.error("Failed to fetch user organizations:", error) + setUserOrganizations([]) + setActiveOrganization(null) + } finally { + setIsLoading(false) + } + } + // Fetch all account data when component mounts using gRPC useEffect(() => { if (user) { - setIsLoading(true) - AccountServiceClient.fetchUserCreditsData(EmptyRequest.create()) - .then((response) => { - setBalance(response.balance?.currentBalance || 0) - setUsageData(response.usageTransactions) - setPaymentsData(response.paymentTransactions) - setIsLoading(false) - }) - .catch((error) => { - console.error("Failed to fetch user credits data:", error) - setIsLoading(false) - }) + ;(async () => { + await Promise.all([getUserCredits(), getUserOrganizations()]) + })() } }, [user]) + useEffect(() => { + if (midOrgOptimisticUpdate) { + return + } + + if (activeOrganization) { + ;(async () => { + await getOrganizationCredits() + })() + } + }, [activeOrganization, midOrgOptimisticUpdate]) + const handleLogin = () => { - AccountServiceClient.accountLoginClicked(EmptyRequest.create()).catch((err) => - console.error("Failed to get login URL:", err), - ) + handleSignIn() } const handleLogout = () => { - // Use gRPC client to notify extension to clear API keys and state - AccountServiceClient.accountLogoutClicked(EmptyRequest.create()).catch((err) => console.error("Failed to logout:", err)) - // Then sign out of Firebase handleSignOut() } + + const handleOrganizationChange = async (event: any) => { + const newOrgId = (event.target as VSCodeDropdownChangeEvent["target"]).value + + if (!activeOrganization || activeOrganization.organizationId !== newOrgId) { + const newSelectedOrg = + newOrgId === "" ? null : userOrganizations.find((org) => org.organizationId === newOrgId) || null + const previousOrganization = activeOrganization + setMidOrgOptimisticUpdate(true) + setActiveOrganization(newSelectedOrg) + try { + await AccountServiceClient.setUserOrganization(UserOrganizationUpdateRequest.create({ organizationId: newOrgId })) + setMidOrgOptimisticUpdate(false) + getUserOrganizations() + } catch (error) { + console.error("Failed to update organization:", error) + setMidOrgOptimisticUpdate(false) + setActiveOrganization(previousOrganization) + } + } + } + return (
{user ? (
- {user.photoURL ? ( - Profile + {user.photoUrl ? ( + Profile ) : (
{user.displayName?.[0] || user.email?.[0] || "?"} @@ -88,7 +175,7 @@ export const ClineAccountView = () => {
{user.displayName && ( -

+

{user.displayName}

)} @@ -96,12 +183,28 @@ export const ClineAccountView = () => { {user.email && (
{user.email}
)} + + {userOrganizations && ( + + Personal + {userOrganizations.map((org: UserOrganization) => ( + + {org.name} + + ))} + + )}
+ {/* TODO: Update to get url for dashboard from EXT */} Dashboard @@ -121,25 +224,12 @@ export const ClineAccountView = () => {
Loading...
) : ( <> - $ - - { - setIsLoading(true) - AccountServiceClient.fetchUserCreditsData(EmptyRequest.create()) - .then((response) => { - setBalance(response.balance?.currentBalance || 0) - setUsageData(response.usageTransactions) - setPaymentsData(response.paymentTransactions) - setIsLoading(false) - }) - .catch((error) => { - console.error("Failed to refresh user credits data:", error) - setIsLoading(false) - }) - }}> + + {/* TODO: Do this in a more correct way. We have to divide by 10000 + * because the balance is stored in microcredits in the backend. + */} + + @@ -147,6 +237,7 @@ export const ClineAccountView = () => {
+ {/* TODO: Update to get url for dashboard from EXT */} Add Credits @@ -156,7 +247,12 @@ export const ClineAccountView = () => {
- +
) : ( diff --git a/webview-ui/src/components/account/CreditsHistoryTable.tsx b/webview-ui/src/components/account/CreditsHistoryTable.tsx index ea27bb6e..17b43c19 100644 --- a/webview-ui/src/components/account/CreditsHistoryTable.tsx +++ b/webview-ui/src/components/account/CreditsHistoryTable.tsx @@ -8,9 +8,10 @@ interface CreditsHistoryTableProps { isLoading: boolean usageData: UsageTransaction[] paymentsData: PaymentTransaction[] + showPayments?: boolean } -const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHistoryTableProps) => { +const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, showPayments }: CreditsHistoryTableProps) => { const [activeTab, setActiveTab] = useState<"usage" | "payments">("usage") return ( @@ -20,9 +21,11 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHist setActiveTab("usage")}> USAGE HISTORY - setActiveTab("payments")}> - PAYMENTS HISTORY - + {showPayments && ( + setActiveTab("payments")}> + PAYMENTS HISTORY + + )}
{/* Content container */} @@ -55,11 +58,11 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHist {usageData.map((row, index) => ( - {formatTimestamp(row.spentAt)} + {formatTimestamp(row.createdAt)} - {`${row.modelProvider}/${row.model}`} + {`${row.aiModelName}`} {/* {`${row.promptTokens} → ${row.completionTokens}`} */} - {`$${Number(row.credits).toFixed(7)}`} + {`$${Number(row.creditsUsed / 1000000).toFixed(4)}`} ))} @@ -71,7 +74,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHist )} - {activeTab === "payments" && ( + {showPayments && activeTab === "payments" && ( <> {paymentsData.length > 0 ? ( diff --git a/webview-ui/src/components/settings/ClineAccountInfoCard.tsx b/webview-ui/src/components/settings/ClineAccountInfoCard.tsx index 1fbe5acc..e9b8e408 100644 --- a/webview-ui/src/components/settings/ClineAccountInfoCard.tsx +++ b/webview-ui/src/components/settings/ClineAccountInfoCard.tsx @@ -1,14 +1,14 @@ import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" -import { useFirebaseAuth } from "@/context/FirebaseAuthContext" +import { useClineAuth } from "@/context/ClineAuthContext" import { useExtensionState } from "@/context/ExtensionStateContext" import { AccountServiceClient } from "@/services/grpc-client" import { EmptyRequest } from "@shared/proto/common" export const ClineAccountInfoCard = () => { - const { user: firebaseUser, handleSignOut } = useFirebaseAuth() - const { userInfo, apiConfiguration, navigateToAccount } = useExtensionState() + const { clineUser } = useClineAuth() + const { apiConfiguration, navigateToAccount } = useExtensionState() - let user = apiConfiguration?.clineApiKey ? firebaseUser || userInfo : undefined + let user = apiConfiguration?.clineAccountId ? clineUser : undefined const handleLogin = () => { AccountServiceClient.accountLoginClicked(EmptyRequest.create()).catch((err) => diff --git a/webview-ui/src/context/ClineAuthContext.tsx b/webview-ui/src/context/ClineAuthContext.tsx new file mode 100644 index 00000000..dfe3068e --- /dev/null +++ b/webview-ui/src/context/ClineAuthContext.tsx @@ -0,0 +1,84 @@ +import { AccountServiceClient } from "@/services/grpc-client" +import { EmptyRequest } from "@shared/proto/common" +import React, { createContext, useCallback, useContext, useEffect, useState } from "react" + +// Define User type (you may need to adjust this based on your actual User type) +export interface ClineUser { + uid: string + email?: string + displayName?: string + photoUrl?: string +} + +export interface ClineAuthContextType { + clineUser: ClineUser | null + handleSignIn: () => Promise + handleSignOut: () => Promise +} + +const ClineAuthContext = createContext(undefined) + +export const ClineAuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { + const [user, setUser] = useState(null) + + useEffect(() => { + console.log("Extension: ClineAuthContext: user updated:", user) + }, [user]) + + // Handle auth status update events + useEffect(() => { + const cancelSubscription = AccountServiceClient.subscribeToAuthStatusUpdate(EmptyRequest.create(), { + onResponse: async (response: any) => { + console.log("Extension: ClineAuthContext: Received auth status update:", response) + if (response && response.user) { + setUser(response.user) + } + }, + onError: (error: Error) => { + console.error("Error in auth callback subscription:", error) + }, + onComplete: () => { + console.log("Auth callback subscription completed") + }, + }) + + // Cleanup function to cancel subscription when component unmounts + return () => { + cancelSubscription() + } + }, []) + + const handleSignIn = useCallback(async () => { + try { + AccountServiceClient.accountLoginClicked(EmptyRequest.create()).catch((err) => + console.error("Failed to get login URL:", err), + ) + } catch (error) { + console.error("Error signing in:", error) + throw error + } + }, []) + + const handleSignOut = useCallback(async () => { + try { + await AccountServiceClient.accountLogoutClicked(EmptyRequest.create()).catch((err) => + console.error("Failed to logout:", err), + ) + } catch (error) { + console.error("Error signing out:", error) + throw error + } + }, []) + + return ( + {children} + ) +} + +export const useClineAuth = () => { + const context = useContext(ClineAuthContext) + if (context === undefined) { + throw new Error("useClineAuth must be used within a ClineAuthProvider") + } + return context +} diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index 92891265..cb5c43d4 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -1,5 +1,5 @@ import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from "react" -import { useEvent } from "react-use" +import "../../../src/shared/webview/types" import { StateServiceClient, ModelsServiceClient, @@ -254,9 +254,8 @@ export const ExtensionStateContextProvider: React.FC<{ // Subscribe to state updates and UI events using the gRPC streaming API useEffect(() => { - // Determine the webview provider type - const webviewType = - window.WEBVIEW_PROVIDER_TYPE === "sidebar" ? WebviewProviderTypeEnum.SIDEBAR : WebviewProviderTypeEnum.TAB + // Use the already defined webview provider type + const webviewType = currentProviderType // Set up state subscription stateSubscriptionRef.current = StateServiceClient.subscribeToState(EmptyRequest.create({}), { diff --git a/webview-ui/src/context/FirebaseAuthContext.tsx b/webview-ui/src/context/FirebaseAuthContext.tsx deleted file mode 100644 index 3d341ea2..00000000 --- a/webview-ui/src/context/FirebaseAuthContext.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import { AccountServiceClient } from "@/services/grpc-client" -import { vscode } from "@/utils/vscode" -import { EmptyRequest } from "@shared/proto/common" -import { initializeApp } from "firebase/app" -import { User, getAuth, signInWithCustomToken, signOut } from "firebase/auth" -import React, { createContext, useCallback, useContext, useEffect, useState } from "react" -import { useExtensionState } from "./ExtensionStateContext" -import { AuthStateChanged, AuthStateChangedRequest } from "@shared/proto/account" - -// Firebase configuration from extension -const firebaseConfig = { - apiKey: "AIzaSyDcXAaanNgR2_T0dq2oOl5XyKPksYHppVo", - authDomain: "cline-bot.firebaseapp.com", - projectId: "cline-bot", - storageBucket: "cline-bot.firebasestorage.app", - messagingSenderId: "364369702101", - appId: "1:364369702101:web:0013885dcf20b43799c65c", - measurementId: "G-MDPRELSCD1", -} - -interface FirebaseAuthContextType { - user: User | null - isInitialized: boolean - signInWithToken: (token: string) => Promise - handleSignOut: () => Promise -} - -const FirebaseAuthContext = createContext(undefined) - -export const FirebaseAuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { - const [user, setUser] = useState(null) - const [isInitialized, setIsInitialized] = useState(false) - const { setUserInfo } = useExtensionState() - - // Initialize Firebase - const app = initializeApp(firebaseConfig) - const auth = getAuth(app) - - // Handle auth state changes - useEffect(() => { - const unsubscribe = auth.onAuthStateChanged((user) => { - setUser(user) - setIsInitialized(true) - - if (!user) { - // when opening the extension in a new webview (ie if you logged in to sidebar webview but then open a popout tab webview) this effect will trigger without the original webview's session, resulting in us clearing out the user info object. - // we rely on this object to determine if the user is logged in, so we only want to clear it when the user logs out, rather than whenever a webview without a session is opened. - return - } - // Sync auth state with extension - AccountServiceClient.authStateChanged( - AuthStateChangedRequest.create({ - user: user - ? { - displayName: user.displayName ?? undefined, - email: user.email ?? undefined, - photoURL: user.photoURL ?? undefined, - } - : undefined, - }), - ) - .then((response: AuthStateChanged) => { - setUserInfo(response.user) - }) - .catch((error) => { - console.error("Error updating auth state via gRPC:", error) - }) - }) - - return () => unsubscribe() - }, [auth]) - - const signInWithToken = useCallback( - async (token: string) => { - try { - await signInWithCustomToken(auth, token) - console.log("Successfully signed in with custom token") - } catch (error) { - console.error("Error signing in with custom token:", error) - throw error - } - }, - [auth], - ) - - // Set up authCallback subscription - useEffect(() => { - const cleanup = AccountServiceClient.subscribeToAuthCallback(EmptyRequest.create({}), { - onResponse: (event) => { - if (event.value) { - signInWithToken(event.value) - } - }, - onError: (error) => { - console.error("Error in authCallback subscription:", error) - }, - onComplete: () => {}, - }) - - return cleanup - }, [signInWithToken]) - - const handleSignOut = useCallback(async () => { - try { - await signOut(auth) - console.log("Successfully signed out of Firebase") - } catch (error) { - console.error("Error signing out of Firebase:", error) - throw error - } - }, [auth]) - - return ( - - {children} - - ) -} - -export const useFirebaseAuth = () => { - const context = useContext(FirebaseAuthContext) - if (context === undefined) { - throw new Error("useFirebaseAuth must be used within a FirebaseAuthProvider") - } - return context -} diff --git a/webview-ui/src/services/grpc-client-base.js b/webview-ui/src/services/grpc-client-base.js new file mode 100644 index 00000000..f19e5414 --- /dev/null +++ b/webview-ui/src/services/grpc-client-base.js @@ -0,0 +1,126 @@ +import { vscode } from "../utils/vscode" +import { v4 as uuidv4 } from "uuid" +/** + * Helper function to encode request objects + */ +function encodeRequest(request) { + if (request === null || request === undefined) { + return {} + } else if (typeof request.toJSON === "function") { + return request.toJSON() + } else if (typeof request === "object") { + return { ...request } + } else { + return { value: request } + } +} +// Create a client for any protobuf service with inferred types +export function createGrpcClient(service) { + const client = {} + // For each method in the service + Object.values(service.methods).forEach((method) => { + if (method.responseStream) { + // Streaming method implementation + client[method.name] = (request, options) => { + const requestId = uuidv4() + // Set up listener for streaming responses + const handleResponse = (event) => { + const message = event.data + if (message.type === "grpc_response" && message.grpc_response?.request_id === requestId) { + if (message.grpc_response.error) { + // Handle error + if (options.onError) { + options.onError(new Error(message.grpc_response.error)) + } + // Only remove the event listener on error + window.removeEventListener("message", handleResponse) + } else if (message.grpc_response.is_streaming === false) { + // End of stream + if (message.grpc_response.message) { + // Process final message if present + const responseType = method.responseType + const response = responseType.fromJSON(message.grpc_response.message) + options.onResponse(response) + } + if (options.onComplete) { + options.onComplete() + } + // Only remove the event listener when the stream is explicitly ended + window.removeEventListener("message", handleResponse) + } else { + // Process streaming message + if (message.grpc_response.message) { + const responseType = method.responseType + const response = responseType.fromJSON(message.grpc_response.message) + options.onResponse(response) + } + } + } + } + window.addEventListener("message", handleResponse) + // Send the streaming request + const encodedRequest = encodeRequest(request) + vscode.postMessage({ + type: "grpc_request", + grpc_request: { + service: service.fullName, + method: method.name, + message: encodedRequest, + request_id: requestId, + is_streaming: true, + }, + }) + // Return a function to cancel the stream + return () => { + window.removeEventListener("message", handleResponse) + // Send cancellation message + vscode.postMessage({ + type: "grpc_request_cancel", + grpc_request_cancel: { + request_id: requestId, + }, + }) + console.log(`[DEBUG] Sent cancellation for request: ${requestId}`) + } + } + } else { + // Unary method implementation + client[method.name] = (request) => { + return new Promise((resolve, reject) => { + const requestId = uuidv4() + // Set up one-time listener for this specific request + const handleResponse = (event) => { + const message = event.data + if (message.type === "grpc_response" && message.grpc_response?.request_id === requestId) { + // Remove listener once we get our response + window.removeEventListener("message", handleResponse) + if (message.grpc_response.error) { + reject(new Error(message.grpc_response.error)) + } else { + // Convert JSON back to protobuf message + const responseType = method.responseType + const response = responseType.fromJSON(message.grpc_response.message) + resolve(response) + } + } + } + window.addEventListener("message", handleResponse) + // Send the request + const encodedRequest = encodeRequest(request) + vscode.postMessage({ + type: "grpc_request", + grpc_request: { + service: service.fullName, + method: method.name, + message: encodedRequest, + request_id: requestId, + is_streaming: false, + }, + }) + }) + } + } + }) + return client +} +//# sourceMappingURL=grpc-client-base.js.map diff --git a/webview-ui/src/services/grpc-client-base.js.map b/webview-ui/src/services/grpc-client-base.js.map new file mode 100644 index 00000000..2640a019 --- /dev/null +++ b/webview-ui/src/services/grpc-client-base.js.map @@ -0,0 +1 @@ +{"version":3,"file":"grpc-client-base.js","sourceRoot":"","sources":["grpc-client-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAgCnC;;GAEG;AACH,SAAS,aAAa,CAAC,OAAY;IAClC,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC/C,OAAO,EAAE,CAAA;IACV,CAAC;SAAM,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QACjD,OAAO,OAAO,CAAC,MAAM,EAAE,CAAA;IACxB,CAAC;SAAM,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,EAAE,GAAG,OAAO,EAAE,CAAA;IACtB,CAAC;SAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAA;IAC1B,CAAC;AACF,CAAC;AAED,+DAA+D;AAC/D,MAAM,UAAU,gBAAgB,CAAyB,OAAU;IAClE,MAAM,MAAM,GAAG,EAAuB,CAAA;IAEtC,iCAAiC;IACjC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QACjD,IAAI,MAAM,CAAC,cAAc,EAAE,CAAC;YAC3B,kCAAkC;YAClC,MAAM,CAAC,MAAM,CAAC,IAA+B,CAAC,GAAG,CAAC,CACjD,OAAY,EACZ,OAIC,EACA,EAAE;gBACH,MAAM,SAAS,GAAG,MAAM,EAAE,CAAA;gBAE1B,0CAA0C;gBAC1C,MAAM,cAAc,GAAG,CAAC,KAAmB,EAAE,EAAE;oBAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAA;oBAC1B,IAAI,OAAO,CAAC,IAAI,KAAK,eAAe,IAAI,OAAO,CAAC,aAAa,EAAE,UAAU,KAAK,SAAS,EAAE,CAAC;wBACzF,IAAI,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;4BACjC,eAAe;4BACf,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;gCACrB,OAAO,CAAC,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAA;4BACxD,CAAC;4BACD,0CAA0C;4BAC1C,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;wBACtD,CAAC;6BAAM,IAAI,OAAO,CAAC,aAAa,CAAC,YAAY,KAAK,KAAK,EAAE,CAAC;4BACzD,gBAAgB;4BAChB,IAAI,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;gCACnC,mCAAmC;gCACnC,MAAM,YAAY,GAAG,MAAM,CAAC,YAAY,CAAA;gCACxC,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;gCACrE,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;4BAC7B,CAAC;4BAED,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;gCACxB,OAAO,CAAC,UAAU,EAAE,CAAA;4BACrB,CAAC;4BACD,qEAAqE;4BACrE,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;wBACtD,CAAC;6BAAM,CAAC;4BACP,4BAA4B;4BAC5B,IAAI,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;gCACnC,MAAM,YAAY,GAAG,MAAM,CAAC,YAAY,CAAA;gCACxC,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;gCACrE,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;4BAC7B,CAAC;wBACF,CAAC;oBACF,CAAC;gBACF,CAAC,CAAA;gBAED,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;gBAElD,6BAA6B;gBAC7B,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;gBAE7C,MAAM,CAAC,WAAW,CAAC;oBAClB,IAAI,EAAE,cAAc;oBACpB,YAAY,EAAE;wBACb,OAAO,EAAE,OAAO,CAAC,QAAQ;wBACzB,MAAM,EAAE,MAAM,CAAC,IAAI;wBACnB,OAAO,EAAE,cAAc;wBACvB,UAAU,EAAE,SAAS;wBACrB,YAAY,EAAE,IAAI;qBAClB;iBACD,CAAC,CAAA;gBAEF,yCAAyC;gBACzC,OAAO,GAAG,EAAE;oBACX,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;oBACrD,4BAA4B;oBAC5B,MAAM,CAAC,WAAW,CAAC;wBAClB,IAAI,EAAE,qBAAqB;wBAC3B,mBAAmB,EAAE;4BACpB,UAAU,EAAE,SAAS;yBACrB;qBACD,CAAC,CAAA;oBACF,OAAO,CAAC,GAAG,CAAC,0CAA0C,SAAS,EAAE,CAAC,CAAA;gBACnE,CAAC,CAAA;YACF,CAAC,CAAQ,CAAA;QACV,CAAC;aAAM,CAAC;YACP,8BAA8B;YAC9B,MAAM,CAAC,MAAM,CAAC,IAA+B,CAAC,GAAG,CAAC,CAAC,OAAY,EAAE,EAAE;gBAClE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBACtC,MAAM,SAAS,GAAG,MAAM,EAAE,CAAA;oBAE1B,qDAAqD;oBACrD,MAAM,cAAc,GAAG,CAAC,KAAmB,EAAE,EAAE;wBAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAA;wBAC1B,IAAI,OAAO,CAAC,IAAI,KAAK,eAAe,IAAI,OAAO,CAAC,aAAa,EAAE,UAAU,KAAK,SAAS,EAAE,CAAC;4BACzF,2CAA2C;4BAC3C,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;4BAErD,IAAI,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;gCACjC,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAA;4BAC/C,CAAC;iCAAM,CAAC;gCACP,wCAAwC;gCACxC,MAAM,YAAY,GAAG,MAAM,CAAC,YAAY,CAAA;gCACxC,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;gCACrE,OAAO,CAAC,QAAQ,CAAC,CAAA;4BAClB,CAAC;wBACF,CAAC;oBACF,CAAC,CAAA;oBAED,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;oBAElD,mBAAmB;oBACnB,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;oBAE7C,MAAM,CAAC,WAAW,CAAC;wBAClB,IAAI,EAAE,cAAc;wBACpB,YAAY,EAAE;4BACb,OAAO,EAAE,OAAO,CAAC,QAAQ;4BACzB,MAAM,EAAE,MAAM,CAAC,IAAI;4BACnB,OAAO,EAAE,cAAc;4BACvB,UAAU,EAAE,SAAS;4BACrB,YAAY,EAAE,KAAK;yBACnB;qBACD,CAAC,CAAA;gBACH,CAAC,CAAC,CAAA;YACH,CAAC,CAAQ,CAAA;QACV,CAAC;IACF,CAAC,CAAC,CAAA;IAEF,OAAO,MAAM,CAAA;AACd,CAAC"} \ No newline at end of file diff --git a/webview-ui/src/services/grpc-client.js b/webview-ui/src/services/grpc-client.js new file mode 100644 index 00000000..0c7a85c5 --- /dev/null +++ b/webview-ui/src/services/grpc-client.js @@ -0,0 +1,39 @@ +// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY +// Generated by proto/build-proto.js +import { createGrpcClient } from "./grpc-client-base" +import { AccountServiceDefinition } from "@shared/proto/account" +import { BrowserServiceDefinition } from "@shared/proto/browser" +import { CheckpointsServiceDefinition } from "@shared/proto/checkpoints" +import { FileServiceDefinition } from "@shared/proto/file" +import { McpServiceDefinition } from "@shared/proto/mcp" +import { StateServiceDefinition } from "@shared/proto/state" +import { TaskServiceDefinition } from "@shared/proto/task" +import { WebServiceDefinition } from "@shared/proto/web" +import { ModelsServiceDefinition } from "@shared/proto/models" +import { SlashServiceDefinition } from "@shared/proto/slash" +import { UiServiceDefinition } from "@shared/proto/ui" +const AccountServiceClient = createGrpcClient(AccountServiceDefinition) +const BrowserServiceClient = createGrpcClient(BrowserServiceDefinition) +const CheckpointsServiceClient = createGrpcClient(CheckpointsServiceDefinition) +const FileServiceClient = createGrpcClient(FileServiceDefinition) +const McpServiceClient = createGrpcClient(McpServiceDefinition) +const StateServiceClient = createGrpcClient(StateServiceDefinition) +const TaskServiceClient = createGrpcClient(TaskServiceDefinition) +const WebServiceClient = createGrpcClient(WebServiceDefinition) +const ModelsServiceClient = createGrpcClient(ModelsServiceDefinition) +const SlashServiceClient = createGrpcClient(SlashServiceDefinition) +const UiServiceClient = createGrpcClient(UiServiceDefinition) +export { + AccountServiceClient, + BrowserServiceClient, + CheckpointsServiceClient, + FileServiceClient, + McpServiceClient, + StateServiceClient, + TaskServiceClient, + WebServiceClient, + ModelsServiceClient, + SlashServiceClient, + UiServiceClient, +} +//# sourceMappingURL=grpc-client.js.map diff --git a/webview-ui/src/services/grpc-client.js.map b/webview-ui/src/services/grpc-client.js.map new file mode 100644 index 00000000..2f147d27 --- /dev/null +++ b/webview-ui/src/services/grpc-client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"grpc-client.js","sourceRoot":"","sources":["grpc-client.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAC/C,oCAAoC;AAEpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAA;AAChE,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAA;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAA;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAA;AAEtD,MAAM,oBAAoB,GAAG,gBAAgB,CAAC,wBAAwB,CAAC,CAAA;AACvE,MAAM,oBAAoB,GAAG,gBAAgB,CAAC,wBAAwB,CAAC,CAAA;AACvE,MAAM,wBAAwB,GAAG,gBAAgB,CAAC,4BAA4B,CAAC,CAAA;AAC/E,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,qBAAqB,CAAC,CAAA;AACjE,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,oBAAoB,CAAC,CAAA;AAC/D,MAAM,kBAAkB,GAAG,gBAAgB,CAAC,sBAAsB,CAAC,CAAA;AACnE,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,qBAAqB,CAAC,CAAA;AACjE,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,oBAAoB,CAAC,CAAA;AAC/D,MAAM,mBAAmB,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,CAAA;AACrE,MAAM,kBAAkB,GAAG,gBAAgB,CAAC,sBAAsB,CAAC,CAAA;AACnE,MAAM,eAAe,GAAG,gBAAgB,CAAC,mBAAmB,CAAC,CAAA;AAE7D,OAAO,EACN,oBAAoB,EACpB,oBAAoB,EACpB,wBAAwB,EACxB,iBAAiB,EACjB,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,CAAA"} \ No newline at end of file diff --git a/webview-ui/src/utils/validate.ts b/webview-ui/src/utils/validate.ts index 79686eae..77233510 100644 --- a/webview-ui/src/utils/validate.ts +++ b/webview-ui/src/utils/validate.ts @@ -59,7 +59,7 @@ export function validateApiConfiguration(apiConfiguration?: ApiConfiguration): s } break case "cline": - if (!apiConfiguration.clineApiKey) { + if (!apiConfiguration.clineAccountId) { return "You must provide a valid API key or choose a different provider." } break diff --git a/webview-ui/src/utils/vscode.js b/webview-ui/src/utils/vscode.js new file mode 100644 index 00000000..aac2ed36 --- /dev/null +++ b/webview-ui/src/utils/vscode.js @@ -0,0 +1,71 @@ +class VSCodeAPIWrapper { + vsCodeApi + constructor() { + // Check if the acquireVsCodeApi function exists in the current development + // context (i.e. VS Code development window or web browser) + if (typeof acquireVsCodeApi === "function") { + this.vsCodeApi = acquireVsCodeApi() + } + } + /** + * Post a message (i.e. send arbitrary data) to the owner of the webview. + * + * @remarks When running webview code inside a web browser, postMessage will instead + * log the given message to the console. + * + * @param message Arbitrary data (must be JSON serializable) to send to the extension context. + */ + postMessage(message) { + if (this.vsCodeApi) { + this.vsCodeApi.postMessage(message) + } else if (window.__is_standalone__) { + if (!window.standalonePostMessage) { + console.warn("Standalone postMessage not found.") + return + } + const json = JSON.stringify(message) + console.log("Standalone postMessage: " + json.slice(0, 200)) + window.standalonePostMessage(json) + } else { + console.log("postMessage fallback: ", message) + } + } + /** + * Get the persistent state stored for this webview. + * + * @remarks When running webview source code inside a web browser, getState will retrieve state + * from local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). + * + * @return The current state or `undefined` if no state has been set. + */ + getState() { + if (this.vsCodeApi) { + return this.vsCodeApi.getState() + } else { + const state = localStorage.getItem("vscodeState") + return state ? JSON.parse(state) : undefined + } + } + /** + * Set the persistent state stored for this webview. + * + * @remarks When running webview source code inside a web browser, setState will set the given + * state using local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). + * + * @param newState New persisted state. This must be a JSON serializable object. Can be retrieved + * using {@link getState}. + * + * @return The new state. + */ + setState(newState) { + if (this.vsCodeApi) { + return this.vsCodeApi.setState(newState) + } else { + localStorage.setItem("vscodeState", JSON.stringify(newState)) + return newState + } + } +} +// Exports class singleton to prevent multiple invocations of acquireVsCodeApi. +export const vscode = new VSCodeAPIWrapper() +//# sourceMappingURL=vscode.js.map diff --git a/webview-ui/src/utils/vscode.js.map b/webview-ui/src/utils/vscode.js.map new file mode 100644 index 00000000..50c8d556 --- /dev/null +++ b/webview-ui/src/utils/vscode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"vscode.js","sourceRoot":"","sources":["vscode.ts"],"names":[],"mappings":"AAmBA,MAAM,gBAAgB;IACJ,SAAS,CAAiC;IAE3D;QACC,2EAA2E;QAC3E,2DAA2D;QAC3D,IAAI,OAAO,gBAAgB,KAAK,UAAU,EAAE,CAAC;YAC5C,IAAI,CAAC,SAAS,GAAG,gBAAgB,EAAE,CAAA;QACpC,CAAC;IACF,CAAC;IAED;;;;;;;OAOG;IACI,WAAW,CAAC,OAAuB;QACzC,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;QACpC,CAAC;aAAM,IAAI,MAAM,CAAC,iBAAiB,EAAE,CAAC;YACrC,IAAI,CAAC,MAAM,CAAC,qBAAqB,EAAE,CAAC;gBACnC,OAAO,CAAC,IAAI,CAAC,mCAAmC,CAAC,CAAA;gBACjD,OAAM;YACP,CAAC;YACD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;YACpC,OAAO,CAAC,GAAG,CAAC,0BAA0B,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAA;YAC5D,MAAM,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAA;QACnC,CAAC;aAAM,CAAC;YACP,OAAO,CAAC,GAAG,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAA;QAC/C,CAAC;IACF,CAAC;IAED;;;;;;;OAOG;IACI,QAAQ;QACd,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAA;QACjC,CAAC;aAAM,CAAC;YACP,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,CAAA;YACjD,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;QAC7C,CAAC;IACF,CAAC;IAED;;;;;;;;;;OAUG;IACI,QAAQ,CAAgC,QAAW;QACzD,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;QACzC,CAAC;aAAM,CAAC;YACP,YAAY,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAA;YAC7D,OAAO,QAAQ,CAAA;QAChB,CAAC;IACF,CAAC;CACD;AAED,+EAA+E;AAC/E,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,gBAAgB,EAAE,CAAA"} \ No newline at end of file From 2428389620105f74853ffa7535493f0ebfb52874 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 8 Jul 2025 16:16:52 -0700 Subject: [PATCH 38/43] v3.18.6 Release Notes v3.18.6 Release Notes --- .changeset/gorgeous-apes-fry.md | 5 ----- .changeset/little-lions-joke.md | 5 ----- .changeset/three-gifts-add.md | 5 ----- CHANGELOG.md | 5 +++++ package-lock.json | 4 ++-- package.json | 2 +- 6 files changed, 8 insertions(+), 18 deletions(-) delete mode 100644 .changeset/gorgeous-apes-fry.md delete mode 100644 .changeset/little-lions-joke.md delete mode 100644 .changeset/three-gifts-add.md diff --git a/.changeset/gorgeous-apes-fry.md b/.changeset/gorgeous-apes-fry.md deleted file mode 100644 index e35440ca..00000000 --- a/.changeset/gorgeous-apes-fry.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -host bridge migration - openExternal diff --git a/.changeset/little-lions-joke.md b/.changeset/little-lions-joke.md deleted file mode 100644 index b4d90b4b..00000000 --- a/.changeset/little-lions-joke.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": minor ---- - -Update request header to include `"ai-client-type": "Cline"` diff --git a/.changeset/three-gifts-add.md b/.changeset/three-gifts-add.md deleted file mode 100644 index 16cdac02..00000000 --- a/.changeset/three-gifts-add.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Add organization and personal account management with credit reporting and account switching diff --git a/CHANGELOG.md b/CHANGELOG.md index ab74baa5..0c48e1b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [3.18.6] + +- Update request header to include `"ai-client-type": "Cline"` to SAP Api Provider +- Add organization organization accounts + ## [3.18.5] - Fix Plan/Act mode persistence across sessions and multi-workspace conflicts diff --git a/package-lock.json b/package-lock.json index 37e74418..85c76975 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.5", + "version": "3.18.6", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.5", + "version": "3.18.6", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index b5ef0f59..4cefead8 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.5", + "version": "3.18.6", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" From ff1e3297a8a16a2b8c0b16ae71d0db2f01a40d8c Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Tue, 8 Jul 2025 17:30:06 -0700 Subject: [PATCH 39/43] ending grok promo in UI (#4740) * ending grok promo in UI * changeset --- .changeset/little-ants-occur.md | 5 +++++ webview-ui/src/components/settings/OpenRouterModelPicker.tsx | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 .changeset/little-ants-occur.md diff --git a/.changeset/little-ants-occur.md b/.changeset/little-ants-occur.md new file mode 100644 index 00000000..0604b10d --- /dev/null +++ b/.changeset/little-ants-occur.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Ending grok 3 promo diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index 5f344c84..5db09682 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -55,8 +55,8 @@ const featuredModels = [ }, { id: "x-ai/grok-3", - description: "Latest flagship model from xAI, free for now!", - label: "Free", + description: "Latest flagship model from xAI", + label: "Fast & Cheap", }, ] From d838bcdc34ede4129a5affa4ee6497af8ca30b99 Mon Sep 17 00:00:00 2001 From: Dennise Bartlett Date: Tue, 8 Jul 2025 17:56:38 -0700 Subject: [PATCH 40/43] Fix account buttons (#4742) * Update links for account buttons * add dashboard url * setup links for future changes --------- Co-authored-by: frostbournesb --- webview-ui/src/components/account/AccountView.tsx | 10 ++++++---- webview-ui/src/components/chat/CreditLimitError.tsx | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/webview-ui/src/components/account/AccountView.tsx b/webview-ui/src/components/account/AccountView.tsx index 414e6acb..9c05c594 100644 --- a/webview-ui/src/components/account/AccountView.tsx +++ b/webview-ui/src/components/account/AccountView.tsx @@ -52,6 +52,10 @@ export const ClineAccountView = () => { const [usageData, setUsageData] = useState([]) const [paymentsData, setPaymentsData] = useState([]) + const dashboardAddCreditsURL = activeOrganization + ? "https://app.cline.bot/dashboard/organization?tab=credits&redirect=true" + : "https://app.cline.bot/dashboard/account?tab=credits&redirect=true" + async function getUserCredits() { setIsLoading(true) try { @@ -204,8 +208,7 @@ export const ClineAccountView = () => {
- {/* TODO: Update to get url for dashboard from EXT */} - + Dashboard
@@ -237,8 +240,7 @@ export const ClineAccountView = () => {
- {/* TODO: Update to get url for dashboard from EXT */} - + Add Credits
diff --git a/webview-ui/src/components/chat/CreditLimitError.tsx b/webview-ui/src/components/chat/CreditLimitError.tsx index ea59d7ef..9500d28d 100644 --- a/webview-ui/src/components/chat/CreditLimitError.tsx +++ b/webview-ui/src/components/chat/CreditLimitError.tsx @@ -30,7 +30,7 @@ const CreditLimitError: React.FC = ({ currentBalance, tot
Date: Tue, 8 Jul 2025 17:57:40 -0700 Subject: [PATCH 41/43] v3.18.7 Release Notes * changeset version bump * Updating CHANGELOG.md format * Update CHANGELOG.md for version 3.18.7 --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: github-actions Co-authored-by: pashpashpash --- .changeset/little-ants-occur.md | 5 --- CHANGELOG.md | 4 ++ package-lock.json | 4 +- package.json | 2 +- src/api/providers/cline.ts | 3 -- src/api/providers/openrouter.ts | 3 -- .../models/refreshOpenRouterModels.ts | 5 --- .../src/components/account/AccountView.tsx | 44 +++++++++---------- .../settings/OpenRouterModelPicker.tsx | 2 +- .../settings/utils/providerUtils.ts | 7 +-- 10 files changed, 31 insertions(+), 48 deletions(-) delete mode 100644 .changeset/little-ants-occur.md diff --git a/.changeset/little-ants-occur.md b/.changeset/little-ants-occur.md deleted file mode 100644 index 0604b10d..00000000 --- a/.changeset/little-ants-occur.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Ending grok 3 promo diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c48e1b4..57c2a8ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [3.18.7] + +- Remove promotional "free" messaging for Grok 3 model in UI + ## [3.18.6] - Update request header to include `"ai-client-type": "Cline"` to SAP Api Provider diff --git a/package-lock.json b/package-lock.json index 85c76975..fb2461db 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.6", + "version": "3.18.7", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.6", + "version": "3.18.7", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index 4cefead8..74ef0776 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.6", + "version": "3.18.7", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" diff --git a/src/api/providers/cline.ts b/src/api/providers/cline.ts index 3ba0a70d..e0a80efe 100644 --- a/src/api/providers/cline.ts +++ b/src/api/providers/cline.ts @@ -266,9 +266,6 @@ export class ClineHandler implements ApiHandler { getModel(): { id: string; info: ModelInfo } { let modelId = this.options.openRouterModelId - if (modelId === "x-ai/grok-3") { - modelId = "x-ai/grok-3-beta" - } const modelInfo = this.options.openRouterModelInfo if (modelId && modelInfo) { return { id: modelId, info: modelInfo } diff --git a/src/api/providers/openrouter.ts b/src/api/providers/openrouter.ts index 4fbd64ad..7e821dea 100644 --- a/src/api/providers/openrouter.ts +++ b/src/api/providers/openrouter.ts @@ -204,9 +204,6 @@ export class OpenRouterHandler implements ApiHandler { getModel(): { id: string; info: ModelInfo } { let modelId = this.options.openRouterModelId - if (modelId === "x-ai/grok-3") { - modelId = "x-ai/grok-3-beta" - } const modelInfo = this.options.openRouterModelInfo if (modelId && modelInfo) { return { id: modelId, info: modelInfo } diff --git a/src/core/controller/models/refreshOpenRouterModels.ts b/src/core/controller/models/refreshOpenRouterModels.ts index 3dbae316..ef270352 100644 --- a/src/core/controller/models/refreshOpenRouterModels.ts +++ b/src/core/controller/models/refreshOpenRouterModels.ts @@ -122,11 +122,6 @@ export async function refreshOpenRouterModels( break } - // add new model id - if (rawModel.id === "x-ai/grok-3-beta") { - models["x-ai/grok-3"] = modelInfo - } - models[rawModel.id] = modelInfo } } else { diff --git a/webview-ui/src/components/account/AccountView.tsx b/webview-ui/src/components/account/AccountView.tsx index 9c05c594..179c0c45 100644 --- a/webview-ui/src/components/account/AccountView.tsx +++ b/webview-ui/src/components/account/AccountView.tsx @@ -47,7 +47,6 @@ export const ClineAccountView = () => { const [balance, setBalance] = useState(0) const [userOrganizations, setUserOrganizations] = useState([]) const [activeOrganization, setActiveOrganization] = useState(null) - const [midOrgOptimisticUpdate, setMidOrgOptimisticUpdate] = useState(false) const [isLoading, setIsLoading] = useState(true) const [usageData, setUsageData] = useState([]) const [paymentsData, setPaymentsData] = useState([]) @@ -115,24 +114,33 @@ export const ClineAccountView = () => { // Fetch all account data when component mounts using gRPC useEffect(() => { - if (user) { - ;(async () => { - await Promise.all([getUserCredits(), getUserOrganizations()]) - })() + if (!user) return + + const fetchUserData = async () => { + try { + await getUserCredits() + await getUserOrganizations() + } catch (error) { + console.error("Failed to fetch user data:", error) + } } + + fetchUserData() }, [user]) useEffect(() => { - if (midOrgOptimisticUpdate) { - return + if (!activeOrganization) return + + const fetchOrgCredits = async () => { + try { + await getOrganizationCredits() + } catch (error) { + console.error("Failed to fetch organization credits:", error) + } } - if (activeOrganization) { - ;(async () => { - await getOrganizationCredits() - })() - } - }, [activeOrganization, midOrgOptimisticUpdate]) + fetchOrgCredits() + }, [activeOrganization]) const handleLogin = () => { handleSignIn() @@ -146,19 +154,11 @@ export const ClineAccountView = () => { const newOrgId = (event.target as VSCodeDropdownChangeEvent["target"]).value if (!activeOrganization || activeOrganization.organizationId !== newOrgId) { - const newSelectedOrg = - newOrgId === "" ? null : userOrganizations.find((org) => org.organizationId === newOrgId) || null - const previousOrganization = activeOrganization - setMidOrgOptimisticUpdate(true) - setActiveOrganization(newSelectedOrg) try { await AccountServiceClient.setUserOrganization(UserOrganizationUpdateRequest.create({ organizationId: newOrgId })) - setMidOrgOptimisticUpdate(false) - getUserOrganizations() + await getUserOrganizations() } catch (error) { console.error("Failed to update organization:", error) - setMidOrgOptimisticUpdate(false) - setActiveOrganization(previousOrganization) } } } diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index 5db09682..aa5b6046 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -54,7 +54,7 @@ const featuredModels = [ label: "Trending", }, { - id: "x-ai/grok-3", + id: "x-ai/grok-3-beta", description: "Latest flagship model from xAI", label: "Fast & Cheap", }, diff --git a/webview-ui/src/components/settings/utils/providerUtils.ts b/webview-ui/src/components/settings/utils/providerUtils.ts index bcfc9b85..1b5711ac 100644 --- a/webview-ui/src/components/settings/utils/providerUtils.ts +++ b/webview-ui/src/components/settings/utils/providerUtils.ts @@ -129,12 +129,7 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration): return { selectedProvider: provider, selectedModelId: openRouterModelId, - // TODO: remove this once we have a better way to handle free models on Cline - // Free grok 3 promotion - selectedModelInfo: - openRouterModelId === "x-ai/grok-3" - ? { ...openRouterModelInfo, inputPrice: 0, outputPrice: 0 } - : openRouterModelInfo, + selectedModelInfo: openRouterModelInfo, } case "openai": return { From bf82444aecb2b53b4fd9e4f2bea4d5eedeee7eb4 Mon Sep 17 00:00:00 2001 From: Frostbourne Date: Tue, 8 Jul 2025 19:59:17 -0700 Subject: [PATCH 42/43] grok 3 cache pricing (#4750) --- src/core/controller/models/refreshOpenRouterModels.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/controller/models/refreshOpenRouterModels.ts b/src/core/controller/models/refreshOpenRouterModels.ts index ef270352..cae6ba01 100644 --- a/src/core/controller/models/refreshOpenRouterModels.ts +++ b/src/core/controller/models/refreshOpenRouterModels.ts @@ -101,7 +101,7 @@ export async function refreshOpenRouterModels( break case "x-ai/grok-3-beta": modelInfo.supportsPromptCache = true - modelInfo.cacheWritesPrice = 0 + modelInfo.cacheWritesPrice = 0.75 modelInfo.cacheReadsPrice = 0 break default: From dea016408c82cb606adc72b96dc50399e8a93139 Mon Sep 17 00:00:00 2001 From: Dennise Bartlett Date: Tue, 8 Jul 2025 20:13:37 -0700 Subject: [PATCH 43/43] Update Changelog and Versions (#4751) --- CHANGELOG.md | 4 ++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57c2a8ec..d9a3ead8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [3.18.8] + +- Update pricing for Grok 3 model because the promotion ended + ## [3.18.7] - Remove promotional "free" messaging for Grok 3 model in UI diff --git a/package-lock.json b/package-lock.json index fb2461db..9e00df7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.7", + "version": "3.18.8", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.7", + "version": "3.18.8", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index 74ef0776..aa2535dc 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,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.", - "version": "3.18.7", + "version": "3.18.8", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0"