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/.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/.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/.vscodeignore b/.vscodeignore index c64544ec..0265a0ef 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 @@ -33,6 +36,8 @@ webview-ui/node_modules/** # Ignore docs docs/** assets/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 !node_modules/@vscode/codicons/dist/codicon.ttf diff --git a/CHANGELOG.md b/CHANGELOG.md index 981c16fb..d9a3ead8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,43 @@ # 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 + +## [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 +- 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 +- 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!) +- 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. +- 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/README.md b/README.md index 4e4aca99..8b517dbb 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ | ✨ 为什么选择 Cline 中文版? | 👉 **扫码添加,领取 100 万 Tokens** 👈 | |:--|:--:| -| ✅ **中文界面体验** —— 一贴合中文开发者使用习惯,命令更自然
✅ **超百款全球模型接入** —— 包括 GPT-4o、Claude 4 sonnet、 Claude 4 opus、Gemini 2.5 pro/flash、DeepSeek 等
✅ **大模型聚合** —— 一调即价更低,性能稳定不掉线
✅ **人民币充值直通** —— 无需海外账号,支持微信/支付宝
✅ **VS Code 插件/原生集成** —— 快速安装,即刻启用
✅ **注册即送 Tokens** —— 免费 100 万 Tokens | ![个人企业微信](https://github.com/user-attachments/assets/482850bf-f152-44e8-9845-b043f3d6eeb7) | +| ✅ **中文界面体验** —— 一贴合中文开发者使用习惯,命令更自然
✅ **超百款全球模型接入** —— 包括 GPT-4o、Claude 4 sonnet、 Claude 4 opus、Gemini 2.5 pro/flash、DeepSeek 等
✅ **大模型聚合** —— 一调即价更低,性能稳定不掉线
✅ **人民币充值直通** —— 无需海外账号,支持微信/支付宝
✅ **VS Code 插件/原生集成** —— 快速安装,即刻启用
✅ **注册即送 Tokens** —— 免费 100 万 Tokens | ![个人企业微信](https://router.shengsuanyun.com/webp/relation-BMfLRnIZ.webp) | 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..baa2d91a 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 9396c22b..95c7bb61 100644 --- a/docs/features/commands-and-shortcuts/terminal-integration.mdx +++ b/docs/features/commands-and-shortcuts/terminal-integration.mdx @@ -73,8 +73,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..556e53fd --- /dev/null +++ b/docs/troubleshooting/terminal-integration-guide.mdx @@ -0,0 +1,390 @@ +--- +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..00f97706 --- /dev/null +++ b/docs/troubleshooting/terminal-quick-fixes.mdx @@ -0,0 +1,49 @@ +--- +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/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/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 } diff --git a/package-lock.json b/package-lock.json index 1d07e306..d2b67e18 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cline-shengsuan", - "version": "3.18.1", + "version": "3.18.8", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "cline-shengsuan", - "version": "3.18.1", + "version": "3.18.8", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index 862c3026..2d7aca90 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "cline-shengsuan", "displayName": "Cline-中文版", "description": "Cline-中文版是一款在您的IDE中运行的强大自主编程助手,经您许可后可创建/编辑文件、运行命令、使用浏览器等。", - "version": "3.18.2", + "version": "3.18.8", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" diff --git a/proto/account.proto b/proto/account.proto index 5c5eff6f..87350bd1 100644 --- a/proto/account.proto +++ b/proto/account.proto @@ -1,81 +1,136 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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); + rpc shengSuanYunLoginClicked(EmptyRequest) returns (String); + rpc shengSuanYunLogoutClicked(EmptyRequest) returns (Empty); + rpc shengSuanYunUserData(EmptyRequest) returns (UserCreditsData); + rpc subscribeSSYAuthCallback(EmptyRequest) returns (stream String); + // Fetches all user credits data + // (balance, usage transactions, payment transactions) + rpc getUserCredits(EmptyRequest) returns (UserCreditsData); - rpc shengSuanYunLoginClicked(EmptyRequest) returns (String); - rpc shengSuanYunLogoutClicked(EmptyRequest) returns (Empty); - rpc shengSuanYunUserData(EmptyRequest) returns (UserCreditsData); - rpc subscribeSSYAuthCallback(EmptyRequest) returns (stream String); + 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; + optional string spent_at = 13; + optional string model = 14; + optional string credits = 15; } -// 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; } diff --git a/proto/browser.proto b/proto/browser.proto index 7b76b5a8..4d6e1099 100644 --- a/proto/browser.proto +++ b/proto/browser.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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 15622d26..57dc737a 100644 --- a/proto/checkpoints.proto +++ b/proto/checkpoints.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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 9f512944..cdd4010c 100644 --- a/proto/file.proto +++ b/proto/file.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.proto"; option java_multiple_files = true; -import "common.proto"; - // Service for file-related operations service FileService { // Copies text to clipboard diff --git a/proto/host/env.proto b/proto/host/env.proto index be37db1f..22d54492 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_shengsuan.EmptyRequest) returns (cline_shengsuan.String); + + // Opens a URL in the user's default browser or application. + rpc openExternal(cline_shengsuan.StringRequest) returns (cline_shengsuan.Empty); } diff --git a/proto/host/window.proto b/proto/host/window.proto index 7d62c8c4..ecd37c97 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_shengsuan.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/proto/mcp.proto b/proto/mcp.proto index 83d3d579..d7afa7cb 100644 --- a/proto/mcp.proto +++ b/proto/mcp.proto @@ -1,16 +1,15 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.proto"; option java_multiple_files = true; -import "common.proto"; - 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 +118,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/proto/models.proto b/proto/models.proto index bcd513fc..5de171f5 100644 --- a/proto/models.proto +++ b/proto/models.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.proto"; option java_multiple_files = true; -import "common.proto"; - // Service for model-related operations service ModelsService { // Fetches available models from Ollama @@ -168,7 +167,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; @@ -238,13 +237,14 @@ message ModelsApiConfiguration { optional string sap_ai_resource_group = 70; optional string sap_ai_core_token_url = 71; optional string sap_ai_core_base_url = 72; - optional string claude_code_path = 73; - optional string sheng_suan_yun_token = 74; - optional string sheng_suan_yun_api_key = 75; - optional string sheng_suan_yun_model_id = 76; - optional ShengSuanYunModelInfo sheng_suan_yun_model_info = 77; - optional string gemini_cli_oauth_path = 78; - optional string gemini_cli_project_id = 79; + optional string sap_ai_core_model_id = 73; + optional string claude_code_path = 74; + optional string sheng_suan_yun_token = 75; + optional string sheng_suan_yun_api_key = 76; + optional string sheng_suan_yun_model_id = 77; + optional ShengSuanYunModelInfo sheng_suan_yun_model_info = 78; + optional string gemini_cli_oauth_path = 79; + optional string gemini_cli_project_id = 80; } message ShengSuanYunModelInfo { diff --git a/proto/slash.proto b/proto/slash.proto index 44330c96..4aa464e1 100644 --- a/proto/slash.proto +++ b/proto/slash.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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 fbcb600b..a74900eb 100644 --- a/proto/state.proto +++ b/proto/state.proto @@ -1,10 +1,9 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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 1d8cb529..d2ea6b09 100644 --- a/proto/task.proto +++ b/proto/task.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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 32b7d0d3..38bdc87e 100644 --- a/proto/ui.proto +++ b/proto/ui.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.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 1dd1ebea..341cef71 100644 --- a/proto/web.proto +++ b/proto/web.proto @@ -1,11 +1,10 @@ syntax = "proto3"; package cline_shengsuan; +import "common.proto"; option java_package = "bot.cline_shengsuan.proto"; option java_multiple_files = true; -import "common.proto"; - service WebService { rpc checkIsImageUrl(StringRequest) returns (IsImageUrl); rpc fetchOpenGraphData(StringRequest) returns (OpenGraphData); 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() 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 641d574d..e6085837 100644 --- a/src/api/providers/cerebras.ts +++ b/src/api/providers/cerebras.ts @@ -7,32 +7,52 @@ 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" 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 +70,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,12 +80,19 @@ 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 }) } } try { - const stream = await this.client.chat.completions.create({ + const stream = await client.chat.completions.create({ model: this.getModel().id, messages: cerebrasMessages, temperature: 0, @@ -74,8 +101,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 diff --git a/src/api/providers/cline.ts b/src/api/providers/cline.ts index 18aea6c0..e0a80efe 100644 --- a/src/api/providers/cline.ts +++ b/src/api/providers/cline.ts @@ -1,143 +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 + 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 - 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 - }, - }) + this._authService = AuthService.getInstance() } @withRetry() async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { + const clineAccountAuthToken = await this._authService.getAuthToken() + this.lastGenerationId = undefined - const stream = await createOpenRouterStream( - this.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 }) @@ -175,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/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 77f97557..19bb6047 100644 --- a/src/api/providers/ollama.ts +++ b/src/api/providers/ollama.ts @@ -9,15 +9,26 @@ import fetch from "node-fetch" 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 { // Create a promise that rejects after timeout @@ -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..7e821dea 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(), @@ -190,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/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/sapaicore.ts b/src/api/providers/sapaicore.ts index 93724aa4..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() @@ -133,6 +135,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 +191,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 +240,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) } @@ -276,7 +285,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 { @@ -339,7 +347,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) { @@ -415,7 +422,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] @@ -439,7 +445,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 { @@ -461,6 +467,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 +583,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/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, diff --git a/src/core/context/context-tracking/FileContextTracker.ts b/src/core/context/context-tracking/FileContextTracker.ts index 14f7d4ce..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 } @@ -244,7 +235,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 +249,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 +264,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 +295,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/account/accountLoginClicked.ts b/src/core/controller/account/accountLoginClicked.ts index 16b82083..d0284b4f 100644 --- a/src/core/controller/account/accountLoginClicked.ts +++ b/src/core/controller/account/accountLoginClicked.ts @@ -1,8 +1,9 @@ -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. @@ -13,21 +14,5 @@ import { EmptyRequest, String } from "../../../shared/proto/common" * @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"}://shengsuan-cloud.cline-shengsuan/auth`)}`, - ) - await vscode.env.openExternal(authUrl) - 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/file/createRuleFile.ts b/src/core/controller/file/createRuleFile.ts index 872a00af..e7d90e77 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/getRelativePaths.ts b/src/core/controller/file/getRelativePaths.ts index bda41ca2..8dfb330b 100644 --- a/src/core/controller/file/getRelativePaths.ts +++ b/src/core/controller/file/getRelativePaths.ts @@ -1,10 +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 * as path from "path" -import { StringRequest } from "@shared/proto/common" -import { getHostBridgeProvider } from "@hosts/host-providers" +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 @@ -13,47 +13,32 @@ 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 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 isDirectory(filePath)) { + result += "/" + } + return result } 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/controller/index.ts b/src/core/controller/index.ts index 0b03a6cf..8b5bdf1b 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" @@ -30,20 +30,19 @@ 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 { SSYAccountService } from "../../services/account/SSYAccountService" import { sendSSYAuthCallbackEvent } from "./account/subscribeSSYAuthCallback" +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 @@ -56,12 +55,12 @@ export class Controller { private postMessage: (message: ExtensionMessage) => Thenable | undefined public uriScheme = vscode.env.uriScheme private disposables: vscode.Disposable[] = [] - private mode: "plan" | "act" = "plan" // In-memory plan/act mode state task?: Task workspaceTracker: WorkspaceTracker mcpHub: McpHub accountService: ClineAccountService accountServiceSSY: SSYAccountService + authService: AuthService latestAnnouncementId = "june-25-2025_16:11:00" // update to some unique identifier when we add a new announcement constructor( @@ -85,10 +84,9 @@ export class Controller { const { apiConfiguration } = await this.getStateToPostToWebview() return apiConfiguration?.shengSuanYunToken }) - 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) => { @@ -96,6 +94,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/ @@ -120,7 +122,7 @@ export class Controller { try { await updateGlobalState(this.context, "shengSuanYunToken", undefined) await updateGlobalState(this.context, "userInfo", undefined) - await updateWorkspaceState(this.context, "apiProvider", "shengsuanyun") + await updateGlobalState(this.context, "apiProvider", "shengsuanyun") await this.postStateToWebview() // vscode.window.showInformationMessage("成功登出 Cline 胜算云") } catch (error) { @@ -148,10 +150,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 @@ -186,6 +191,7 @@ export class Controller { terminalOutputLineLimit ?? 500, defaultTerminalProfile ?? "default", enableCheckpointsSetting ?? true, + await getCwd(getDesktopDir()), task, images, files, @@ -244,8 +250,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) @@ -261,11 +267,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) @@ -274,9 +275,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": @@ -286,20 +287,20 @@ 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 "shengsuanyun": - await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.shengSuanYunModelId) - await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.shengSuanYunModelInfo) + await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.shengSuanYunModelId) + await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.shengSuanYunModelInfo) 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, @@ -307,51 +308,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 } @@ -363,9 +351,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": @@ -375,45 +363,46 @@ export class Controller { case "qwen": case "deepseek": case "xai": - await updateWorkspaceState(this.context, "apiModelId", newModelId) + await updateGlobalState(this.context, "apiModelId", newModelId) break case "shengsuanyun": - await updateWorkspaceState(this.context, "shengSuanYunModelId", newModelId) - await updateWorkspaceState(this.context, "shengSuanYunModelInfo", newModelInfo) + await updateGlobalState(this.context, "shengSuanYunModelId", newModelId) + await updateGlobalState(this.context, "shengSuanYunModelInfo", newModelInfo) 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 } @@ -424,9 +413,9 @@ 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 updateWorkspaceState(this.context, "chatSettings", persistentChatSettings) + await updateGlobalState(this.context, "chatSettings", persistentChatSettings) await this.postStateToWebview() if (this.task) { @@ -491,33 +480,29 @@ 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 updateWorkspaceState(this.context, "apiProvider", clineProvider) + 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 = { ...apiConfiguration, apiProvider: clineProvider, - clineApiKey: apiKey, } if (this.task) { @@ -525,7 +510,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("登录失败") @@ -535,7 +519,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", { @@ -669,7 +652,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) { @@ -703,7 +686,7 @@ export class Controller { } const shengsuanyun: ApiProvider = "shengsuanyun" - await updateWorkspaceState(this.context, "apiProvider", shengsuanyun) + await updateGlobalState(this.context, "apiProvider", shengsuanyun) await updateGlobalState(this.context, "shengSuanYunToken", customToken) await storeSecret(this.context, "shengSuanYunApiKey", apiKey) await this.postStateToWebview() @@ -909,10 +892,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 = @@ -1139,6 +1125,4 @@ Commit message:` vscode.window.showErrorMessage(`无法生成提交消息: ${errorMessage}`) } } - - // dev } diff --git a/src/core/controller/mcp/downloadMcp.ts b/src/core/controller/mcp/downloadMcp.ts index 061191c9..e2f14a31 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("下载 MCP 失败:", error) let errorMessage = "下载 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/core/controller/models/refreshOpenRouterModels.ts b/src/core/controller/models/refreshOpenRouterModels.ts index 3dbae316..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: @@ -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/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/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/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/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 25bb93d9..c486516f 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/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index bc91819b..be95a45a 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" @@ -81,14 +81,10 @@ export type GlobalStateKey = | "sapAiCoreTokenUrl" | "sapAiCoreBaseUrl" | "sapAiResourceGroup" - | "sapAiCoreClientId" - | "sapAiCoreClientSecret" - | "sapAiCoreModelId" | "claudeCodePath" - -export type LocalStateKey = - | "localClineRulesToggles" + // Settings around plan/act and ephemeral model configuration | "chatSettings" + | "mode" // Current active model configuration (per workspace) | "apiProvider" | "apiModelId" @@ -109,6 +105,7 @@ export type LocalStateKey = | "requestyModelInfo" | "togetherModelId" | "fireworksModelId" + | "sapAiCoreModelId" // Previous mode saved configurations (per workspace) | "previousModeApiProvider" | "previousModeModelId" @@ -118,9 +115,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..3ca0a296 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 } } @@ -179,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 4ccdd1ec..a2f41122 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" @@ -12,25 +12,73 @@ import { TelemetrySetting } from "@shared/TelemetrySetting" import { UserInfo } from "@shared/UserInfo" import { ClineRulesToggles } from "@shared/cline-rules" import { migrateEnableCheckpointsSetting, migrateMcpMarketplaceEnableSetting } from "./state-migrations" +import { ShengSuanYunModelInfo } from "@/shared/proto/models" /* Storage https://dev.to/kompotkot/how-to-use-secretstorage-in-your-vscode-extensions-2hco https://www.eliostruyf.com/devhack-code-extension-storage-options/ */ -// global +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) } -// secrets +// 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))) +} + +// 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 { @@ -39,26 +87,36 @@ 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: string, value: any) { +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: string) { +export async function getWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey) { + if (isTemporaryProfile) { + return inMemoryWorkspaceState.get(key) + } return await context.workspaceState.get(key) } export async function getAllExtensionState(context: vscode.ExtensionContext) { + const firstBatchStart = performance.now() const [ isNewUser, welcomeViewCompleted, apiKey, openRouterApiKey, - clineApiKey, + clineAccountId, awsAccessKey, awsSecretKey, awsSessionToken, @@ -127,14 +185,13 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { sapAiCoreBaseUrl, sapAiCoreTokenUrl, sapAiResourceGroup, - sapAiCoreModelId, claudeCodePath, ] = await Promise.all([ getGlobalState(context, "isNewUser") as Promise, 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, @@ -203,14 +260,15 @@ 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, ]) const localClineRulesToggles = (await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles + const secondBatchStart = performance.now() const [ chatSettings, + currentMode, storedApiProvider, apiModelId, thinkingBudgetTokens, @@ -228,8 +286,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { liteLlmModelInfo, requestyModelId, requestyModelInfo, - shengSuanYunModelId, - shengSuanYunModelInfo, togetherModelId, fireworksModelId, previousModeApiProvider, @@ -240,51 +296,47 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { previousModeReasoningEffort, previousModeAwsBedrockCustomSelected, previousModeAwsBedrockCustomModelBaseId, - previousModeSapAiCoreClientId, - previousModeSapAiCoreClientSecret, - previousModeSapAiCoreBaseUrl, - previousModeSapAiCoreTokenUrl, - previousModeSapAiCoreResourceGroup, previousModeSapAiCoreModelId, + sapAiCoreModelId, + shengSuanYunModelId, + shengSuanYunModelInfo, ] = 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, "shengSuanYunModelId") as Promise, - getWorkspaceState(context, "shengSuanYunModelInfo") 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, "mode") as Promise<"plan" | "act" | undefined>, + 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, + getGlobalState(context, "shengSuanYunModelId") as Promise, + getGlobalState(context, "shengSuanYunModelInfo") as Promise, ]) + const processingStart = performance.now() let apiProvider: ApiProvider if (storedApiProvider) { apiProvider = storedApiProvider @@ -295,7 +347,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { apiProvider = "anthropic" } else { // New users should default to openrouter, since they've opted to use an API key instead of signing in - apiProvider = "openrouter" + apiProvider = "shengsuanyun" } } @@ -327,7 +379,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { apiModelId, apiKey, openRouterApiKey, - clineApiKey, + clineAccountId, claudeCodePath, awsAccessKey, awsSecretKey, @@ -411,7 +463,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, @@ -422,11 +475,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { previousModeReasoningEffort, previousModeAwsBedrockCustomSelected, previousModeAwsBedrockCustomModelBaseId, - previousModeSapAiCoreClientId, - previousModeSapAiCoreClientSecret, - previousModeSapAiCoreBaseUrl, - previousModeSapAiCoreTokenUrl, - previousModeSapAiCoreResourceGroup, previousModeSapAiCoreModelId, mcpMarketplaceEnabled: mcpMarketplaceEnabled, mcpRichDisplayEnabled: mcpRichDisplayEnabled ?? true, @@ -500,7 +548,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a xaiApiKey, thinkingBudgetTokens, reasoningEffort, - clineApiKey, + clineAccountId, sambanovaApiKey, cerebrasApiKey, nebiusApiKey, @@ -521,90 +569,97 @@ 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) - await updateWorkspaceState(context, "shengSuanYunModelId", shengSuanYunModelId) - await updateWorkspaceState(context, "shengSuanYunModelInfo", shengSuanYunModelInfo) - // 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, "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) - await updateGlobalState(context, "shengSuanYunToken", shengSuanYunToken) + // 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, + shengSuanYunModelId, + shengSuanYunModelInfo, - // 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, "shengSuanYunApiKey", shengSuanYunApiKey) - await storeSecret(context, "sapAiCoreClientId", sapAiCoreClientId) - await storeSecret(context, "sapAiCoreClientSecret", sapAiCoreClientSecret) + // 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, + shengSuanYunToken, + } + + // OPTIMIZED: Batch all secret updates into 1 operation instead of 23 + const batchedSecretUpdates = { + apiKey, + openRouterApiKey, + clineAccountId, + awsAccessKey, + awsSecretKey, + awsSessionToken, + openAiApiKey, + geminiApiKey, + openAiNativeApiKey, + deepSeekApiKey, + requestyApiKey, + togetherApiKey, + qwenApiKey, + doubaoApiKey, + mistralApiKey, + liteLlmApiKey, + fireworksApiKey, + asksageApiKey, + xaiApiKey, + sambanovaApiKey, + cerebrasApiKey, + nebiusApiKey, + sapAiCoreClientId, + sapAiCoreClientSecret, + shengSuanYunApiKey, + } + + // Execute batched operations in parallel for maximum performance + await Promise.all([updateGlobalStateBatch(context, batchedGlobalUpdates), updateSecretsBatch(context, batchedSecretUpdates)]) } export async function resetWorkspaceState(context: vscode.ExtensionContext) { @@ -633,7 +688,7 @@ export async function resetGlobalState(context: vscode.ExtensionContext) { "qwenApiKey", "doubaoApiKey", "mistralApiKey", - "clineApiKey", + "clineAccountId", "liteLlmApiKey", "fireworksApiKey", "asksageApiKey", diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index b31b6e18..2a35612c 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 e27afc54..4ba03e1d 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -26,16 +26,15 @@ 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" -import os from "os" 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 +69,7 @@ import { getSavedClineMessages, GlobalFileNames, } from "@core/storage/disk" -import { 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,9 +85,6 @@ 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 - export type ToolResponse = string | Array type UserContent = Array @@ -96,6 +92,7 @@ export class Task { // Core task variables readonly taskId: string private taskIsFavorited?: boolean + private cwd: string taskState: TaskState @@ -152,6 +149,7 @@ export class Task { terminalOutputLineLimit: number, defaultTerminalProfile: string, enableCheckpointsSetting: boolean, + cwd: string, task?: string, images?: string[], files?: string[], @@ -181,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) => { @@ -1097,7 +1096,7 @@ export class Task { const [taskResumptionMessage, userResponseMessage] = formatResponse.taskResumption( this.chatSettings?.mode === "plan" ? "plan" : "act", agoText, - cwd, + this.cwd, wasRecent, responseText, hasPendingFileContextWarnings, @@ -1328,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 }) @@ -1405,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) @@ -1581,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) @@ -1590,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 @@ -1873,7 +1872,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) @@ -2125,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 @@ -2298,6 +2304,13 @@ export class Task { this.api.getModel().id, "assistant", true, + { + tokensIn: inputTokens, + tokensOut: outputTokens, + cacheWriteTokens, + cacheReadTokens, + totalCost, + }, ) await this.messageStateHandler.addToApiConversationHistory({ @@ -2357,7 +2370,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. @@ -2375,7 +2388,7 @@ export class Task { ) { const parsedText = await parseMentions( block.text, - cwd, + this.cwd, this.urlContentFetcher, this.fileContextTracker, ) @@ -2411,7 +2424,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 @@ -2426,7 +2439,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 @@ -2445,7 +2458,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 @@ -2571,19 +2584,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, path.join(os.homedir(), "Desktop")) + 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")}` } 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/core/webview/index.ts b/src/core/webview/index.ts index a5b16fdc..eef249c7 100644 --- a/src/core/webview/index.ts +++ b/src/core/webview/index.ts @@ -197,11 +197,11 @@ export abstract class WebviewProvider { + script-src https://us-assets.i.posthog.com 'nonce-${nonce}' 'unsafe-eval';"> Cline diff --git a/src/extension.ts b/src/extension.ts index 32a2a0cd..ce0f00a2 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, @@ -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" /* @@ -60,9 +61,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 +70,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) @@ -293,23 +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))) { - vscode.window.showErrorMessage("认证状态无效") + 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/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/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/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/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/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") - }) -}) diff --git a/src/integrations/checkpoints/CheckpointUtils.ts b/src/integrations/checkpoints/CheckpointUtils.ts index 96f0456c..0ba23100 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/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index 90fe9caa..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, @@ -77,6 +75,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 +119,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" +function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions, cwd: string) { + const claudePath = path?.trim() || "claude" const args = [ "-p", @@ -129,10 +143,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 +167,7 @@ function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetToken stderr: "pipe", env, cwd, - maxBuffer: 1024 * 1024 * 1000, + maxBuffer: BUFFER_SIZE, timeout: CLAUDE_CODE_TIMEOUT, }) 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/integrations/misc/process-files.ts b/src/integrations/misc/process-files.ts index e6998756..ddb9c7c4 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/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 { diff --git a/src/services/account/ClineAccountService.ts b/src/services/account/ClineAccountService.ts index 66b56085..4007dd05 100644 --- a/src/services/account/ClineAccountService.ts +++ b/src/services/account/ClineAccountService.ts @@ -1,12 +1,43 @@ import axios, { AxiosRequestConfig, AxiosResponse } from "axios" -import type { BalanceResponse, PaymentTransaction, UsageTransaction } from "@shared/ClineAccount" +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 } /** @@ -17,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 + } } /** @@ -48,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) @@ -62,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 @@ -76,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/account/SSYAccountService.ts b/src/services/account/SSYAccountService.ts index a1e966d0..767463b8 100644 --- a/src/services/account/SSYAccountService.ts +++ b/src/services/account/SSYAccountService.ts @@ -43,7 +43,6 @@ export class SSYAccountService { } else { usage = usage.logs.map((it: any) => ({ spentAt: it.request_time, - modelProvider: "", model: `${it.model?.company}/${it.model?.name}`, credits: (rate * it.total_amount) / 10000000, totalTokens: it.total_amount, @@ -57,7 +56,9 @@ export class SSYAccountService { } else { payment = payment.records.map((it: any) => ({ paidAt: it.create_at, + creatorId: "", amountCents: ((rate * it.price) / 10000).toString(), + credits: 0, })) } 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/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( diff --git a/src/services/test/TestServer.ts b/src/services/test/TestServer.ts index 5d99ffe2..1fa9c76c 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,17 +264,17 @@ 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) // 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() diff --git a/src/shared/ChatSettings.ts b/src/shared/ChatSettings.ts index f8a9a721..8134ff6a 100644 --- a/src/shared/ChatSettings.ts +++ b/src/shared/ChatSettings.ts @@ -13,6 +13,6 @@ export type StoredChatSettings = Omit export const DEFAULT_CHAT_SETTINGS: ChatSettings = { mode: "act", - preferredLanguage: "English", + preferredLanguage: "Simplified Chinese - 简体中文", openAIReasoningEffort: "medium", } diff --git a/src/shared/ClineAccount.ts b/src/shared/ClineAccount.ts index 1cc9a288..d40524a9 100644 --- a/src/shared/ClineAccount.ts +++ b/src/shared/ClineAccount.ts @@ -1,16 +1,49 @@ +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 + model?: string + modelProvider?: string + spentAt?: string + credits?: string } export interface PaymentTransaction { @@ -19,3 +52,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 0eae66e3..d7aa4901 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -1,48 +1,16 @@ // 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 } 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 { ClineRulesToggles } from "./cline-rules" // webview will hold state export interface ExtensionMessage { - type: "action" | "state" | "selectedImages" | "mcpDownloadDetails" | "grpc_response" - 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/src/shared/Languages.ts b/src/shared/Languages.ts index 8b933ccc..06a08426 100644 --- a/src/shared/Languages.ts +++ b/src/shared/Languages.ts @@ -38,7 +38,7 @@ export type LanguageDisplay = | "Traditional Chinese - 繁體中文" | "Turkish - Türkçe" -export const DEFAULT_LANGUAGE_SETTINGS: LanguageKey = "en" +export const DEFAULT_LANGUAGE_SETTINGS: LanguageKey = "zh-CN" export const languageOptions: { key: LanguageKey; display: LanguageDisplay }[] = [ { key: "en", display: "English" }, 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 a16a288e..d18eaf34 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -1,4 +1,5 @@ import type { LanguageModelChatSelector } from "../api/providers/types" +import { ShengSuanYunModelInfo } from "./proto/models" export type ApiProvider = | "anthropic" @@ -32,7 +33,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 @@ -99,7 +100,7 @@ export interface ApiHandlerOptions { shengSuanYunApiKey?: string shengSuanYunToken?: string shengSuanYunModelId?: string - shengSuanYunModelInfo?: ModelInfo + shengSuanYunModelInfo?: ShengSuanYunModelInfo sapAiCoreClientId?: string sapAiCoreClientSecret?: string sapAiResourceGroup?: string @@ -2378,7 +2379,7 @@ export const requestyDefaultModelInfo: ModelInfo = { // ShengSuanYun // https://router.shengsuanyun.com/model export const shengSuanYunDefaultModelId: string = "anthropic/claude-sonnet-4" -export const shengSuanYunDefaultModelInfo: ModelInfo = { +export const shengSuanYunDefaultModelInfo: ShengSuanYunModelInfo = { maxTokens: 64_000, contextWindow: 200_000, supportsImages: true, @@ -2449,21 +2450,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, @@ -2473,7 +2494,7 @@ export const sapAiCoreModels = { inputPrice: 3.0, outputPrice: 15.0, }, - o1: { + "gpt-4o": { maxTokens: 4096, contextWindow: 200_000, supportsImages: true, @@ -2481,7 +2502,7 @@ export const sapAiCoreModels = { inputPrice: 3.0, outputPrice: 15.0, }, - "o3-mini": { + "gpt-4o-mini": { maxTokens: 4096, contextWindow: 200_000, supportsImages: true, @@ -2507,6 +2528,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, @@ -2516,6 +2545,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, diff --git a/src/shared/proto-conversions/models/api-configuration-conversion.ts b/src/shared/proto-conversions/models/api-configuration-conversion.ts index 70b7119b..da248e6b 100644 --- a/src/shared/proto-conversions/models/api-configuration-conversion.ts +++ b/src/shared/proto-conversions/models/api-configuration-conversion.ts @@ -14,6 +14,7 @@ import { OpenRouterModelInfo, ThinkingConfig, ShengSuanYunModelInfo, + PriceTier, } from "../../proto/models" // Convert application ThinkingConfig to proto ThinkingConfig @@ -30,16 +31,19 @@ function convertThinkingConfigToProto(config: ModelInfo["thinkingConfig"]): Thin } // Convert proto ThinkingConfig to application ThinkingConfig -function convertProtoToThinkingConfig(config: ThinkingConfig | undefined): ModelInfo["thinkingConfig"] | undefined { +function convertProtoToThinkingConfig(config: ThinkingConfig | undefined): ThinkingConfig | undefined { if (!config) { return undefined } + // Explicitly ensure outputPriceTiers is always a non-undefined array + const outputPriceTiers: PriceTier[] = Array.isArray(config.outputPriceTiers) ? config.outputPriceTiers : [] + return { maxBudget: config.maxBudget, outputPrice: config.outputPrice, - outputPriceTiers: config.outputPriceTiers.length > 0 ? config.outputPriceTiers : undefined, - } + outputPriceTiers, + } as ThinkingConfig } // Convert application ModelInfo to proto OpenRouterModelInfo @@ -87,7 +91,7 @@ function convertProtoToModelInfo(info: OpenRouterModelInfo | undefined): ModelIn } // Convert application ModelInfo to proto ShengSuanYunModelInfo -function convertModelInfoToProtoShengSuanYun(info: ModelInfo | undefined): ShengSuanYunModelInfo | undefined { +function convertModelInfoToProtoShengSuanYun(info: ShengSuanYunModelInfo | undefined): ShengSuanYunModelInfo | undefined { if (!info) { return undefined } @@ -107,7 +111,7 @@ function convertModelInfoToProtoShengSuanYun(info: ModelInfo | undefined): Sheng } // Convert proto ShengSuanYunModelInfo to application ModelInfo -function convertProtoToShengSuanYunModelInfo(info: ShengSuanYunModelInfo | undefined): ModelInfo | undefined { +function convertProtoToShengSuanYunModelInfo(info: ShengSuanYunModelInfo | undefined): ShengSuanYunModelInfo | undefined { if (!info) { return undefined } @@ -283,7 +287,7 @@ function convertApiProviderToProto(provider: string | undefined): ProtoApiProvid case "shengsuanyun": return ProtoApiProvider.SHENG_SUAN_YUN default: - return ProtoApiProvider.ANTHROPIC + return ProtoApiProvider.SHENG_SUAN_YUN } } @@ -345,7 +349,7 @@ function convertProtoToApiProvider(provider: ProtoApiProvider): ApiProvider { case ProtoApiProvider.SHENG_SUAN_YUN: return "shengsuanyun" default: - return "anthropic" + return "shengsuanyun" } } @@ -354,7 +358,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, @@ -424,6 +428,7 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA sapAiResourceGroup: config.sapAiResourceGroup, sapAiCoreTokenUrl: config.sapAiCoreTokenUrl, sapAiCoreBaseUrl: config.sapAiCoreBaseUrl, + sapAiCoreModelId: config.sapAiCoreModelId, claudeCodePath: config.claudeCodePath, shengSuanYunToken: config.shengSuanYunToken, shengSuanYunApiKey: config.shengSuanYunApiKey, @@ -437,7 +442,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, @@ -507,6 +512,7 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio sapAiResourceGroup: protoConfig.sapAiResourceGroup, sapAiCoreTokenUrl: protoConfig.sapAiCoreTokenUrl, sapAiCoreBaseUrl: protoConfig.sapAiCoreBaseUrl, + sapAiCoreModelId: protoConfig.sapAiCoreModelId, claudeCodePath: protoConfig.claudeCodePath, shengSuanYunToken: protoConfig.shengSuanYunToken, shengSuanYunApiKey: protoConfig.shengSuanYunApiKey, diff --git a/src/shared/proto-conversions/state/settings-conversion.ts b/src/shared/proto-conversions/state/settings-conversion.ts index 45a0080f..1a8402d5 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, @@ -143,7 +143,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/shared/proto/account.ts b/src/shared/proto/account.ts index 529b3c71..2db7e427 100644 --- a/src/shared/proto/account.ts +++ b/src/shared/proto/account.ts @@ -13,41 +13,73 @@ export interface AuthStateChangedRequest { user?: UserInfo | undefined; } -export interface AuthStateChanged { +export interface AuthState { user?: UserInfo | undefined; } +/** User's information */ export interface UserInfo { + uid: string; displayName?: string | undefined; email?: string | undefined; photoUrl?: string | undefined; } -/** Response containing all user credits data */ +export interface UserOrganization { + active: boolean; + memberId: string; + name: string; + organizationId: string; + /** ["admin", "member", "owner"] */ + roles: string[]; +} + +export interface UserOrganizationsResponse { + organizations: UserOrganization[]; +} + +export interface UserOrganizationUpdateRequest { + organizationId?: string | undefined; +} + export interface UserCreditsData { balance?: UserCreditsBalance | undefined; usageTransactions: UsageTransaction[]; paymentTransactions: PaymentTransaction[]; } -/** User's current credit balance */ +export interface GetOrganizationCreditsRequest { + organizationId: string; +} + +export interface OrganizationCreditsData { + balance?: UserCreditsBalance | undefined; + organizationId: string; + usageTransactions: OrganizationUsageTransaction[]; +} + export interface UserCreditsBalance { currentBalance: number; } -/** Usage transaction record */ 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; + organizationId: string; + promptTokens: number; totalTokens: number; + userId: string; + spentAt?: string | undefined; + model?: string | undefined; + credits?: string | undefined; } -/** Payment transaction record */ export interface PaymentTransaction { paidAt: string; creatorId: string; @@ -55,6 +87,21 @@ export interface PaymentTransaction { credits: number; } +export interface OrganizationUsageTransaction { + aiInferenceProviderName: string; + aiModelName: string; + aiModelTypeName: string; + completionTokens: number; + costUsd: number; + createdAt: string; + creditsUsed: number; + generationId: string; + organizationId: string; + promptTokens: number; + totalTokens: number; + userId: string; +} + function createBaseAuthStateChangedRequest(): AuthStateChangedRequest { return { metadata: undefined, user: undefined }; } @@ -133,22 +180,22 @@ export const AuthStateChangedRequest: MessageFns = { }, }; -function createBaseAuthStateChanged(): AuthStateChanged { +function createBaseAuthState(): AuthState { return { user: undefined }; } -export const AuthStateChanged: MessageFns = { - encode(message: AuthStateChanged, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { +export const AuthState: MessageFns = { + encode(message: AuthState, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { if (message.user !== undefined) { UserInfo.encode(message.user, writer.uint32(10).fork()).join(); } return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): AuthStateChanged { + decode(input: BinaryReader | Uint8Array, length?: number): AuthState { const reader = input instanceof BinaryReader ? input : new BinaryReader(input); const end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseAuthStateChanged(); + const message = createBaseAuthState(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { @@ -169,11 +216,11 @@ export const AuthStateChanged: MessageFns = { return message; }, - fromJSON(object: any): AuthStateChanged { + fromJSON(object: any): AuthState { return { user: isSet(object.user) ? UserInfo.fromJSON(object.user) : undefined }; }, - toJSON(message: AuthStateChanged): unknown { + toJSON(message: AuthState): unknown { const obj: any = {}; if (message.user !== undefined) { obj.user = UserInfo.toJSON(message.user); @@ -181,30 +228,33 @@ export const AuthStateChanged: MessageFns = { return obj; }, - create, I>>(base?: I): AuthStateChanged { - return AuthStateChanged.fromPartial(base ?? ({} as any)); + create, I>>(base?: I): AuthState { + return AuthState.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): AuthStateChanged { - const message = createBaseAuthStateChanged(); + fromPartial, I>>(object: I): AuthState { + const message = createBaseAuthState(); message.user = (object.user !== undefined && object.user !== null) ? UserInfo.fromPartial(object.user) : undefined; return message; }, }; function createBaseUserInfo(): UserInfo { - return { displayName: undefined, email: undefined, photoUrl: undefined }; + return { uid: "", displayName: undefined, email: undefined, photoUrl: undefined }; } export const UserInfo: MessageFns = { encode(message: UserInfo, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.uid !== "") { + writer.uint32(10).string(message.uid); + } if (message.displayName !== undefined) { - writer.uint32(10).string(message.displayName); + writer.uint32(18).string(message.displayName); } if (message.email !== undefined) { - writer.uint32(18).string(message.email); + writer.uint32(26).string(message.email); } if (message.photoUrl !== undefined) { - writer.uint32(26).string(message.photoUrl); + writer.uint32(34).string(message.photoUrl); } return writer; }, @@ -221,7 +271,7 @@ export const UserInfo: MessageFns = { break; } - message.displayName = reader.string(); + message.uid = reader.string(); continue; } case 2: { @@ -229,7 +279,7 @@ export const UserInfo: MessageFns = { break; } - message.email = reader.string(); + message.displayName = reader.string(); continue; } case 3: { @@ -237,6 +287,14 @@ export const UserInfo: MessageFns = { break; } + message.email = reader.string(); + continue; + } + case 4: { + if (tag !== 34) { + break; + } + message.photoUrl = reader.string(); continue; } @@ -251,6 +309,7 @@ export const UserInfo: MessageFns = { fromJSON(object: any): UserInfo { return { + uid: isSet(object.uid) ? globalThis.String(object.uid) : "", displayName: isSet(object.displayName) ? globalThis.String(object.displayName) : undefined, email: isSet(object.email) ? globalThis.String(object.email) : undefined, photoUrl: isSet(object.photoUrl) ? globalThis.String(object.photoUrl) : undefined, @@ -259,6 +318,9 @@ export const UserInfo: MessageFns = { toJSON(message: UserInfo): unknown { const obj: any = {}; + if (message.uid !== "") { + obj.uid = message.uid; + } if (message.displayName !== undefined) { obj.displayName = message.displayName; } @@ -276,6 +338,7 @@ export const UserInfo: MessageFns = { }, fromPartial, I>>(object: I): UserInfo { const message = createBaseUserInfo(); + message.uid = object.uid ?? ""; message.displayName = object.displayName ?? undefined; message.email = object.email ?? undefined; message.photoUrl = object.photoUrl ?? undefined; @@ -283,6 +346,252 @@ export const UserInfo: MessageFns = { }, }; +function createBaseUserOrganization(): UserOrganization { + return { active: false, memberId: "", name: "", organizationId: "", roles: [] }; +} + +export const UserOrganization: MessageFns = { + encode(message: UserOrganization, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.active !== false) { + writer.uint32(8).bool(message.active); + } + if (message.memberId !== "") { + writer.uint32(18).string(message.memberId); + } + if (message.name !== "") { + writer.uint32(26).string(message.name); + } + if (message.organizationId !== "") { + writer.uint32(34).string(message.organizationId); + } + for (const v of message.roles) { + writer.uint32(42).string(v!); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): UserOrganization { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseUserOrganization(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 8) { + break; + } + + message.active = reader.bool(); + continue; + } + case 2: { + if (tag !== 18) { + break; + } + + message.memberId = reader.string(); + continue; + } + case 3: { + if (tag !== 26) { + break; + } + + message.name = reader.string(); + continue; + } + case 4: { + if (tag !== 34) { + break; + } + + message.organizationId = reader.string(); + continue; + } + case 5: { + if (tag !== 42) { + break; + } + + message.roles.push(reader.string()); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): UserOrganization { + return { + active: isSet(object.active) ? globalThis.Boolean(object.active) : false, + memberId: isSet(object.memberId) ? globalThis.String(object.memberId) : "", + name: isSet(object.name) ? globalThis.String(object.name) : "", + organizationId: isSet(object.organizationId) ? globalThis.String(object.organizationId) : "", + roles: globalThis.Array.isArray(object?.roles) ? object.roles.map((e: any) => globalThis.String(e)) : [], + }; + }, + + toJSON(message: UserOrganization): unknown { + const obj: any = {}; + if (message.active !== false) { + obj.active = message.active; + } + if (message.memberId !== "") { + obj.memberId = message.memberId; + } + if (message.name !== "") { + obj.name = message.name; + } + if (message.organizationId !== "") { + obj.organizationId = message.organizationId; + } + if (message.roles?.length) { + obj.roles = message.roles; + } + return obj; + }, + + create, I>>(base?: I): UserOrganization { + return UserOrganization.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>(object: I): UserOrganization { + const message = createBaseUserOrganization(); + message.active = object.active ?? false; + message.memberId = object.memberId ?? ""; + message.name = object.name ?? ""; + message.organizationId = object.organizationId ?? ""; + message.roles = object.roles?.map((e) => e) || []; + return message; + }, +}; + +function createBaseUserOrganizationsResponse(): UserOrganizationsResponse { + return { organizations: [] }; +} + +export const UserOrganizationsResponse: MessageFns = { + encode(message: UserOrganizationsResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + for (const v of message.organizations) { + UserOrganization.encode(v!, writer.uint32(10).fork()).join(); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): UserOrganizationsResponse { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseUserOrganizationsResponse(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 10) { + break; + } + + message.organizations.push(UserOrganization.decode(reader, reader.uint32())); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): UserOrganizationsResponse { + return { + organizations: globalThis.Array.isArray(object?.organizations) + ? object.organizations.map((e: any) => UserOrganization.fromJSON(e)) + : [], + }; + }, + + toJSON(message: UserOrganizationsResponse): unknown { + const obj: any = {}; + if (message.organizations?.length) { + obj.organizations = message.organizations.map((e) => UserOrganization.toJSON(e)); + } + return obj; + }, + + create, I>>(base?: I): UserOrganizationsResponse { + return UserOrganizationsResponse.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>(object: I): UserOrganizationsResponse { + const message = createBaseUserOrganizationsResponse(); + message.organizations = object.organizations?.map((e) => UserOrganization.fromPartial(e)) || []; + return message; + }, +}; + +function createBaseUserOrganizationUpdateRequest(): UserOrganizationUpdateRequest { + return { organizationId: undefined }; +} + +export const UserOrganizationUpdateRequest: MessageFns = { + encode(message: UserOrganizationUpdateRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.organizationId !== undefined) { + writer.uint32(10).string(message.organizationId); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): UserOrganizationUpdateRequest { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseUserOrganizationUpdateRequest(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 10) { + break; + } + + message.organizationId = reader.string(); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): UserOrganizationUpdateRequest { + return { organizationId: isSet(object.organizationId) ? globalThis.String(object.organizationId) : undefined }; + }, + + toJSON(message: UserOrganizationUpdateRequest): unknown { + const obj: any = {}; + if (message.organizationId !== undefined) { + obj.organizationId = message.organizationId; + } + return obj; + }, + + create, I>>(base?: I): UserOrganizationUpdateRequest { + return UserOrganizationUpdateRequest.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>( + object: I, + ): UserOrganizationUpdateRequest { + const message = createBaseUserOrganizationUpdateRequest(); + message.organizationId = object.organizationId ?? undefined; + return message; + }, +}; + function createBaseUserCreditsData(): UserCreditsData { return { balance: undefined, usageTransactions: [], paymentTransactions: [] }; } @@ -381,6 +690,162 @@ export const UserCreditsData: MessageFns = { }, }; +function createBaseGetOrganizationCreditsRequest(): GetOrganizationCreditsRequest { + return { organizationId: "" }; +} + +export const GetOrganizationCreditsRequest: MessageFns = { + encode(message: GetOrganizationCreditsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.organizationId !== "") { + writer.uint32(10).string(message.organizationId); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): GetOrganizationCreditsRequest { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseGetOrganizationCreditsRequest(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 10) { + break; + } + + message.organizationId = reader.string(); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): GetOrganizationCreditsRequest { + return { organizationId: isSet(object.organizationId) ? globalThis.String(object.organizationId) : "" }; + }, + + toJSON(message: GetOrganizationCreditsRequest): unknown { + const obj: any = {}; + if (message.organizationId !== "") { + obj.organizationId = message.organizationId; + } + return obj; + }, + + create, I>>(base?: I): GetOrganizationCreditsRequest { + return GetOrganizationCreditsRequest.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>( + object: I, + ): GetOrganizationCreditsRequest { + const message = createBaseGetOrganizationCreditsRequest(); + message.organizationId = object.organizationId ?? ""; + return message; + }, +}; + +function createBaseOrganizationCreditsData(): OrganizationCreditsData { + return { balance: undefined, organizationId: "", usageTransactions: [] }; +} + +export const OrganizationCreditsData: MessageFns = { + encode(message: OrganizationCreditsData, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.balance !== undefined) { + UserCreditsBalance.encode(message.balance, writer.uint32(10).fork()).join(); + } + if (message.organizationId !== "") { + writer.uint32(18).string(message.organizationId); + } + for (const v of message.usageTransactions) { + OrganizationUsageTransaction.encode(v!, writer.uint32(26).fork()).join(); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): OrganizationCreditsData { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseOrganizationCreditsData(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 10) { + break; + } + + message.balance = UserCreditsBalance.decode(reader, reader.uint32()); + continue; + } + case 2: { + if (tag !== 18) { + break; + } + + message.organizationId = reader.string(); + continue; + } + case 3: { + if (tag !== 26) { + break; + } + + message.usageTransactions.push(OrganizationUsageTransaction.decode(reader, reader.uint32())); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): OrganizationCreditsData { + return { + balance: isSet(object.balance) ? UserCreditsBalance.fromJSON(object.balance) : undefined, + organizationId: isSet(object.organizationId) ? globalThis.String(object.organizationId) : "", + usageTransactions: globalThis.Array.isArray(object?.usageTransactions) + ? object.usageTransactions.map((e: any) => OrganizationUsageTransaction.fromJSON(e)) + : [], + }; + }, + + toJSON(message: OrganizationCreditsData): unknown { + const obj: any = {}; + if (message.balance !== undefined) { + obj.balance = UserCreditsBalance.toJSON(message.balance); + } + if (message.organizationId !== "") { + obj.organizationId = message.organizationId; + } + if (message.usageTransactions?.length) { + obj.usageTransactions = message.usageTransactions.map((e) => OrganizationUsageTransaction.toJSON(e)); + } + return obj; + }, + + create, I>>(base?: I): OrganizationCreditsData { + return OrganizationCreditsData.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>(object: I): OrganizationCreditsData { + const message = createBaseOrganizationCreditsData(); + message.balance = (object.balance !== undefined && object.balance !== null) + ? UserCreditsBalance.fromPartial(object.balance) + : undefined; + message.organizationId = object.organizationId ?? ""; + message.usageTransactions = object.usageTransactions?.map((e) => OrganizationUsageTransaction.fromPartial(e)) || []; + return message; + }, +}; + function createBaseUserCreditsBalance(): UserCreditsBalance { return { currentBalance: 0 }; } @@ -441,42 +906,70 @@ export const UserCreditsBalance: MessageFns = { function createBaseUsageTransaction(): UsageTransaction { return { - spentAt: "", - creatorId: "", - credits: 0, - modelProvider: "", - model: "", - promptTokens: 0, + aiInferenceProviderName: "", + aiModelName: "", + aiModelTypeName: "", completionTokens: 0, + costUsd: 0, + createdAt: "", + creditsUsed: 0, + generationId: "", + organizationId: "", + promptTokens: 0, totalTokens: 0, + userId: "", + spentAt: undefined, + model: undefined, + credits: undefined, }; } export const UsageTransaction: MessageFns = { encode(message: UsageTransaction, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.spentAt !== "") { - writer.uint32(10).string(message.spentAt); + if (message.aiInferenceProviderName !== "") { + writer.uint32(10).string(message.aiInferenceProviderName); } - if (message.creatorId !== "") { - writer.uint32(18).string(message.creatorId); + if (message.aiModelName !== "") { + writer.uint32(18).string(message.aiModelName); } - if (message.credits !== 0) { - writer.uint32(25).double(message.credits); - } - if (message.modelProvider !== "") { - writer.uint32(34).string(message.modelProvider); - } - if (message.model !== "") { - writer.uint32(42).string(message.model); - } - if (message.promptTokens !== 0) { - writer.uint32(48).int32(message.promptTokens); + if (message.aiModelTypeName !== "") { + writer.uint32(26).string(message.aiModelTypeName); } if (message.completionTokens !== 0) { - writer.uint32(56).int32(message.completionTokens); + writer.uint32(32).int32(message.completionTokens); + } + if (message.costUsd !== 0) { + writer.uint32(41).double(message.costUsd); + } + if (message.createdAt !== "") { + writer.uint32(50).string(message.createdAt); + } + if (message.creditsUsed !== 0) { + writer.uint32(57).double(message.creditsUsed); + } + if (message.generationId !== "") { + writer.uint32(66).string(message.generationId); + } + if (message.organizationId !== "") { + writer.uint32(74).string(message.organizationId); + } + if (message.promptTokens !== 0) { + writer.uint32(80).int32(message.promptTokens); } if (message.totalTokens !== 0) { - writer.uint32(64).int32(message.totalTokens); + writer.uint32(88).int32(message.totalTokens); + } + if (message.userId !== "") { + writer.uint32(98).string(message.userId); + } + if (message.spentAt !== undefined) { + writer.uint32(106).string(message.spentAt); + } + if (message.model !== undefined) { + writer.uint32(114).string(message.model); + } + if (message.credits !== undefined) { + writer.uint32(122).string(message.credits); } return writer; }, @@ -493,7 +986,7 @@ export const UsageTransaction: MessageFns = { break; } - message.spentAt = reader.string(); + message.aiInferenceProviderName = reader.string(); continue; } case 2: { @@ -501,57 +994,113 @@ export const UsageTransaction: MessageFns = { break; } - message.creatorId = reader.string(); + message.aiModelName = reader.string(); continue; } case 3: { - if (tag !== 25) { + if (tag !== 26) { break; } - message.credits = reader.double(); + message.aiModelTypeName = reader.string(); continue; } case 4: { - if (tag !== 34) { - break; - } - - message.modelProvider = reader.string(); - continue; - } - case 5: { - if (tag !== 42) { - break; - } - - message.model = reader.string(); - continue; - } - case 6: { - if (tag !== 48) { - break; - } - - message.promptTokens = reader.int32(); - continue; - } - case 7: { - if (tag !== 56) { + if (tag !== 32) { break; } message.completionTokens = reader.int32(); continue; } + case 5: { + if (tag !== 41) { + break; + } + + message.costUsd = reader.double(); + continue; + } + case 6: { + if (tag !== 50) { + break; + } + + message.createdAt = reader.string(); + continue; + } + case 7: { + if (tag !== 57) { + break; + } + + message.creditsUsed = reader.double(); + continue; + } case 8: { - if (tag !== 64) { + if (tag !== 66) { + break; + } + + message.generationId = reader.string(); + continue; + } + case 9: { + if (tag !== 74) { + break; + } + + message.organizationId = reader.string(); + continue; + } + case 10: { + if (tag !== 80) { + break; + } + + message.promptTokens = reader.int32(); + continue; + } + case 11: { + if (tag !== 88) { break; } message.totalTokens = reader.int32(); continue; } + case 12: { + if (tag !== 98) { + break; + } + + message.userId = reader.string(); + continue; + } + case 13: { + if (tag !== 106) { + break; + } + + message.spentAt = reader.string(); + continue; + } + case 14: { + if (tag !== 114) { + break; + } + + message.model = reader.string(); + continue; + } + case 15: { + if (tag !== 122) { + break; + } + + message.credits = reader.string(); + continue; + } } if ((tag & 7) === 4 || tag === 0) { break; @@ -563,43 +1112,73 @@ export const UsageTransaction: MessageFns = { fromJSON(object: any): UsageTransaction { return { - spentAt: isSet(object.spentAt) ? globalThis.String(object.spentAt) : "", - creatorId: isSet(object.creatorId) ? globalThis.String(object.creatorId) : "", - credits: isSet(object.credits) ? globalThis.Number(object.credits) : 0, - modelProvider: isSet(object.modelProvider) ? globalThis.String(object.modelProvider) : "", - model: isSet(object.model) ? globalThis.String(object.model) : "", - promptTokens: isSet(object.promptTokens) ? globalThis.Number(object.promptTokens) : 0, + aiInferenceProviderName: isSet(object.aiInferenceProviderName) + ? globalThis.String(object.aiInferenceProviderName) + : "", + aiModelName: isSet(object.aiModelName) ? globalThis.String(object.aiModelName) : "", + aiModelTypeName: isSet(object.aiModelTypeName) ? globalThis.String(object.aiModelTypeName) : "", completionTokens: isSet(object.completionTokens) ? globalThis.Number(object.completionTokens) : 0, + costUsd: isSet(object.costUsd) ? globalThis.Number(object.costUsd) : 0, + createdAt: isSet(object.createdAt) ? globalThis.String(object.createdAt) : "", + creditsUsed: isSet(object.creditsUsed) ? globalThis.Number(object.creditsUsed) : 0, + generationId: isSet(object.generationId) ? globalThis.String(object.generationId) : "", + organizationId: isSet(object.organizationId) ? globalThis.String(object.organizationId) : "", + promptTokens: isSet(object.promptTokens) ? globalThis.Number(object.promptTokens) : 0, totalTokens: isSet(object.totalTokens) ? globalThis.Number(object.totalTokens) : 0, + userId: isSet(object.userId) ? globalThis.String(object.userId) : "", + spentAt: isSet(object.spentAt) ? globalThis.String(object.spentAt) : undefined, + model: isSet(object.model) ? globalThis.String(object.model) : undefined, + credits: isSet(object.credits) ? globalThis.String(object.credits) : undefined, }; }, toJSON(message: UsageTransaction): unknown { const obj: any = {}; - if (message.spentAt !== "") { - obj.spentAt = message.spentAt; + if (message.aiInferenceProviderName !== "") { + obj.aiInferenceProviderName = message.aiInferenceProviderName; } - if (message.creatorId !== "") { - obj.creatorId = message.creatorId; + if (message.aiModelName !== "") { + obj.aiModelName = message.aiModelName; } - if (message.credits !== 0) { - obj.credits = message.credits; - } - if (message.modelProvider !== "") { - obj.modelProvider = message.modelProvider; - } - if (message.model !== "") { - obj.model = message.model; - } - if (message.promptTokens !== 0) { - obj.promptTokens = Math.round(message.promptTokens); + if (message.aiModelTypeName !== "") { + obj.aiModelTypeName = message.aiModelTypeName; } if (message.completionTokens !== 0) { obj.completionTokens = Math.round(message.completionTokens); } + if (message.costUsd !== 0) { + obj.costUsd = message.costUsd; + } + if (message.createdAt !== "") { + obj.createdAt = message.createdAt; + } + if (message.creditsUsed !== 0) { + obj.creditsUsed = message.creditsUsed; + } + if (message.generationId !== "") { + obj.generationId = message.generationId; + } + if (message.organizationId !== "") { + obj.organizationId = message.organizationId; + } + if (message.promptTokens !== 0) { + obj.promptTokens = Math.round(message.promptTokens); + } if (message.totalTokens !== 0) { obj.totalTokens = Math.round(message.totalTokens); } + if (message.userId !== "") { + obj.userId = message.userId; + } + if (message.spentAt !== undefined) { + obj.spentAt = message.spentAt; + } + if (message.model !== undefined) { + obj.model = message.model; + } + if (message.credits !== undefined) { + obj.credits = message.credits; + } return obj; }, @@ -608,14 +1187,21 @@ export const UsageTransaction: MessageFns = { }, fromPartial, I>>(object: I): UsageTransaction { const message = createBaseUsageTransaction(); - message.spentAt = object.spentAt ?? ""; - message.creatorId = object.creatorId ?? ""; - message.credits = object.credits ?? 0; - message.modelProvider = object.modelProvider ?? ""; - message.model = object.model ?? ""; - message.promptTokens = object.promptTokens ?? 0; + message.aiInferenceProviderName = object.aiInferenceProviderName ?? ""; + message.aiModelName = object.aiModelName ?? ""; + message.aiModelTypeName = object.aiModelTypeName ?? ""; message.completionTokens = object.completionTokens ?? 0; + message.costUsd = object.costUsd ?? 0; + message.createdAt = object.createdAt ?? ""; + message.creditsUsed = object.creditsUsed ?? 0; + message.generationId = object.generationId ?? ""; + message.organizationId = object.organizationId ?? ""; + message.promptTokens = object.promptTokens ?? 0; message.totalTokens = object.totalTokens ?? 0; + message.userId = object.userId ?? ""; + message.spentAt = object.spentAt ?? undefined; + message.model = object.model ?? undefined; + message.credits = object.credits ?? undefined; return message; }, }; @@ -728,6 +1314,257 @@ export const PaymentTransaction: MessageFns = { }, }; +function createBaseOrganizationUsageTransaction(): OrganizationUsageTransaction { + return { + aiInferenceProviderName: "", + aiModelName: "", + aiModelTypeName: "", + completionTokens: 0, + costUsd: 0, + createdAt: "", + creditsUsed: 0, + generationId: "", + organizationId: "", + promptTokens: 0, + totalTokens: 0, + userId: "", + }; +} + +export const OrganizationUsageTransaction: MessageFns = { + encode(message: OrganizationUsageTransaction, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.aiInferenceProviderName !== "") { + writer.uint32(10).string(message.aiInferenceProviderName); + } + if (message.aiModelName !== "") { + writer.uint32(18).string(message.aiModelName); + } + if (message.aiModelTypeName !== "") { + writer.uint32(26).string(message.aiModelTypeName); + } + if (message.completionTokens !== 0) { + writer.uint32(32).int32(message.completionTokens); + } + if (message.costUsd !== 0) { + writer.uint32(41).double(message.costUsd); + } + if (message.createdAt !== "") { + writer.uint32(50).string(message.createdAt); + } + if (message.creditsUsed !== 0) { + writer.uint32(57).double(message.creditsUsed); + } + if (message.generationId !== "") { + writer.uint32(66).string(message.generationId); + } + if (message.organizationId !== "") { + writer.uint32(74).string(message.organizationId); + } + if (message.promptTokens !== 0) { + writer.uint32(80).int32(message.promptTokens); + } + if (message.totalTokens !== 0) { + writer.uint32(88).int32(message.totalTokens); + } + if (message.userId !== "") { + writer.uint32(98).string(message.userId); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): OrganizationUsageTransaction { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseOrganizationUsageTransaction(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 10) { + break; + } + + message.aiInferenceProviderName = reader.string(); + continue; + } + case 2: { + if (tag !== 18) { + break; + } + + message.aiModelName = reader.string(); + continue; + } + case 3: { + if (tag !== 26) { + break; + } + + message.aiModelTypeName = reader.string(); + continue; + } + case 4: { + if (tag !== 32) { + break; + } + + message.completionTokens = reader.int32(); + continue; + } + case 5: { + if (tag !== 41) { + break; + } + + message.costUsd = reader.double(); + continue; + } + case 6: { + if (tag !== 50) { + break; + } + + message.createdAt = reader.string(); + continue; + } + case 7: { + if (tag !== 57) { + break; + } + + message.creditsUsed = reader.double(); + continue; + } + case 8: { + if (tag !== 66) { + break; + } + + message.generationId = reader.string(); + continue; + } + case 9: { + if (tag !== 74) { + break; + } + + message.organizationId = reader.string(); + continue; + } + case 10: { + if (tag !== 80) { + break; + } + + message.promptTokens = reader.int32(); + continue; + } + case 11: { + if (tag !== 88) { + break; + } + + message.totalTokens = reader.int32(); + continue; + } + case 12: { + if (tag !== 98) { + break; + } + + message.userId = reader.string(); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): OrganizationUsageTransaction { + return { + aiInferenceProviderName: isSet(object.aiInferenceProviderName) + ? globalThis.String(object.aiInferenceProviderName) + : "", + aiModelName: isSet(object.aiModelName) ? globalThis.String(object.aiModelName) : "", + aiModelTypeName: isSet(object.aiModelTypeName) ? globalThis.String(object.aiModelTypeName) : "", + completionTokens: isSet(object.completionTokens) ? globalThis.Number(object.completionTokens) : 0, + costUsd: isSet(object.costUsd) ? globalThis.Number(object.costUsd) : 0, + createdAt: isSet(object.createdAt) ? globalThis.String(object.createdAt) : "", + creditsUsed: isSet(object.creditsUsed) ? globalThis.Number(object.creditsUsed) : 0, + generationId: isSet(object.generationId) ? globalThis.String(object.generationId) : "", + organizationId: isSet(object.organizationId) ? globalThis.String(object.organizationId) : "", + promptTokens: isSet(object.promptTokens) ? globalThis.Number(object.promptTokens) : 0, + totalTokens: isSet(object.totalTokens) ? globalThis.Number(object.totalTokens) : 0, + userId: isSet(object.userId) ? globalThis.String(object.userId) : "", + }; + }, + + toJSON(message: OrganizationUsageTransaction): unknown { + const obj: any = {}; + if (message.aiInferenceProviderName !== "") { + obj.aiInferenceProviderName = message.aiInferenceProviderName; + } + if (message.aiModelName !== "") { + obj.aiModelName = message.aiModelName; + } + if (message.aiModelTypeName !== "") { + obj.aiModelTypeName = message.aiModelTypeName; + } + if (message.completionTokens !== 0) { + obj.completionTokens = Math.round(message.completionTokens); + } + if (message.costUsd !== 0) { + obj.costUsd = message.costUsd; + } + if (message.createdAt !== "") { + obj.createdAt = message.createdAt; + } + if (message.creditsUsed !== 0) { + obj.creditsUsed = message.creditsUsed; + } + if (message.generationId !== "") { + obj.generationId = message.generationId; + } + if (message.organizationId !== "") { + obj.organizationId = message.organizationId; + } + if (message.promptTokens !== 0) { + obj.promptTokens = Math.round(message.promptTokens); + } + if (message.totalTokens !== 0) { + obj.totalTokens = Math.round(message.totalTokens); + } + if (message.userId !== "") { + obj.userId = message.userId; + } + return obj; + }, + + create, I>>(base?: I): OrganizationUsageTransaction { + return OrganizationUsageTransaction.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>(object: I): OrganizationUsageTransaction { + const message = createBaseOrganizationUsageTransaction(); + message.aiInferenceProviderName = object.aiInferenceProviderName ?? ""; + message.aiModelName = object.aiModelName ?? ""; + message.aiModelTypeName = object.aiModelTypeName ?? ""; + message.completionTokens = object.completionTokens ?? 0; + message.costUsd = object.costUsd ?? 0; + message.createdAt = object.createdAt ?? ""; + message.creditsUsed = object.creditsUsed ?? 0; + message.generationId = object.generationId ?? ""; + message.organizationId = object.organizationId ?? ""; + message.promptTokens = object.promptTokens ?? 0; + message.totalTokens = object.totalTokens ?? 0; + message.userId = object.userId ?? ""; + return message; + }, +}; + /** Service for account-related operations */ export type AccountServiceDefinition = typeof AccountServiceDefinition; export const AccountServiceDefinition = { @@ -759,12 +1596,12 @@ export const AccountServiceDefinition = { responseStream: false, options: {}, }, - /** Subscribe to auth callback events (when authentication tokens are received) */ - subscribeToAuthCallback: { - name: "subscribeToAuthCallback", + /** Subscribe to auth status update events (when authentication state changes) */ + subscribeToAuthStatusUpdate: { + name: "subscribeToAuthStatusUpdate", requestType: EmptyRequest, requestStream: false, - responseType: String, + responseType: AuthState, responseStream: true, options: {}, }, @@ -776,16 +1613,7 @@ export const AccountServiceDefinition = { name: "authStateChanged", requestType: AuthStateChangedRequest, requestStream: false, - responseType: AuthStateChanged, - responseStream: false, - options: {}, - }, - /** Fetches all user credits data (balance, usage transactions, payment transactions) */ - fetchUserCreditsData: { - name: "fetchUserCreditsData", - requestType: EmptyRequest, - requestStream: false, - responseType: UserCreditsData, + responseType: AuthState, responseStream: false, options: {}, }, @@ -821,6 +1649,46 @@ export const AccountServiceDefinition = { responseStream: true, options: {}, }, + /** + * Fetches all user credits data + * (balance, usage transactions, payment transactions) + */ + getUserCredits: { + name: "getUserCredits", + requestType: EmptyRequest, + requestStream: false, + responseType: UserCreditsData, + responseStream: false, + options: {}, + }, + getOrganizationCredits: { + name: "getOrganizationCredits", + requestType: GetOrganizationCreditsRequest, + requestStream: false, + responseType: OrganizationCreditsData, + responseStream: false, + options: {}, + }, + /** + * Fetches all user organizations data + * Returns a list of UserOrganization objects + */ + getUserOrganizations: { + name: "getUserOrganizations", + requestType: EmptyRequest, + requestStream: false, + responseType: UserOrganizationsResponse, + responseStream: false, + options: {}, + }, + setUserOrganization: { + name: "setUserOrganization", + requestType: UserOrganizationUpdateRequest, + requestStream: false, + responseType: Empty, + responseStream: false, + options: {}, + }, }, } as const; diff --git a/src/shared/proto/mcp.ts b/src/shared/proto/mcp.ts index 26d3c2b2..4d0e4a25 100644 --- a/src/shared/proto/mcp.ts +++ b/src/shared/proto/mcp.ts @@ -138,6 +138,18 @@ export interface McpMarketplaceCatalog { items: McpMarketplaceItem[]; } +export interface McpDownloadResponse { + mcpId: string; + githubUrl: string; + name: string; + author: string; + description: string; + readmeContent: string; + llmsInstallationContent: string; + requiresApiKey: boolean; + error?: string | undefined; +} + function createBaseToggleMcpServerRequest(): ToggleMcpServerRequest { return { metadata: undefined, serverName: "", disabled: false }; } @@ -1535,6 +1547,206 @@ export const McpMarketplaceCatalog: MessageFns = { }, }; +function createBaseMcpDownloadResponse(): McpDownloadResponse { + return { + mcpId: "", + githubUrl: "", + name: "", + author: "", + description: "", + readmeContent: "", + llmsInstallationContent: "", + requiresApiKey: false, + error: undefined, + }; +} + +export const McpDownloadResponse: MessageFns = { + encode(message: McpDownloadResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + if (message.mcpId !== "") { + writer.uint32(10).string(message.mcpId); + } + if (message.githubUrl !== "") { + writer.uint32(18).string(message.githubUrl); + } + if (message.name !== "") { + writer.uint32(26).string(message.name); + } + if (message.author !== "") { + writer.uint32(34).string(message.author); + } + if (message.description !== "") { + writer.uint32(42).string(message.description); + } + if (message.readmeContent !== "") { + writer.uint32(50).string(message.readmeContent); + } + if (message.llmsInstallationContent !== "") { + writer.uint32(58).string(message.llmsInstallationContent); + } + if (message.requiresApiKey !== false) { + writer.uint32(64).bool(message.requiresApiKey); + } + if (message.error !== undefined) { + writer.uint32(74).string(message.error); + } + return writer; + }, + + decode(input: BinaryReader | Uint8Array, length?: number): McpDownloadResponse { + const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + const end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseMcpDownloadResponse(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + if (tag !== 10) { + break; + } + + message.mcpId = reader.string(); + continue; + } + case 2: { + if (tag !== 18) { + break; + } + + message.githubUrl = reader.string(); + continue; + } + case 3: { + if (tag !== 26) { + break; + } + + message.name = reader.string(); + continue; + } + case 4: { + if (tag !== 34) { + break; + } + + message.author = reader.string(); + continue; + } + case 5: { + if (tag !== 42) { + break; + } + + message.description = reader.string(); + continue; + } + case 6: { + if (tag !== 50) { + break; + } + + message.readmeContent = reader.string(); + continue; + } + case 7: { + if (tag !== 58) { + break; + } + + message.llmsInstallationContent = reader.string(); + continue; + } + case 8: { + if (tag !== 64) { + break; + } + + message.requiresApiKey = reader.bool(); + continue; + } + case 9: { + if (tag !== 74) { + break; + } + + message.error = reader.string(); + continue; + } + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skip(tag & 7); + } + return message; + }, + + fromJSON(object: any): McpDownloadResponse { + return { + mcpId: isSet(object.mcpId) ? globalThis.String(object.mcpId) : "", + githubUrl: isSet(object.githubUrl) ? globalThis.String(object.githubUrl) : "", + name: isSet(object.name) ? globalThis.String(object.name) : "", + author: isSet(object.author) ? globalThis.String(object.author) : "", + description: isSet(object.description) ? globalThis.String(object.description) : "", + readmeContent: isSet(object.readmeContent) ? globalThis.String(object.readmeContent) : "", + llmsInstallationContent: isSet(object.llmsInstallationContent) + ? globalThis.String(object.llmsInstallationContent) + : "", + requiresApiKey: isSet(object.requiresApiKey) ? globalThis.Boolean(object.requiresApiKey) : false, + error: isSet(object.error) ? globalThis.String(object.error) : undefined, + }; + }, + + toJSON(message: McpDownloadResponse): unknown { + const obj: any = {}; + if (message.mcpId !== "") { + obj.mcpId = message.mcpId; + } + if (message.githubUrl !== "") { + obj.githubUrl = message.githubUrl; + } + if (message.name !== "") { + obj.name = message.name; + } + if (message.author !== "") { + obj.author = message.author; + } + if (message.description !== "") { + obj.description = message.description; + } + if (message.readmeContent !== "") { + obj.readmeContent = message.readmeContent; + } + if (message.llmsInstallationContent !== "") { + obj.llmsInstallationContent = message.llmsInstallationContent; + } + if (message.requiresApiKey !== false) { + obj.requiresApiKey = message.requiresApiKey; + } + if (message.error !== undefined) { + obj.error = message.error; + } + return obj; + }, + + create, I>>(base?: I): McpDownloadResponse { + return McpDownloadResponse.fromPartial(base ?? ({} as any)); + }, + fromPartial, I>>(object: I): McpDownloadResponse { + const message = createBaseMcpDownloadResponse(); + message.mcpId = object.mcpId ?? ""; + message.githubUrl = object.githubUrl ?? ""; + message.name = object.name ?? ""; + message.author = object.author ?? ""; + message.description = object.description ?? ""; + message.readmeContent = object.readmeContent ?? ""; + message.llmsInstallationContent = object.llmsInstallationContent ?? ""; + message.requiresApiKey = object.requiresApiKey ?? false; + message.error = object.error ?? undefined; + return message; + }, +}; + export type McpServiceDefinition = typeof McpServiceDefinition; export const McpServiceDefinition = { name: "McpService", @@ -1568,7 +1780,7 @@ export const McpServiceDefinition = { name: "downloadMcp", requestType: StringRequest, requestStream: false, - responseType: Empty, + responseType: McpDownloadResponse, responseStream: false, options: {}, }, diff --git a/src/shared/proto/models.ts b/src/shared/proto/models.ts index 6264b71d..38b728ba 100644 --- a/src/shared/proto/models.ts +++ b/src/shared/proto/models.ts @@ -315,7 +315,7 @@ export interface ModelsApiConfiguration { /** From ApiHandlerOptions (excluding onRetryAttempt function) */ apiModelId?: string | undefined; apiKey?: string | undefined; - clineApiKey?: string | undefined; + clineAccountId?: string | undefined; taskId?: string | undefined; liteLlmBaseUrl?: string | undefined; liteLlmModelId?: string | undefined; @@ -385,6 +385,7 @@ export interface ModelsApiConfiguration { sapAiResourceGroup?: string | undefined; sapAiCoreTokenUrl?: string | undefined; sapAiCoreBaseUrl?: string | undefined; + sapAiCoreModelId?: string | undefined; claudeCodePath?: string | undefined; shengSuanYunToken?: string | undefined; shengSuanYunApiKey?: string | undefined; @@ -2041,7 +2042,7 @@ function createBaseModelsApiConfiguration(): ModelsApiConfiguration { return { apiModelId: undefined, apiKey: undefined, - clineApiKey: undefined, + clineAccountId: undefined, taskId: undefined, liteLlmBaseUrl: undefined, liteLlmModelId: undefined, @@ -2111,6 +2112,7 @@ function createBaseModelsApiConfiguration(): ModelsApiConfiguration { sapAiResourceGroup: undefined, sapAiCoreTokenUrl: undefined, sapAiCoreBaseUrl: undefined, + sapAiCoreModelId: undefined, claudeCodePath: undefined, shengSuanYunToken: undefined, shengSuanYunApiKey: undefined, @@ -2129,8 +2131,8 @@ export const ModelsApiConfiguration: MessageFns = { if (message.apiKey !== undefined) { writer.uint32(18).string(message.apiKey); } - if (message.clineApiKey !== undefined) { - writer.uint32(26).string(message.clineApiKey); + if (message.clineAccountId !== undefined) { + writer.uint32(26).string(message.clineAccountId); } if (message.taskId !== undefined) { writer.uint32(34).string(message.taskId); @@ -2339,26 +2341,29 @@ export const ModelsApiConfiguration: MessageFns = { if (message.sapAiCoreBaseUrl !== undefined) { writer.uint32(578).string(message.sapAiCoreBaseUrl); } + if (message.sapAiCoreModelId !== undefined) { + writer.uint32(586).string(message.sapAiCoreModelId); + } if (message.claudeCodePath !== undefined) { - writer.uint32(586).string(message.claudeCodePath); + writer.uint32(594).string(message.claudeCodePath); } if (message.shengSuanYunToken !== undefined) { - writer.uint32(594).string(message.shengSuanYunToken); + writer.uint32(602).string(message.shengSuanYunToken); } if (message.shengSuanYunApiKey !== undefined) { - writer.uint32(602).string(message.shengSuanYunApiKey); + writer.uint32(610).string(message.shengSuanYunApiKey); } if (message.shengSuanYunModelId !== undefined) { - writer.uint32(610).string(message.shengSuanYunModelId); + writer.uint32(618).string(message.shengSuanYunModelId); } if (message.shengSuanYunModelInfo !== undefined) { - ShengSuanYunModelInfo.encode(message.shengSuanYunModelInfo, writer.uint32(618).fork()).join(); + ShengSuanYunModelInfo.encode(message.shengSuanYunModelInfo, writer.uint32(626).fork()).join(); } if (message.geminiCliOauthPath !== undefined) { - writer.uint32(626).string(message.geminiCliOauthPath); + writer.uint32(634).string(message.geminiCliOauthPath); } if (message.geminiCliProjectId !== undefined) { - writer.uint32(634).string(message.geminiCliProjectId); + writer.uint32(642).string(message.geminiCliProjectId); } return writer; }, @@ -2391,7 +2396,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.clineApiKey = reader.string(); + message.clineAccountId = reader.string(); continue; } case 4: { @@ -2954,7 +2959,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.claudeCodePath = reader.string(); + message.sapAiCoreModelId = reader.string(); continue; } case 74: { @@ -2962,7 +2967,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.shengSuanYunToken = reader.string(); + message.claudeCodePath = reader.string(); continue; } case 75: { @@ -2970,7 +2975,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.shengSuanYunApiKey = reader.string(); + message.shengSuanYunToken = reader.string(); continue; } case 76: { @@ -2978,7 +2983,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.shengSuanYunModelId = reader.string(); + message.shengSuanYunApiKey = reader.string(); continue; } case 77: { @@ -2986,7 +2991,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.shengSuanYunModelInfo = ShengSuanYunModelInfo.decode(reader, reader.uint32()); + message.shengSuanYunModelId = reader.string(); continue; } case 78: { @@ -2994,7 +2999,7 @@ export const ModelsApiConfiguration: MessageFns = { break; } - message.geminiCliOauthPath = reader.string(); + message.shengSuanYunModelInfo = ShengSuanYunModelInfo.decode(reader, reader.uint32()); continue; } case 79: { @@ -3002,6 +3007,14 @@ export const ModelsApiConfiguration: MessageFns = { break; } + message.geminiCliOauthPath = reader.string(); + continue; + } + case 80: { + if (tag !== 642) { + break; + } + message.geminiCliProjectId = reader.string(); continue; } @@ -3018,7 +3031,7 @@ export const ModelsApiConfiguration: MessageFns = { return { apiModelId: isSet(object.apiModelId) ? globalThis.String(object.apiModelId) : undefined, apiKey: isSet(object.apiKey) ? globalThis.String(object.apiKey) : undefined, - clineApiKey: isSet(object.clineApiKey) ? globalThis.String(object.clineApiKey) : undefined, + clineAccountId: isSet(object.clineAccountId) ? globalThis.String(object.clineAccountId) : undefined, taskId: isSet(object.taskId) ? globalThis.String(object.taskId) : undefined, liteLlmBaseUrl: isSet(object.liteLlmBaseUrl) ? globalThis.String(object.liteLlmBaseUrl) : undefined, liteLlmModelId: isSet(object.liteLlmModelId) ? globalThis.String(object.liteLlmModelId) : undefined, @@ -3125,6 +3138,7 @@ export const ModelsApiConfiguration: MessageFns = { sapAiResourceGroup: isSet(object.sapAiResourceGroup) ? globalThis.String(object.sapAiResourceGroup) : undefined, sapAiCoreTokenUrl: isSet(object.sapAiCoreTokenUrl) ? globalThis.String(object.sapAiCoreTokenUrl) : undefined, sapAiCoreBaseUrl: isSet(object.sapAiCoreBaseUrl) ? globalThis.String(object.sapAiCoreBaseUrl) : undefined, + sapAiCoreModelId: isSet(object.sapAiCoreModelId) ? globalThis.String(object.sapAiCoreModelId) : undefined, claudeCodePath: isSet(object.claudeCodePath) ? globalThis.String(object.claudeCodePath) : undefined, shengSuanYunToken: isSet(object.shengSuanYunToken) ? globalThis.String(object.shengSuanYunToken) : undefined, shengSuanYunApiKey: isSet(object.shengSuanYunApiKey) ? globalThis.String(object.shengSuanYunApiKey) : undefined, @@ -3147,8 +3161,8 @@ export const ModelsApiConfiguration: MessageFns = { if (message.apiKey !== undefined) { obj.apiKey = message.apiKey; } - if (message.clineApiKey !== undefined) { - obj.clineApiKey = message.clineApiKey; + if (message.clineAccountId !== undefined) { + obj.clineAccountId = message.clineAccountId; } if (message.taskId !== undefined) { obj.taskId = message.taskId; @@ -3363,6 +3377,9 @@ export const ModelsApiConfiguration: MessageFns = { if (message.sapAiCoreBaseUrl !== undefined) { obj.sapAiCoreBaseUrl = message.sapAiCoreBaseUrl; } + if (message.sapAiCoreModelId !== undefined) { + obj.sapAiCoreModelId = message.sapAiCoreModelId; + } if (message.claudeCodePath !== undefined) { obj.claudeCodePath = message.claudeCodePath; } @@ -3394,7 +3411,7 @@ export const ModelsApiConfiguration: MessageFns = { const message = createBaseModelsApiConfiguration(); message.apiModelId = object.apiModelId ?? undefined; message.apiKey = object.apiKey ?? undefined; - message.clineApiKey = object.clineApiKey ?? undefined; + message.clineAccountId = object.clineAccountId ?? undefined; message.taskId = object.taskId ?? undefined; message.liteLlmBaseUrl = object.liteLlmBaseUrl ?? undefined; message.liteLlmModelId = object.liteLlmModelId ?? undefined; @@ -3483,6 +3500,7 @@ export const ModelsApiConfiguration: MessageFns = { message.sapAiResourceGroup = object.sapAiResourceGroup ?? undefined; message.sapAiCoreTokenUrl = object.sapAiCoreTokenUrl ?? undefined; message.sapAiCoreBaseUrl = object.sapAiCoreBaseUrl ?? undefined; + message.sapAiCoreModelId = object.sapAiCoreModelId ?? undefined; message.claudeCodePath = object.claudeCodePath ?? undefined; message.shengSuanYunToken = object.shengSuanYunToken ?? undefined; message.shengSuanYunApiKey = object.shengSuanYunApiKey ?? undefined; diff --git a/src/shared/proto/state.ts b/src/shared/proto/state.ts index 7154ff0a..7aee166b 100644 --- a/src/shared/proto/state.ts +++ b/src/shared/proto/state.ts @@ -179,7 +179,7 @@ export interface ApiConfiguration { | string | undefined; /** Provider-specific API keys */ - clineApiKey?: string | undefined; + clineAccountId?: string | undefined; openrouterApiKey?: string | undefined; anthropicBaseUrl?: string | undefined; openaiApiKey?: string | undefined; @@ -1704,7 +1704,7 @@ function createBaseApiConfiguration(): ApiConfiguration { apiModelId: undefined, apiKey: undefined, apiBaseUrl: undefined, - clineApiKey: undefined, + clineAccountId: undefined, openrouterApiKey: undefined, anthropicBaseUrl: undefined, openaiApiKey: undefined, @@ -1798,8 +1798,8 @@ export const ApiConfiguration: MessageFns = { if (message.apiBaseUrl !== undefined) { writer.uint32(34).string(message.apiBaseUrl); } - if (message.clineApiKey !== undefined) { - writer.uint32(42).string(message.clineApiKey); + if (message.clineAccountId !== undefined) { + writer.uint32(42).string(message.clineAccountId); } if (message.openrouterApiKey !== undefined) { writer.uint32(50).string(message.openrouterApiKey); @@ -2076,7 +2076,7 @@ export const ApiConfiguration: MessageFns = { break; } - message.clineApiKey = reader.string(); + message.clineAccountId = reader.string(); continue; } case 6: { @@ -2702,7 +2702,7 @@ export const ApiConfiguration: MessageFns = { apiModelId: isSet(object.apiModelId) ? globalThis.String(object.apiModelId) : undefined, apiKey: isSet(object.apiKey) ? globalThis.String(object.apiKey) : undefined, apiBaseUrl: isSet(object.apiBaseUrl) ? globalThis.String(object.apiBaseUrl) : undefined, - clineApiKey: isSet(object.clineApiKey) ? globalThis.String(object.clineApiKey) : undefined, + clineAccountId: isSet(object.clineAccountId) ? globalThis.String(object.clineAccountId) : undefined, openrouterApiKey: isSet(object.openrouterApiKey) ? globalThis.String(object.openrouterApiKey) : undefined, anthropicBaseUrl: isSet(object.anthropicBaseUrl) ? globalThis.String(object.anthropicBaseUrl) : undefined, openaiApiKey: isSet(object.openaiApiKey) ? globalThis.String(object.openaiApiKey) : undefined, @@ -2828,8 +2828,8 @@ export const ApiConfiguration: MessageFns = { if (message.apiBaseUrl !== undefined) { obj.apiBaseUrl = message.apiBaseUrl; } - if (message.clineApiKey !== undefined) { - obj.clineApiKey = message.clineApiKey; + if (message.clineAccountId !== undefined) { + obj.clineAccountId = message.clineAccountId; } if (message.openrouterApiKey !== undefined) { obj.openrouterApiKey = message.openrouterApiKey; @@ -3071,7 +3071,7 @@ export const ApiConfiguration: MessageFns = { message.apiModelId = object.apiModelId ?? undefined; message.apiKey = object.apiKey ?? undefined; message.apiBaseUrl = object.apiBaseUrl ?? undefined; - message.clineApiKey = object.clineApiKey ?? undefined; + message.clineAccountId = object.clineAccountId ?? undefined; message.openrouterApiKey = object.openrouterApiKey ?? undefined; message.anthropicBaseUrl = object.anthropicBaseUrl ?? undefined; message.openaiApiKey = object.openaiApiKey ?? undefined; 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) 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/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 diff --git a/src/utils/path.ts b/src/utils/path.ts index fd1f85e7..f62d231a 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: @@ -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() } @@ -103,37 +103,70 @@ 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() { + 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 = "") => { - 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)) + 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 +} - // Use path.relative to check if the path is within the workspace - const relativePath = path.relative(normalizedWorkspace, normalizedPath) - - return !relativePath.startsWith("..") && !path.isAbsolute(relativePath) +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 } 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 4d4bcc57..88ec5ac5 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) @@ -816,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") diff --git a/webview-ui/.eslintrc.json b/webview-ui/.eslintrc.json index 984861dd..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": "off", //"warn", + "eslint-rules/no-direct-vscode-api": "warn", "no-restricted-syntax": [ "error", { 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 0e35fcbe..0ff5ac23 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" import { ShengSuanYunAuthProvider } from "./context/ShengSuanYunAuthContext" @@ -10,11 +10,11 @@ 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 d115f904..b74e5e9d 100644 --- a/webview-ui/src/components/account/AccountView.tsx +++ b/webview-ui/src/components/account/AccountView.tsx @@ -1,6 +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 { 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 +11,13 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { AccountServiceClient } from "@/services/grpc-client" import { EmptyRequest } from "@shared/proto/common" import { useShengSuanYunAuth } from "@/context/ShengSuanYunAuthContext" +import { GetOrganizationCreditsRequest, UserOrganization, UserOrganizationUpdateRequest } from "@shared/proto/account" + +type VSCodeDropdownChangeEvent = Event & { + target: { + value: string + } +} type AccountViewProps = { onDone: () => void @@ -32,53 +40,138 @@ 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 [isLoading, setIsLoading] = useState(true) const [usageData, setUsageData] = useState([]) const [paymentsData, setPaymentsData] = useState([]) - 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) - }) + 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 { + const res = await AccountServiceClient.getUserCredits(EmptyRequest.create()) + setBalance(res.balance?.currentBalance || 0) + setUsageData(res.usageTransactions) + setPaymentsData(res.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 res = await AccountServiceClient.getOrganizationCredits( + GetOrganizationCreditsRequest.create({ + organizationId: activeOrganization.organizationId, + }), + ) + setBalance(res.balance?.currentBalance || 0) + setUsageData(res.usageTransactions) + setPaymentsData(res.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 res = await AccountServiceClient.getUserOrganizations(EmptyRequest.create()) + setUserOrganizations(res.organizations || []) + setActiveOrganization(res.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) return + + const fetchUserData = async () => { + try { + await getUserCredits() + await getUserOrganizations() + } catch (error) { + console.error("Failed to fetch user data:", error) + } + } + + fetchUserData() }, [user]) + useEffect(() => { + if (!activeOrganization) return + + const fetchOrgCredits = async () => { + try { + await getOrganizationCredits() + } catch (error) { + console.error("Failed to fetch organization credits:", error) + } + } + + fetchOrgCredits() + }, [activeOrganization]) + 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) { + try { + await AccountServiceClient.setUserOrganization(UserOrganizationUpdateRequest.create({ organizationId: newOrgId })) + await getUserOrganizations() + } catch (error) { + console.error("Failed to update organization:", error) + } + } + } + return (
{user ? (
- {user.photoURL ? ( - Profile + {user.photoUrl ? ( + Profile ) : (
{user.displayName?.[0] || user.email?.[0] || "?"} @@ -87,7 +180,7 @@ export const ClineAccountView = () => {
{user.displayName && ( -

+

{user.displayName}

)} @@ -95,17 +188,29 @@ export const ClineAccountView = () => { {user.email && (
{user.email}
)} + + {userOrganizations && ( + + Personal + {userOrganizations.map((org: UserOrganization) => ( + + {org.name} + + ))} + + )}
- - 仪表盘 + + Dashboard
@@ -123,25 +228,12 @@ export const ClineAccountView = () => {
加载...
) : ( <> - $ - - { - 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. + */} + + @@ -149,8 +241,8 @@ export const ClineAccountView = () => {
- - 充值 + + Add Credits
@@ -158,7 +250,12 @@ export const ClineAccountView = () => {
- +
) : ( @@ -196,10 +293,10 @@ export const SSYAccountView = () => { if (user) { setIsLoading(true) AccountServiceClient.shengSuanYunUserData(EmptyRequest.create()) - .then((response) => { - setBalance(response.balance?.currentBalance || 0) - setUsageData(response.usageTransactions) - setPaymentsData(response.paymentTransactions) + .then((res) => { + setBalance(res.balance?.currentBalance || 0) + setUsageData(res.usageTransactions) + setPaymentsData(res.paymentTransactions) setIsLoading(false) }) .catch((error) => { @@ -280,16 +377,15 @@ export const SSYAccountView = () => { onClick={() => { setIsLoading(true) AccountServiceClient.shengSuanYunUserData(EmptyRequest.create()) - .then((response) => { - setBalance(response.balance?.currentBalance || 0) - setUsageData(response.usageTransactions) - setPaymentsData(response.paymentTransactions) - setIsLoading(false) + .then((res) => { + setBalance(res.balance?.currentBalance || 0) + setUsageData(res.usageTransactions) + setPaymentsData(res.paymentTransactions) }) .catch((error) => { console.error("Failed to refresh user credits data:", error) - setIsLoading(false) }) + .finally(() => setIsLoading(false)) }}> diff --git a/webview-ui/src/components/account/CreditsHistoryTable.tsx b/webview-ui/src/components/account/CreditsHistoryTable.tsx index a6a321c8..d00afadc 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 (
@@ -52,22 +53,16 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHist {usageData && - usageData.map((row, index) => { - let model = row.model - if (row.modelProvider.length) { - model = `${row.modelProvider}/${model}` - } - return ( - - - {formatTimestamp(row.spentAt, "zh-CN")} - - {model} - {/* {`${row.promptTokens} → ${row.completionTokens}`} */} - {`$${Number(row.credits || "0").toFixed(7)}`} - - ) - })} + usageData.map((row, index) => ( + + + {formatTimestamp(row.spentAt, "zh-CN")} + + {row.model} + {/* {`${row.promptTokens} → ${row.completionTokens}`} */} + {`$${Number(row.credits || "0").toFixed(7)}`} + + ))} ) : (
@@ -77,7 +72,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHist )} - {activeTab === "payments" && ( + {showPayments && activeTab === "payments" && ( <> {paymentsData && paymentsData.length > 0 ? ( diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 37d59065..40155997 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -661,9 +661,9 @@ export const ChatRowContent = memo(
{toolIcon("search")} {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} + toolIcon("sign-out", "yellow", -90, "在你的工作区之外")} - Cline wants to search this directory for {tool.regex}: + Cline 需要搜索目录 {tool.regex}:
{tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This URL is external")} + toolIcon("sign-out", "yellow", -90, "这是一个外部 URL")} - {message.type === "ask" - ? "Cline wants to fetch content from this URL:" - : "Cline fetched content from this URL:"} + {message.type === "ask" ? "Cline 从该 URL 获取内容:" : "Cline 从该 URL 获取到内容:"}
= ({ currentBalance, tot
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( diff --git a/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx b/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx index 2c89e8e8..5faa6bba 100644 --- a/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx +++ b/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx @@ -17,13 +17,13 @@ const CopyTaskButton: React.FC<{ } return ( - + + aria-label="复制任务">
diff --git a/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx b/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx index c35b4cae..7e404235 100644 --- a/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx +++ b/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx @@ -7,7 +7,7 @@ const DeleteTaskButton: React.FC<{ taskSize: string taskId?: string }> = ({ taskSize, taskId }) => ( - + taskId && TaskServiceClient.deleteTasksWithIds(StringArrayRequest.create({ value: [taskId] }))} diff --git a/webview-ui/src/components/chat/task-header/buttons/OpenDiskTaskHistoryButton.tsx b/webview-ui/src/components/chat/task-header/buttons/OpenDiskTaskHistoryButton.tsx index 342ddee1..12d627e4 100644 --- a/webview-ui/src/components/chat/task-header/buttons/OpenDiskTaskHistoryButton.tsx +++ b/webview-ui/src/components/chat/task-header/buttons/OpenDiskTaskHistoryButton.tsx @@ -15,13 +15,13 @@ const OpenDiskTaskHistoryButton: React.FC<{ } return ( - + + aria-label="任务记录">
diff --git a/webview-ui/src/components/common/MarkdownBlock.tsx b/webview-ui/src/components/common/MarkdownBlock.tsx index 4b794b3d..f1ea348e 100644 --- a/webview-ui/src/components/common/MarkdownBlock.tsx +++ b/webview-ui/src/components/common/MarkdownBlock.tsx @@ -32,14 +32,14 @@ const ActModeHighlight: React.FC = () => { ) } }} - title={chatSettings.mode === "plan" ? "Click to toggle to Act Mode" : "Already in Act Mode"} + title={chatSettings.mode === "plan" ? "点击切换到执行模式" : "已经在执行模式"} className={`text-[var(--vscode-textLink-foreground)] inline-flex items-center gap-1 ${ chatSettings.mode === "plan" ? "hover:opacity-90 cursor-pointer" : "cursor-default opacity-60" }`}>
- Act Mode (⌘⇧A) + 执行模式 (⌘⇧A) ) } diff --git a/webview-ui/src/components/history/HistoryView.tsx b/webview-ui/src/components/history/HistoryView.tsx index da06661b..083de185 100644 --- a/webview-ui/src/components/history/HistoryView.tsx +++ b/webview-ui/src/components/history/HistoryView.tsx @@ -750,7 +750,7 @@ const ExportButton = ({ itemId }: { itemId: string }) => ( console.error("Failed to export task:", err), ) }}> -
EXPORT
+
导出
) 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 27fd5b1d..f4bdc851 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 6a918d88..c8d5e199 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(() => { @@ -288,7 +273,9 @@ const McpMarketplaceView = () => { {searchQuery || selectedCategory ? "未找到匹配的 MCP 服务器" : "在市场上找不到 MCP 服务器"}
) : ( - filteredItems.map((item) => ) + filteredItems.map((item) => ( + + )) )}
diff --git a/webview-ui/src/components/settings/ClineAccountInfoCard.tsx b/webview-ui/src/components/settings/ClineAccountInfoCard.tsx index 70a452bb..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) => @@ -17,20 +17,19 @@ export const ClineAccountInfoCard = () => { } const handleShowAccount = () => { - // navigateToAccount() - handleSignOut() + navigateToAccount() } return (
- {user?.providerId == "firebase" ? ( + {user ? ( - 退出登录 + View Billing & Usage ) : (
- 注册 Cline + Sign Up with Cline
)} diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index 783d208a..e61f4350 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -44,19 +44,19 @@ 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", }, { - id: "x-ai/grok-3", - description: "Latest flagship model from xAI, free for now!", - label: "Free", + id: "x-ai/grok-3-beta", + description: "Latest flagship model from xAI", + label: "Fast & Cheap", }, ] @@ -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)) { @@ -244,6 +262,7 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } placeholder="查找模型..." value={searchTerm} onInput={(e) => { + setIsSearchInputDirty(true) handleModelChange((e.target as HTMLInputElement)?.value?.toLowerCase()) setIsDropdownVisible(true) }} @@ -327,8 +346,8 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } 如果你不确定使用哪个模型, Cline 使用{" "} handleModelChange("google/gemini-2.5-pro")}> - google/gemini-2.5-pro. + onClick={() => handleModelChange("anthropic/claude-sonnet-4")}> + anthropic/claude-sonnet-4. 你也可以尝试使用 "free" 搜索免费模型 diff --git a/webview-ui/src/components/settings/PreferredLanguageSetting.tsx b/webview-ui/src/components/settings/PreferredLanguageSetting.tsx index 20db61b7..99d7d96a 100644 --- a/webview-ui/src/components/settings/PreferredLanguageSetting.tsx +++ b/webview-ui/src/components/settings/PreferredLanguageSetting.tsx @@ -26,7 +26,7 @@ const PreferredLanguageSetting: React.FC = () => { { handleLanguageChange(e.target.value) }} diff --git a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx index 457e4aeb..d735596b 100644 --- a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx @@ -78,66 +78,81 @@ export const TerminalSettingsSection: React.FC = (
{renderSectionHeader("terminal")}
-
-
-
diff --git a/webview-ui/src/components/settings/utils/providerUtils.ts b/webview-ui/src/components/settings/utils/providerUtils.ts index ac8b47f4..baf3e499 100644 --- a/webview-ui/src/components/settings/utils/providerUtils.ts +++ b/webview-ui/src/components/settings/utils/providerUtils.ts @@ -131,12 +131,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 { 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 c464fdf7..08fbb1f8 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, @@ -31,7 +31,7 @@ import { } from "../../../src/shared/api" import { McpMarketplaceCatalog, McpServer, McpViewTab } from "../../../src/shared/mcp" import { convertTextMateToHljs } from "../utils/textMateToHljs" -import { OpenRouterCompatibleModelInfo } from "@shared/proto/models" +import { OpenRouterCompatibleModelInfo, ShengSuanYunModelInfo } from "@shared/proto/models" import { UserInfo } from "@shared/proto/account" interface ExtensionStateContextType extends ExtensionState { @@ -41,7 +41,7 @@ interface ExtensionStateContextType extends ExtensionState { openRouterModels: Record openAiModels: string[] requestyModels: Record - shengSuanYunModels: Record + shengSuanYunModels: Record mcpServers: McpServer[] mcpMarketplaceCatalog: McpMarketplaceCatalog filePaths: string[] @@ -73,7 +73,7 @@ interface ExtensionStateContextType extends ExtensionState { setChatSettings: (value: ChatSettings) => void setMcpServers: (value: McpServer[]) => void setRequestyModels: (value: Record) => void - setShengSuanYunModels: (value: Record) => void + setShengSuanYunModels: (value: Record) => void setGlobalClineRulesToggles: (toggles: Record) => void setLocalClineRulesToggles: (toggles: Record) => void setLocalCursorRulesToggles: (toggles: Record) => void @@ -223,7 +223,7 @@ export const ExtensionStateContextProvider: React.FC<{ const [requestyModels, setRequestyModels] = useState>({ [requestyDefaultModelId]: requestyDefaultModelInfo, }) - const [shengSuanYunModels, setShengSuanYunModels] = useState>({ + const [shengSuanYunModels, setShengSuanYunModels] = useState>({ [shengSuanYunDefaultModelId]: shengSuanYunDefaultModelInfo, }) const [mcpServers, setMcpServers] = useState([]) @@ -261,9 +261,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({}), { @@ -749,7 +748,7 @@ export const ExtensionStateContextProvider: React.FC<{ })), setMcpServers: (mcpServers: McpServer[]) => setMcpServers(mcpServers), setRequestyModels: (models: Record) => setRequestyModels(models), - setShengSuanYunModels: (models: Record) => setShengSuanYunModels(models), + setShengSuanYunModels: (models: Record) => setShengSuanYunModels(models), setMcpMarketplaceCatalog: (catalog: McpMarketplaceCatalog) => setMcpMarketplaceCatalog(catalog), setAvailableTerminalProfiles, setShowMcp, diff --git a/webview-ui/src/context/FirebaseAuthContext.tsx b/webview-ui/src/context/FirebaseAuthContext.tsx deleted file mode 100644 index b5e003f7..00000000 --- a/webview-ui/src/context/FirebaseAuthContext.tsx +++ /dev/null @@ -1,125 +0,0 @@ -import { AccountServiceClient } from "@/services/grpc-client" -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("自定义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/context/ShengSuanYunAuthContext.tsx b/webview-ui/src/context/ShengSuanYunAuthContext.tsx index 7fd71b93..26e2d823 100644 --- a/webview-ui/src/context/ShengSuanYunAuthContext.tsx +++ b/webview-ui/src/context/ShengSuanYunAuthContext.tsx @@ -2,7 +2,7 @@ import React, { createContext, useCallback, useContext, useEffect, useState } fr import { useExtensionState } from "./ExtensionStateContext" import axios, { AxiosRequestConfig } from "axios" import { AccountServiceClient } from "@/services/grpc-client" -import { AuthStateChanged, AuthStateChangedRequest } from "@shared/proto/account" +import { AuthStateChangedRequest } from "@shared/proto/account" import { EmptyRequest } from "@shared/proto/common" interface ShengSuanYunAuthContextType { @@ -43,7 +43,7 @@ export const ShengSuanYunAuthProvider: React.FC<{ children: React.ReactNode }> = setUser(user) setIsInitialized(true) AccountServiceClient.authStateChanged(AuthStateChangedRequest.create({ user })) - .then((res: AuthStateChanged) => { + .then((res) => { setUserInfo(res.user) }) .catch((error) => { 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/format.ts b/webview-ui/src/utils/format.ts index f9e7995e..05b37f90 100644 --- a/webview-ui/src/utils/format.ts +++ b/webview-ui/src/utils/format.ts @@ -22,9 +22,8 @@ export function formatDollars(cents?: number): string { return (cents / 100).toFixed(2) } -export function formatTimestamp(timestamp: string, tz: string = "en-US"): string { - const date = new Date(timestamp) - +export function formatTimestamp(timestamp: any, tz: string = "en-US"): string { + const date = timestamp ? new Date(timestamp) : new Date() const dateFormatter = new Intl.DateTimeFormat(tz, { month: "2-digit", day: "2-digit", @@ -33,7 +32,6 @@ export function formatTimestamp(timestamp: string, tz: string = "en-US"): string minute: "2-digit", hour12: true, }) - return dateFormatter.format(date) } diff --git a/webview-ui/src/utils/validate.ts b/webview-ui/src/utils/validate.ts index 339e81f5..63d2451e 100644 --- a/webview-ui/src/utils/validate.ts +++ b/webview-ui/src/utils/validate.ts @@ -59,8 +59,8 @@ export function validateApiConfiguration(apiConfiguration?: ApiConfiguration): s } break case "cline": - if (!apiConfiguration.clineApiKey) { - return "您必须提供有效的API密钥或选择其他提供者。" + if (!apiConfiguration.clineAccountId) { + return "You must provide a valid API key or choose a different provider." } break case "openai": 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