Matt Rubens пре 11 месеци
родитељ
комит
60a0a824b9
100 измењених фајлова са 9839 додато и 9734 уклоњено
  1. 12 12
      .changeset/changelog-config.js
  2. 9 9
      .changeset/config.json
  3. 10 1
      .github/pull_request_template.md
  4. 24 19
      README.md
  5. 112 103
      cline_docs/settings.md
  6. 37 38
      jest.config.js
  7. 11 11
      src/__mocks__/@modelcontextprotocol/sdk/client/index.js
  8. 15 15
      src/__mocks__/@modelcontextprotocol/sdk/client/stdio.js
  9. 21 21
      src/__mocks__/@modelcontextprotocol/sdk/index.js
  10. 29 29
      src/__mocks__/@modelcontextprotocol/sdk/types.js
  11. 13 13
      src/__mocks__/McpHub.ts
  12. 7 7
      src/__mocks__/default-shell.js
  13. 3 3
      src/__mocks__/delay.js
  14. 6 6
      src/__mocks__/globby.js
  15. 3 3
      src/__mocks__/os-name.js
  16. 16 16
      src/__mocks__/p-wait-for.js
  17. 18 18
      src/__mocks__/serialize-error.js
  18. 4 4
      src/__mocks__/strip-ansi.js
  19. 55 55
      src/__mocks__/vscode.js
  20. 236 237
      src/api/providers/__tests__/anthropic.test.ts
  21. 259 246
      src/api/providers/__tests__/bedrock.test.ts
  22. 215 201
      src/api/providers/__tests__/deepseek.test.ts
  23. 208 210
      src/api/providers/__tests__/gemini.test.ts
  24. 236 224
      src/api/providers/__tests__/glama.test.ts
  25. 165 158
      src/api/providers/__tests__/lmstudio.test.ts
  26. 163 158
      src/api/providers/__tests__/ollama.test.ts
  27. 324 317
      src/api/providers/__tests__/openai-native.test.ts
  28. 231 222
      src/api/providers/__tests__/openai.test.ts
  29. 294 280
      src/api/providers/__tests__/openrouter.test.ts
  30. 265 266
      src/api/providers/__tests__/vertex.test.ts
  31. 210 204
      src/api/providers/__tests__/vscode-lm.test.ts
  32. 3 3
      src/api/providers/anthropic.ts
  33. 255 249
      src/api/providers/bedrock.ts
  34. 19 19
      src/api/providers/deepseek.ts
  35. 22 19
      src/api/providers/glama.ts
  36. 1 1
      src/api/providers/lmstudio.ts
  37. 1 1
      src/api/providers/ollama.ts
  38. 6 3
      src/api/providers/openai-native.ts
  39. 5 5
      src/api/providers/openai.ts
  40. 14 12
      src/api/providers/openrouter.ts
  41. 3 3
      src/api/providers/vertex.ts
  42. 221 238
      src/api/providers/vscode-lm.ts
  43. 249 251
      src/api/transform/__tests__/bedrock-converse-format.test.ts
  44. 260 242
      src/api/transform/__tests__/openai-format.test.ts
  45. 114 114
      src/api/transform/__tests__/stream.test.ts
  46. 199 189
      src/api/transform/__tests__/vscode-lm-format.test.ts
  47. 205 199
      src/api/transform/bedrock-converse-format.ts
  48. 90 99
      src/api/transform/vscode-lm-format.ts
  49. 115 75
      src/core/Cline.ts
  50. 797 825
      src/core/__tests__/Cline.test.ts
  51. 45 45
      src/core/__tests__/mode-validator.test.ts
  52. 216 216
      src/core/config/ConfigManager.ts
  53. 462 444
      src/core/config/__tests__/ConfigManager.test.ts
  54. 13 9
      src/core/diff/DiffStrategy.ts
  55. 239 242
      src/core/diff/strategies/__tests__/new-unified.test.ts
  56. 375 364
      src/core/diff/strategies/__tests__/search-replace.test.ts
  57. 74 75
      src/core/diff/strategies/__tests__/unified.test.ts
  58. 4 4
      src/core/diff/strategies/new-unified/__tests__/edit-strategies.test.ts
  59. 184 184
      src/core/diff/strategies/new-unified/__tests__/search-strategies.test.ts
  60. 27 35
      src/core/diff/strategies/new-unified/edit-strategies.ts
  61. 5 5
      src/core/diff/strategies/new-unified/index.ts
  62. 20 20
      src/core/diff/strategies/new-unified/search-strategies.ts
  63. 13 13
      src/core/diff/strategies/new-unified/types.ts
  64. 261 248
      src/core/diff/strategies/search-replace.ts
  65. 29 29
      src/core/diff/strategies/unified.ts
  66. 29 25
      src/core/diff/types.ts
  67. 35 39
      src/core/mentions/__tests__/index.test.ts
  68. 7 9
      src/core/mode-validator.ts
  69. 339 404
      src/core/prompts/__tests__/system.test.ts
  70. 17 13
      src/core/prompts/sections/capabilities.ts
  71. 42 37
      src/core/prompts/sections/custom-instructions.ts
  72. 8 8
      src/core/prompts/sections/index.ts
  73. 41 40
      src/core/prompts/sections/mcp-servers.ts
  74. 2 2
      src/core/prompts/sections/objective.ts
  75. 11 15
      src/core/prompts/sections/rules.ts
  76. 2 2
      src/core/prompts/sections/system-info.ts
  77. 2 2
      src/core/prompts/sections/tool-use-guidelines.ts
  78. 2 2
      src/core/prompts/sections/tool-use.ts
  79. 102 105
      src/core/prompts/system.ts
  80. 6 6
      src/core/prompts/tools/access-mcp-resource.ts
  81. 2 2
      src/core/prompts/tools/ask-followup-question.ts
  82. 2 2
      src/core/prompts/tools/attempt-completion.ts
  83. 6 6
      src/core/prompts/tools/browser-action.ts
  84. 3 3
      src/core/prompts/tools/execute-command.ts
  85. 67 66
      src/core/prompts/tools/index.ts
  86. 3 3
      src/core/prompts/tools/list-code-definition-names.ts
  87. 3 3
      src/core/prompts/tools/list-files.ts
  88. 3 3
      src/core/prompts/tools/read-file.ts
  89. 2 2
      src/core/prompts/tools/search-files.ts
  90. 9 9
      src/core/prompts/tools/types.ts
  91. 6 6
      src/core/prompts/tools/use-mcp-tool.ts
  92. 2 2
      src/core/prompts/tools/write-to-file.ts
  93. 43 43
      src/core/prompts/types.ts
  94. 25 25
      src/core/tool-lists.ts
  95. 219 204
      src/core/webview/ClineProvider.ts
  96. 947 967
      src/core/webview/__tests__/ClineProvider.test.ts
  97. 3 5
      src/extension.ts
  98. 5 5
      src/integrations/editor/DiffViewProvider.ts
  99. 40 44
      src/integrations/editor/__tests__/DiffViewProvider.test.ts
  100. 47 39
      src/integrations/editor/__tests__/detect-omission.test.ts

+ 12 - 12
.changeset/changelog-config.js

@@ -1,20 +1,20 @@
 // Half-works to simplify the format but needs 'overwrite_changeset_changelog.py' in GHA to finish formatting
 
 const getReleaseLine = async (changeset) => {
-  const [firstLine] = changeset.summary
-    .split('\n')
-    .map(l => l.trim())
-    .filter(Boolean);
-  return `- ${firstLine}`;
-};
+	const [firstLine] = changeset.summary
+		.split("\n")
+		.map((l) => l.trim())
+		.filter(Boolean)
+	return `- ${firstLine}`
+}
 
 const getDependencyReleaseLine = async () => {
-  return '';
-};
+	return ""
+}
 
 const changelogFunctions = {
-  getReleaseLine,
-  getDependencyReleaseLine,
-};
+	getReleaseLine,
+	getDependencyReleaseLine,
+}
 
-module.exports = changelogFunctions;
+module.exports = changelogFunctions

+ 9 - 9
.changeset/config.json

@@ -1,11 +1,11 @@
 {
-  "$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
-  "changelog": "./changelog-config.js",
-  "commit": false,
-  "fixed": [],
-  "linked": [],
-  "access": "restricted",
-  "baseBranch": "main",
-  "updateInternalDependencies": "patch",
-  "ignore": []
+	"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
+	"changelog": "./changelog-config.js",
+	"commit": false,
+	"fixed": [],
+	"linked": [],
+	"access": "restricted",
+	"baseBranch": "main",
+	"updateInternalDependencies": "patch",
+	"ignore": []
 }

+ 10 - 1
.github/pull_request_template.md

@@ -1,28 +1,37 @@
 <!-- **Note:** Consider creating PRs as a DRAFT. For early feedback and self-review. -->
+
 ## Description
 
 ## Type of change
+
 <!-- Please ignore options that are not relevant -->
+
 - [ ] Bug fix (non-breaking change which fixes an issue)
 - [ ] New feature
 - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
 - [ ] This change requires a documentation update
 
 ## How Has This Been Tested?
+
 <!-- Please describe the tests that you ran to verify your changes -->
 
 ## Checklist:
+
 <!-- Go over all the following points, and put an `x` in all the boxes that apply -->
+
 - [ ] My code follows the patterns of this project
 - [ ] I have performed a self-review of my own code
 - [ ] I have commented my code, particularly in hard-to-understand areas
 - [ ] I have made corresponding changes to the documentation
 
 ## Additional context
+
 <!-- Add any other context or screenshots about the pull request here -->
 
 ## Related Issues
+
 <!-- List any related issues here. Use the GitHub issue linking syntax: #issue-number -->
 
 ## Reviewers
-<!-- @mention specific team members or individuals who should review this PR -->
+
+<!-- @mention specific team members or individuals who should review this PR -->

+ 24 - 19
README.md

@@ -10,14 +10,15 @@ Hot off the heels of **v3.0** introducing Code, Architect, and Ask chat modes, o
 
 You can now tailor the **role definition** and **custom instructions** for every chat mode to perfectly fit your workflow. Want to adjust Architect mode to focus more on system scalability? Or tweak Ask mode for deeper research queries? Done. Plus, you can define these via **mode-specific `.clinerules-[mode]` files**. You’ll find all of this in the new **Prompts** tab in the top menu.
 
-The second big feature in this release is a complete revamp of **prompt enhancements**. This feature helps you craft messages to get even better results from Cline. Here’s what’s new:  
-- Works with **any provider** and API configuration, not just OpenRouter.  
-- Fully customizable prompts to match your unique needs.  
+The second big feature in this release is a complete revamp of **prompt enhancements**. This feature helps you craft messages to get even better results from Cline. Here’s what’s new:
+
+- Works with **any provider** and API configuration, not just OpenRouter.
+- Fully customizable prompts to match your unique needs.
 - Same simple workflow: just hit the ✨ **Enhance Prompt** button in the chat input to try it out.
 
 Whether you’re using GPT-4, other APIs, or switching configurations, this gives you total control over how your prompts are optimized.
 
-As always, we’d love to hear your thoughts and ideas! What features do you want to see in **v3.2**? Drop by https://www.reddit.com/r/roocline and join the discussion - we're building Roo Cline together. 🚀  
+As always, we’d love to hear your thoughts and ideas! What features do you want to see in **v3.2**? Drop by https://www.reddit.com/r/roocline and join the discussion - we're building Roo Cline together. 🚀
 
 ## New in 3.0 - Chat Modes!
 
@@ -33,6 +34,7 @@ You can now choose between different prompts for Roo Cline to better suit your w
 It’s super simple! There’s a dropdown in the bottom left of the chat input to switch modes. Right next to it, you’ll find a way to switch between the API configuration profiles associated with the current mode (configured on the settings screen).
 
 **Why Add This?**
+
 - It keeps Cline from being overly eager to jump into solving problems when you just want to think or ask questions.
 - Each mode remembers the API configuration you last used with it. For example, you can use more thoughtful models like OpenAI o1 for Architect and Ask, while sticking with Sonnet or DeepSeek for coding tasks.
 - It builds on research suggesting better results when separating "thinking" from "coding," explained well in this very thoughtful [article](https://aider.chat/2024/09/26/architect.html) from aider.
@@ -50,25 +52,27 @@ Here's an example of Roo-Cline autonomously creating a snake game with "Always a
 https://github.com/user-attachments/assets/c2bb31dc-e9b2-4d73-885d-17f1471a4987
 
 ## Contributing
+
 To contribute to the project, start by exploring [open issues](https://github.com/RooVetGit/Roo-Cline/issues) or checking our [feature request board](https://github.com/RooVetGit/Roo-Cline/discussions/categories/feature-requests). We'd also love to have you join the [Roo Cline Reddit](https://www.reddit.com/r/roocline/) to share ideas and connect with other contributors.
 
 ### Local Setup
 
 1. Install dependencies:
-   ```bash
-   npm run install:all
-   ```
+
+    ```bash
+    npm run install:all
+    ```
 
 2. Build the VSIX file:
-   ```bash
-   npm run build
-   ```
+    ```bash
+    npm run build
+    ```
 3. The new VSIX file will be created in the `bin/` directory
 4. Install the extension from the VSIX file as described below:
 
-   - **Option 1:** Drag and drop the `.vsix` file into your VSCode-compatible editor's Extensions panel (Cmd/Ctrl+Shift+X).
+    - **Option 1:** Drag and drop the `.vsix` file into your VSCode-compatible editor's Extensions panel (Cmd/Ctrl+Shift+X).
 
-   - **Option 2:** Install the plugin using the CLI, make sure you have your VSCode-compatible CLI installed and in your `PATH` variable. Cursor example: `export PATH="$PATH:/Applications/Cursor.app/Contents/MacOS"`
+    - **Option 2:** Install the plugin using the CLI, make sure you have your VSCode-compatible CLI installed and in your `PATH` variable. Cursor example: `export PATH="$PATH:/Applications/Cursor.app/Contents/MacOS"`
 
     ```bash
     # Ex: cursor --install-extension bin/roo-cline-2.0.1.vsix
@@ -83,16 +87,17 @@ We use [changesets](https://github.com/changesets/changesets) for versioning and
 
 1. Create a PR with your changes
 2. Create a new changeset by running `npm run changeset`
-   - Select the appropriate kind of change - `patch` for bug fixes, `minor` for new features, or `major` for breaking changes
-   - Write a clear description of your changes that will be included in the changelog
+    - Select the appropriate kind of change - `patch` for bug fixes, `minor` for new features, or `major` for breaking changes
+    - Write a clear description of your changes that will be included in the changelog
 3. Get the PR approved and pass all checks
 4. Merge it
 
 Once your merge is successful:
+
 - The release workflow will automatically create a new "Changeset version bump" PR
 - This PR will:
-  - Update the version based on your changeset
-  - Update the `CHANGELOG.md` file
+    - Update the version based on your changeset
+    - Update the `CHANGELOG.md` file
 - Once the PR is approved and merged, a new version will be published
 
 ---
@@ -193,9 +198,9 @@ Try asking Cline to "test the app", and watch as he runs a command like `npm run
 
 Thanks to the [Model Context Protocol](https://github.com/modelcontextprotocol), Cline can extend his capabilities through custom tools. While you can use [community-made servers](https://github.com/modelcontextprotocol/servers), Cline can instead create and install tools tailored to your specific workflow. Just ask Cline to "add a tool" and he will handle everything, from creating a new MCP server to installing it into the extension. These custom tools then become part of Cline's toolkit, ready to use in future tasks.
 
--   "add a tool that fetches Jira tickets": Retrieve ticket ACs and put Cline to work
--   "add a tool that manages AWS EC2s": Check server metrics and scale instances up or down
--   "add a tool that pulls the latest PagerDuty incidents": Fetch details and ask Cline to fix bugs
+- "add a tool that fetches Jira tickets": Retrieve ticket ACs and put Cline to work
+- "add a tool that manages AWS EC2s": Check server metrics and scale instances up or down
+- "add a tool that pulls the latest PagerDuty incidents": Fetch details and ask Cline to fix bugs
 
 <!-- Transparent pixel to create line break after floating image -->
 

+ 112 - 103
cline_docs/settings.md

@@ -1,137 +1,146 @@
-
 ## For All Settings
 
 1. Add the setting to ExtensionMessage.ts:
-   - Add the setting to the ExtensionState interface
-   - Make it required if it has a default value, optional if it can be undefined
-   - Example: `preferredLanguage: string`
+
+    - Add the setting to the ExtensionState interface
+    - Make it required if it has a default value, optional if it can be undefined
+    - Example: `preferredLanguage: string`
 
 2. Add test coverage:
-   - Add the setting to mockState in ClineProvider.test.ts
-   - Add test cases for setting persistence and state updates
-   - Ensure all tests pass before submitting changes
+    - Add the setting to mockState in ClineProvider.test.ts
+    - Add test cases for setting persistence and state updates
+    - Ensure all tests pass before submitting changes
 
 ## For Checkbox Settings
 
 1. Add the message type to WebviewMessage.ts:
-   - Add the setting name to the WebviewMessage type's type union
-   - Example: `| "multisearchDiffEnabled"`
+
+    - Add the setting name to the WebviewMessage type's type union
+    - Example: `| "multisearchDiffEnabled"`
 
 2. Add the setting to ExtensionStateContext.tsx:
-   - Add the setting to the ExtensionStateContextType interface
-   - Add the setter function to the interface
-   - Add the setting to the initial state in useState
-   - Add the setting to the contextValue object
-   - Example:
-     ```typescript
-     interface ExtensionStateContextType {
-       multisearchDiffEnabled: boolean;
-       setMultisearchDiffEnabled: (value: boolean) => void;
-     }
-     ```
+
+    - Add the setting to the ExtensionStateContextType interface
+    - Add the setter function to the interface
+    - Add the setting to the initial state in useState
+    - Add the setting to the contextValue object
+    - Example:
+        ```typescript
+        interface ExtensionStateContextType {
+        	multisearchDiffEnabled: boolean
+        	setMultisearchDiffEnabled: (value: boolean) => void
+        }
+        ```
 
 3. Add the setting to ClineProvider.ts:
-   - Add the setting name to the GlobalStateKey type union
-   - Add the setting to the Promise.all array in getState
-   - Add the setting to the return value in getState with a default value
-   - Add the setting to the destructured variables in getStateToPostToWebview
-   - Add the setting to the return value in getStateToPostToWebview
-   - Add a case in setWebviewMessageListener to handle the setting's message type
-   - Example:
-     ```typescript
-     case "multisearchDiffEnabled":
-       await this.updateGlobalState("multisearchDiffEnabled", message.bool)
-       await this.postStateToWebview()
-       break
-     ```
+
+    - Add the setting name to the GlobalStateKey type union
+    - Add the setting to the Promise.all array in getState
+    - Add the setting to the return value in getState with a default value
+    - Add the setting to the destructured variables in getStateToPostToWebview
+    - Add the setting to the return value in getStateToPostToWebview
+    - Add a case in setWebviewMessageListener to handle the setting's message type
+    - Example:
+        ```typescript
+        case "multisearchDiffEnabled":
+          await this.updateGlobalState("multisearchDiffEnabled", message.bool)
+          await this.postStateToWebview()
+          break
+        ```
 
 4. Add the checkbox UI to SettingsView.tsx:
-   - Import the setting and its setter from ExtensionStateContext
-   - Add the VSCodeCheckbox component with the setting's state and onChange handler
-   - Add appropriate labels and description text
-   - Example:
-     ```typescript
-     <VSCodeCheckbox 
-       checked={multisearchDiffEnabled} 
-       onChange={(e: any) => setMultisearchDiffEnabled(e.target.checked)}
-     >
-       <span style={{ fontWeight: "500" }}>Enable multi-search diff matching</span>
-     </VSCodeCheckbox>
-     ```
+
+    - Import the setting and its setter from ExtensionStateContext
+    - Add the VSCodeCheckbox component with the setting's state and onChange handler
+    - Add appropriate labels and description text
+    - Example:
+        ```typescript
+        <VSCodeCheckbox
+          checked={multisearchDiffEnabled}
+          onChange={(e: any) => setMultisearchDiffEnabled(e.target.checked)}
+        >
+          <span style={{ fontWeight: "500" }}>Enable multi-search diff matching</span>
+        </VSCodeCheckbox>
+        ```
 
 5. Add the setting to handleSubmit in SettingsView.tsx:
-   - Add a vscode.postMessage call to send the setting's value when clicking Done
-   - Example:
-     ```typescript
-     vscode.postMessage({ type: "multisearchDiffEnabled", bool: multisearchDiffEnabled })
-     ```
+    - Add a vscode.postMessage call to send the setting's value when clicking Done
+    - Example:
+        ```typescript
+        vscode.postMessage({ type: "multisearchDiffEnabled", bool: multisearchDiffEnabled })
+        ```
 
 ## For Select/Dropdown Settings
 
 1. Add the message type to WebviewMessage.ts:
-   - Add the setting name to the WebviewMessage type's type union
-   - Example: `| "preferredLanguage"`
+
+    - Add the setting name to the WebviewMessage type's type union
+    - Example: `| "preferredLanguage"`
 
 2. Add the setting to ExtensionStateContext.tsx:
-   - Add the setting to the ExtensionStateContextType interface
-   - Add the setter function to the interface
-   - Add the setting to the initial state in useState with a default value
-   - Add the setting to the contextValue object
-   - Example:
-     ```typescript
-     interface ExtensionStateContextType {
-       preferredLanguage: string;
-       setPreferredLanguage: (value: string) => void;
-     }
-     ```
+
+    - Add the setting to the ExtensionStateContextType interface
+    - Add the setter function to the interface
+    - Add the setting to the initial state in useState with a default value
+    - Add the setting to the contextValue object
+    - Example:
+        ```typescript
+        interface ExtensionStateContextType {
+        	preferredLanguage: string
+        	setPreferredLanguage: (value: string) => void
+        }
+        ```
 
 3. Add the setting to ClineProvider.ts:
-   - Add the setting name to the GlobalStateKey type union
-   - Add the setting to the Promise.all array in getState
-   - Add the setting to the return value in getState with a default value
-   - Add the setting to the destructured variables in getStateToPostToWebview
-   - Add the setting to the return value in getStateToPostToWebview
-   - Add a case in setWebviewMessageListener to handle the setting's message type
-   - Example:
-     ```typescript
-     case "preferredLanguage":
-       await this.updateGlobalState("preferredLanguage", message.text)
-       await this.postStateToWebview()
-       break
-     ```
+
+    - Add the setting name to the GlobalStateKey type union
+    - Add the setting to the Promise.all array in getState
+    - Add the setting to the return value in getState with a default value
+    - Add the setting to the destructured variables in getStateToPostToWebview
+    - Add the setting to the return value in getStateToPostToWebview
+    - Add a case in setWebviewMessageListener to handle the setting's message type
+    - Example:
+        ```typescript
+        case "preferredLanguage":
+          await this.updateGlobalState("preferredLanguage", message.text)
+          await this.postStateToWebview()
+          break
+        ```
 
 4. Add the select UI to SettingsView.tsx:
-   - Import the setting and its setter from ExtensionStateContext
-   - Add the select element with appropriate styling to match VSCode's theme
-   - Add options for the dropdown
-   - Add appropriate labels and description text
-   - Example:
-     ```typescript
-     <select
-       value={preferredLanguage}
-       onChange={(e) => setPreferredLanguage(e.target.value)}
-       style={{
-         width: "100%",
-         padding: "4px 8px",
-         backgroundColor: "var(--vscode-input-background)",
-         color: "var(--vscode-input-foreground)",
-         border: "1px solid var(--vscode-input-border)",
-         borderRadius: "2px"
-       }}>
-       <option value="English">English</option>
-       <option value="Spanish">Spanish</option>
-       ...
-     </select>
-     ```
+
+    - Import the setting and its setter from ExtensionStateContext
+    - Add the select element with appropriate styling to match VSCode's theme
+    - Add options for the dropdown
+    - Add appropriate labels and description text
+    - Example:
+        ```typescript
+        <select
+          value={preferredLanguage}
+          onChange={(e) => setPreferredLanguage(e.target.value)}
+          style={{
+            width: "100%",
+            padding: "4px 8px",
+            backgroundColor: "var(--vscode-input-background)",
+            color: "var(--vscode-input-foreground)",
+            border: "1px solid var(--vscode-input-border)",
+            borderRadius: "2px"
+          }}>
+          <option value="English">English</option>
+          <option value="Spanish">Spanish</option>
+          ...
+        </select>
+        ```
 
 5. Add the setting to handleSubmit in SettingsView.tsx:
-   - Add a vscode.postMessage call to send the setting's value when clicking Done
-   - Example:
-     ```typescript
-     vscode.postMessage({ type: "preferredLanguage", text: preferredLanguage })
-     ```
+    - Add a vscode.postMessage call to send the setting's value when clicking Done
+    - Example:
+        ```typescript
+        vscode.postMessage({ type: "preferredLanguage", text: preferredLanguage })
+        ```
 
 These steps ensure that:
+
 - The setting's state is properly typed throughout the application
 - The setting persists between sessions
 - The setting's value is properly synchronized between the webview and extension

+ 37 - 38
jest.config.js

@@ -1,41 +1,40 @@
 /** @type {import('ts-jest').JestConfigWithTsJest} */
 module.exports = {
-    preset: 'ts-jest',
-    testEnvironment: 'node',
-    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
-    transform: {
-        '^.+\\.tsx?$': ['ts-jest', {
-            tsconfig: {
-                "module": "CommonJS",
-                "moduleResolution": "node",
-                "esModuleInterop": true,
-                "allowJs": true
-            },
-            diagnostics: false,
-            isolatedModules: true
-        }]
-    },
-    testMatch: ['**/__tests__/**/*.test.ts'],
-    moduleNameMapper: {
-        '^vscode$': '<rootDir>/src/__mocks__/vscode.js',
-        '@modelcontextprotocol/sdk$': '<rootDir>/src/__mocks__/@modelcontextprotocol/sdk/index.js',
-        '@modelcontextprotocol/sdk/(.*)': '<rootDir>/src/__mocks__/@modelcontextprotocol/sdk/$1',
-        '^delay$': '<rootDir>/src/__mocks__/delay.js',
-        '^p-wait-for$': '<rootDir>/src/__mocks__/p-wait-for.js',
-        '^globby$': '<rootDir>/src/__mocks__/globby.js',
-        '^serialize-error$': '<rootDir>/src/__mocks__/serialize-error.js',
-        '^strip-ansi$': '<rootDir>/src/__mocks__/strip-ansi.js',
-        '^default-shell$': '<rootDir>/src/__mocks__/default-shell.js',
-        '^os-name$': '<rootDir>/src/__mocks__/os-name.js'
-    },
-    transformIgnorePatterns: [
-        'node_modules/(?!(@modelcontextprotocol|delay|p-wait-for|globby|serialize-error|strip-ansi|default-shell|os-name)/)'
-    ],
-    modulePathIgnorePatterns: [
-        '.vscode-test'
-    ],
-    reporters: [
-        ["jest-simple-dot-reporter", {}]
-    ],
-    setupFiles: []
+	preset: "ts-jest",
+	testEnvironment: "node",
+	moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
+	transform: {
+		"^.+\\.tsx?$": [
+			"ts-jest",
+			{
+				tsconfig: {
+					module: "CommonJS",
+					moduleResolution: "node",
+					esModuleInterop: true,
+					allowJs: true,
+				},
+				diagnostics: false,
+				isolatedModules: true,
+			},
+		],
+	},
+	testMatch: ["**/__tests__/**/*.test.ts"],
+	moduleNameMapper: {
+		"^vscode$": "<rootDir>/src/__mocks__/vscode.js",
+		"@modelcontextprotocol/sdk$": "<rootDir>/src/__mocks__/@modelcontextprotocol/sdk/index.js",
+		"@modelcontextprotocol/sdk/(.*)": "<rootDir>/src/__mocks__/@modelcontextprotocol/sdk/$1",
+		"^delay$": "<rootDir>/src/__mocks__/delay.js",
+		"^p-wait-for$": "<rootDir>/src/__mocks__/p-wait-for.js",
+		"^globby$": "<rootDir>/src/__mocks__/globby.js",
+		"^serialize-error$": "<rootDir>/src/__mocks__/serialize-error.js",
+		"^strip-ansi$": "<rootDir>/src/__mocks__/strip-ansi.js",
+		"^default-shell$": "<rootDir>/src/__mocks__/default-shell.js",
+		"^os-name$": "<rootDir>/src/__mocks__/os-name.js",
+	},
+	transformIgnorePatterns: [
+		"node_modules/(?!(@modelcontextprotocol|delay|p-wait-for|globby|serialize-error|strip-ansi|default-shell|os-name)/)",
+	],
+	modulePathIgnorePatterns: [".vscode-test"],
+	reporters: [["jest-simple-dot-reporter", {}]],
+	setupFiles: [],
 }

+ 11 - 11
src/__mocks__/@modelcontextprotocol/sdk/client/index.js

@@ -1,17 +1,17 @@
 class Client {
-  constructor() {
-    this.request = jest.fn()
-  }
+	constructor() {
+		this.request = jest.fn()
+	}
 
-  connect() {
-    return Promise.resolve()
-  }
+	connect() {
+		return Promise.resolve()
+	}
 
-  close() {
-    return Promise.resolve()
-  }
+	close() {
+		return Promise.resolve()
+	}
 }
 
 module.exports = {
-  Client
-}
+	Client,
+}

+ 15 - 15
src/__mocks__/@modelcontextprotocol/sdk/client/stdio.js

@@ -1,22 +1,22 @@
 class StdioClientTransport {
-  constructor() {
-    this.start = jest.fn().mockResolvedValue(undefined)
-    this.close = jest.fn().mockResolvedValue(undefined)
-    this.stderr = {
-      on: jest.fn()
-    }
-  }
+	constructor() {
+		this.start = jest.fn().mockResolvedValue(undefined)
+		this.close = jest.fn().mockResolvedValue(undefined)
+		this.stderr = {
+			on: jest.fn(),
+		}
+	}
 }
 
 class StdioServerParameters {
-  constructor() {
-    this.command = ''
-    this.args = []
-    this.env = {}
-  }
+	constructor() {
+		this.command = ""
+		this.args = []
+		this.env = {}
+	}
 }
 
 module.exports = {
-  StdioClientTransport,
-  StdioServerParameters
-}
+	StdioClientTransport,
+	StdioServerParameters,
+}

+ 21 - 21
src/__mocks__/@modelcontextprotocol/sdk/index.js

@@ -1,24 +1,24 @@
-const { Client } = require('./client/index.js')
-const { StdioClientTransport, StdioServerParameters } = require('./client/stdio.js')
+const { Client } = require("./client/index.js")
+const { StdioClientTransport, StdioServerParameters } = require("./client/stdio.js")
 const {
-  CallToolResultSchema,
-  ListToolsResultSchema,
-  ListResourcesResultSchema,
-  ListResourceTemplatesResultSchema,
-  ReadResourceResultSchema,
-  ErrorCode,
-  McpError
-} = require('./types.js')
+	CallToolResultSchema,
+	ListToolsResultSchema,
+	ListResourcesResultSchema,
+	ListResourceTemplatesResultSchema,
+	ReadResourceResultSchema,
+	ErrorCode,
+	McpError,
+} = require("./types.js")
 
 module.exports = {
-  Client,
-  StdioClientTransport,
-  StdioServerParameters,
-  CallToolResultSchema,
-  ListToolsResultSchema,
-  ListResourcesResultSchema,
-  ListResourceTemplatesResultSchema,
-  ReadResourceResultSchema,
-  ErrorCode,
-  McpError
-}
+	Client,
+	StdioClientTransport,
+	StdioServerParameters,
+	CallToolResultSchema,
+	ListToolsResultSchema,
+	ListResourcesResultSchema,
+	ListResourceTemplatesResultSchema,
+	ReadResourceResultSchema,
+	ErrorCode,
+	McpError,
+}

+ 29 - 29
src/__mocks__/@modelcontextprotocol/sdk/types.js

@@ -1,51 +1,51 @@
 const CallToolResultSchema = {
-  parse: jest.fn().mockReturnValue({})
+	parse: jest.fn().mockReturnValue({}),
 }
 
 const ListToolsResultSchema = {
-  parse: jest.fn().mockReturnValue({
-    tools: []
-  })
+	parse: jest.fn().mockReturnValue({
+		tools: [],
+	}),
 }
 
 const ListResourcesResultSchema = {
-  parse: jest.fn().mockReturnValue({
-    resources: []
-  })
+	parse: jest.fn().mockReturnValue({
+		resources: [],
+	}),
 }
 
 const ListResourceTemplatesResultSchema = {
-  parse: jest.fn().mockReturnValue({
-    resourceTemplates: []
-  })
+	parse: jest.fn().mockReturnValue({
+		resourceTemplates: [],
+	}),
 }
 
 const ReadResourceResultSchema = {
-  parse: jest.fn().mockReturnValue({
-    contents: []
-  })
+	parse: jest.fn().mockReturnValue({
+		contents: [],
+	}),
 }
 
 const ErrorCode = {
-  InvalidRequest: 'InvalidRequest',
-  MethodNotFound: 'MethodNotFound',
-  InvalidParams: 'InvalidParams',
-  InternalError: 'InternalError'
+	InvalidRequest: "InvalidRequest",
+	MethodNotFound: "MethodNotFound",
+	InvalidParams: "InvalidParams",
+	InternalError: "InternalError",
 }
 
 class McpError extends Error {
-  constructor(code, message) {
-    super(message)
-    this.code = code
-  }
+	constructor(code, message) {
+		super(message)
+		this.code = code
+	}
 }
 
 module.exports = {
-  CallToolResultSchema,
-  ListToolsResultSchema,
-  ListResourcesResultSchema,
-  ListResourceTemplatesResultSchema,
-  ReadResourceResultSchema,
-  ErrorCode,
-  McpError
-}
+	CallToolResultSchema,
+	ListToolsResultSchema,
+	ListResourcesResultSchema,
+	ListResourceTemplatesResultSchema,
+	ReadResourceResultSchema,
+	ErrorCode,
+	McpError,
+}

+ 13 - 13
src/__mocks__/McpHub.ts

@@ -1,17 +1,17 @@
 export class McpHub {
-  connections = []
-  isConnecting = false
+	connections = []
+	isConnecting = false
 
-  constructor() {
-    this.toggleToolAlwaysAllow = jest.fn()
-    this.callTool = jest.fn()
-  }
+	constructor() {
+		this.toggleToolAlwaysAllow = jest.fn()
+		this.callTool = jest.fn()
+	}
 
-  async toggleToolAlwaysAllow(serverName: string, toolName: string, shouldAllow: boolean): Promise<void> {
-    return Promise.resolve()
-  }
+	async toggleToolAlwaysAllow(serverName: string, toolName: string, shouldAllow: boolean): Promise<void> {
+		return Promise.resolve()
+	}
 
-  async callTool(serverName: string, toolName: string, toolArguments?: Record<string, unknown>): Promise<any> {
-    return Promise.resolve({ result: 'success' })
-  }
-}
+	async callTool(serverName: string, toolName: string, toolArguments?: Record<string, unknown>): Promise<any> {
+		return Promise.resolve({ result: "success" })
+	}
+}

+ 7 - 7
src/__mocks__/default-shell.js

@@ -1,12 +1,12 @@
 // Mock default shell based on platform
-const os = require('os');
+const os = require("os")
 
-let defaultShell;
-if (os.platform() === 'win32') {
-  defaultShell = 'cmd.exe';
+let defaultShell
+if (os.platform() === "win32") {
+	defaultShell = "cmd.exe"
 } else {
-  defaultShell = '/bin/bash';
+	defaultShell = "/bin/bash"
 }
 
-module.exports = defaultShell;
-module.exports.default = defaultShell;
+module.exports = defaultShell
+module.exports.default = defaultShell

+ 3 - 3
src/__mocks__/delay.js

@@ -1,6 +1,6 @@
 function delay(ms) {
-  return new Promise(resolve => setTimeout(resolve, ms));
+	return new Promise((resolve) => setTimeout(resolve, ms))
 }
 
-module.exports = delay;
-module.exports.default = delay;
+module.exports = delay
+module.exports.default = delay

+ 6 - 6
src/__mocks__/globby.js

@@ -1,10 +1,10 @@
 function globby(patterns, options) {
-  return Promise.resolve([]);
+	return Promise.resolve([])
 }
 
-globby.sync = function(patterns, options) {
-  return [];
-};
+globby.sync = function (patterns, options) {
+	return []
+}
 
-module.exports = globby;
-module.exports.default = globby;
+module.exports = globby
+module.exports.default = globby

+ 3 - 3
src/__mocks__/os-name.js

@@ -1,6 +1,6 @@
 function osName() {
-  return 'macOS';
+	return "macOS"
 }
 
-module.exports = osName;
-module.exports.default = osName;
+module.exports = osName
+module.exports.default = osName

+ 16 - 16
src/__mocks__/p-wait-for.js

@@ -1,20 +1,20 @@
 function pWaitFor(condition, options = {}) {
-  return new Promise((resolve, reject) => {
-    const interval = setInterval(() => {
-      if (condition()) {
-        clearInterval(interval);
-        resolve();
-      }
-    }, options.interval || 20);
+	return new Promise((resolve, reject) => {
+		const interval = setInterval(() => {
+			if (condition()) {
+				clearInterval(interval)
+				resolve()
+			}
+		}, options.interval || 20)
 
-    if (options.timeout) {
-      setTimeout(() => {
-        clearInterval(interval);
-        reject(new Error('Timed out'));
-      }, options.timeout);
-    }
-  });
+		if (options.timeout) {
+			setTimeout(() => {
+				clearInterval(interval)
+				reject(new Error("Timed out"))
+			}, options.timeout)
+		}
+	})
 }
 
-module.exports = pWaitFor;
-module.exports.default = pWaitFor;
+module.exports = pWaitFor
+module.exports.default = pWaitFor

+ 18 - 18
src/__mocks__/serialize-error.js

@@ -1,25 +1,25 @@
 function serializeError(error) {
-  if (error instanceof Error) {
-    return {
-      name: error.name,
-      message: error.message,
-      stack: error.stack
-    };
-  }
-  return error;
+	if (error instanceof Error) {
+		return {
+			name: error.name,
+			message: error.message,
+			stack: error.stack,
+		}
+	}
+	return error
 }
 
 function deserializeError(errorData) {
-  if (errorData && typeof errorData === 'object') {
-    const error = new Error(errorData.message);
-    error.name = errorData.name;
-    error.stack = errorData.stack;
-    return error;
-  }
-  return errorData;
+	if (errorData && typeof errorData === "object") {
+		const error = new Error(errorData.message)
+		error.name = errorData.name
+		error.stack = errorData.stack
+		return error
+	}
+	return errorData
 }
 
 module.exports = {
-  serializeError,
-  deserializeError
-};
+	serializeError,
+	deserializeError,
+}

+ 4 - 4
src/__mocks__/strip-ansi.js

@@ -1,7 +1,7 @@
 function stripAnsi(string) {
-  // Simple mock that just returns the input string
-  return string;
+	// Simple mock that just returns the input string
+	return string
 }
 
-module.exports = stripAnsi;
-module.exports.default = stripAnsi;
+module.exports = stripAnsi
+module.exports.default = stripAnsi

+ 55 - 55
src/__mocks__/vscode.js

@@ -1,57 +1,57 @@
 const vscode = {
-  window: {
-    showInformationMessage: jest.fn(),
-    showErrorMessage: jest.fn(),
-    createTextEditorDecorationType: jest.fn().mockReturnValue({
-      dispose: jest.fn()
-    })
-  },
-  workspace: {
-    onDidSaveTextDocument: jest.fn()
-  },
-  Disposable: class {
-    dispose() {}
-  },
-  Uri: {
-    file: (path) => ({
-      fsPath: path,
-      scheme: 'file',
-      authority: '',
-      path: path,
-      query: '',
-      fragment: '',
-      with: jest.fn(),
-      toJSON: jest.fn()
-    })
-  },
-  EventEmitter: class {
-    constructor() {
-      this.event = jest.fn();
-      this.fire = jest.fn();
-    }
-  },
-  ConfigurationTarget: {
-    Global: 1,
-    Workspace: 2,
-    WorkspaceFolder: 3
-  },
-  Position: class {
-    constructor(line, character) {
-      this.line = line;
-      this.character = character;
-    }
-  },
-  Range: class {
-    constructor(startLine, startCharacter, endLine, endCharacter) {
-      this.start = new vscode.Position(startLine, startCharacter);
-      this.end = new vscode.Position(endLine, endCharacter);
-    }
-  },
-  ThemeColor: class {
-    constructor(id) {
-      this.id = id;
-    }
-  }
-};
+	window: {
+		showInformationMessage: jest.fn(),
+		showErrorMessage: jest.fn(),
+		createTextEditorDecorationType: jest.fn().mockReturnValue({
+			dispose: jest.fn(),
+		}),
+	},
+	workspace: {
+		onDidSaveTextDocument: jest.fn(),
+	},
+	Disposable: class {
+		dispose() {}
+	},
+	Uri: {
+		file: (path) => ({
+			fsPath: path,
+			scheme: "file",
+			authority: "",
+			path: path,
+			query: "",
+			fragment: "",
+			with: jest.fn(),
+			toJSON: jest.fn(),
+		}),
+	},
+	EventEmitter: class {
+		constructor() {
+			this.event = jest.fn()
+			this.fire = jest.fn()
+		}
+	},
+	ConfigurationTarget: {
+		Global: 1,
+		Workspace: 2,
+		WorkspaceFolder: 3,
+	},
+	Position: class {
+		constructor(line, character) {
+			this.line = line
+			this.character = character
+		}
+	},
+	Range: class {
+		constructor(startLine, startCharacter, endLine, endCharacter) {
+			this.start = new vscode.Position(startLine, startCharacter)
+			this.end = new vscode.Position(endLine, endCharacter)
+		}
+	},
+	ThemeColor: class {
+		constructor(id) {
+			this.id = id
+		}
+	},
+}
 
-module.exports = vscode;
+module.exports = vscode

+ 236 - 237
src/api/providers/__tests__/anthropic.test.ts

@@ -1,239 +1,238 @@
-import { AnthropicHandler } from '../anthropic';
-import { ApiHandlerOptions } from '../../../shared/api';
-import { ApiStream } from '../../transform/stream';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { AnthropicHandler } from "../anthropic"
+import { ApiHandlerOptions } from "../../../shared/api"
+import { ApiStream } from "../../transform/stream"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock Anthropic client
-const mockBetaCreate = jest.fn();
-const mockCreate = jest.fn();
-jest.mock('@anthropic-ai/sdk', () => {
-    return {
-        Anthropic: jest.fn().mockImplementation(() => ({
-            beta: {
-                promptCaching: {
-                    messages: {
-                        create: mockBetaCreate.mockImplementation(async () => ({
-                            async *[Symbol.asyncIterator]() {
-                                yield {
-                                    type: 'message_start',
-                                    message: {
-                                        usage: {
-                                            input_tokens: 100,
-                                            output_tokens: 50,
-                                            cache_creation_input_tokens: 20,
-                                            cache_read_input_tokens: 10
-                                        }
-                                    }
-                                };
-                                yield {
-                                    type: 'content_block_start',
-                                    index: 0,
-                                    content_block: {
-                                        type: 'text',
-                                        text: 'Hello'
-                                    }
-                                };
-                                yield {
-                                    type: 'content_block_delta',
-                                    delta: {
-                                        type: 'text_delta',
-                                        text: ' world'
-                                    }
-                                };
-                            }
-                        }))
-                    }
-                }
-            },
-            messages: {
-                create: mockCreate.mockImplementation(async (options) => {
-                    if (!options.stream) {
-                        return {
-                            id: 'test-completion',
-                            content: [
-                                { type: 'text', text: 'Test response' }
-                            ],
-                            role: 'assistant',
-                            model: options.model,
-                            usage: {
-                                input_tokens: 10,
-                                output_tokens: 5
-                            }
-                        }
-                    }
-                    return {
-                        async *[Symbol.asyncIterator]() {
-                            yield {
-                                type: 'message_start',
-                                message: {
-                                    usage: {
-                                        input_tokens: 10,
-                                        output_tokens: 5
-                                    }
-                                }
-                            }
-                            yield {
-                                type: 'content_block_start',
-                                content_block: {
-                                    type: 'text',
-                                    text: 'Test response'
-                                }
-                            }
-                        }
-                    }
-                })
-            }
-        }))
-    };
-});
-
-describe('AnthropicHandler', () => {
-    let handler: AnthropicHandler;
-    let mockOptions: ApiHandlerOptions;
-
-    beforeEach(() => {
-        mockOptions = {
-            apiKey: 'test-api-key',
-            apiModelId: 'claude-3-5-sonnet-20241022'
-        };
-        handler = new AnthropicHandler(mockOptions);
-        mockBetaCreate.mockClear();
-        mockCreate.mockClear();
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(AnthropicHandler);
-            expect(handler.getModel().id).toBe(mockOptions.apiModelId);
-        });
-
-        it('should initialize with undefined API key', () => {
-            // The SDK will handle API key validation, so we just verify it initializes
-            const handlerWithoutKey = new AnthropicHandler({
-                ...mockOptions,
-                apiKey: undefined
-            });
-            expect(handlerWithoutKey).toBeInstanceOf(AnthropicHandler);
-        });
-
-        it('should use custom base URL if provided', () => {
-            const customBaseUrl = 'https://custom.anthropic.com';
-            const handlerWithCustomUrl = new AnthropicHandler({
-                ...mockOptions,
-                anthropicBaseUrl: customBaseUrl
-            });
-            expect(handlerWithCustomUrl).toBeInstanceOf(AnthropicHandler);
-        });
-    });
-
-    describe('createMessage', () => {
-        const systemPrompt = 'You are a helpful assistant.';
-        const messages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: [{ 
-                    type: 'text' as const,
-                    text: 'Hello!'
-                }]
-            }
-        ];
-
-        it('should handle prompt caching for supported models', async () => {
-            const stream = handler.createMessage(systemPrompt, [
-                {
-                    role: 'user',
-                    content: [{ type: 'text' as const, text: 'First message' }]
-                },
-                {
-                    role: 'assistant',
-                    content: [{ type: 'text' as const, text: 'Response' }]
-                },
-                {
-                    role: 'user',
-                    content: [{ type: 'text' as const, text: 'Second message' }]
-                }
-            ]);
-
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            // Verify usage information
-            const usageChunk = chunks.find(chunk => chunk.type === 'usage');
-            expect(usageChunk).toBeDefined();
-            expect(usageChunk?.inputTokens).toBe(100);
-            expect(usageChunk?.outputTokens).toBe(50);
-            expect(usageChunk?.cacheWriteTokens).toBe(20);
-            expect(usageChunk?.cacheReadTokens).toBe(10);
-
-            // Verify text content
-            const textChunks = chunks.filter(chunk => chunk.type === 'text');
-            expect(textChunks).toHaveLength(2);
-            expect(textChunks[0].text).toBe('Hello');
-            expect(textChunks[1].text).toBe(' world');
-
-            // Verify beta API was used
-            expect(mockBetaCreate).toHaveBeenCalled();
-            expect(mockCreate).not.toHaveBeenCalled();
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: mockOptions.apiModelId,
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                max_tokens: 8192,
-                temperature: 0,
-                stream: false
-            });
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Anthropic completion error: API Error');
-        });
-
-        it('should handle non-text content', async () => {
-            mockCreate.mockImplementationOnce(async () => ({
-                content: [{ type: 'image' }]
-            }));
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-
-        it('should handle empty response', async () => {
-            mockCreate.mockImplementationOnce(async () => ({
-                content: [{ type: 'text', text: '' }]
-            }));
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return default model if no model ID is provided', () => {
-            const handlerWithoutModel = new AnthropicHandler({
-                ...mockOptions,
-                apiModelId: undefined
-            });
-            const model = handlerWithoutModel.getModel();
-            expect(model.id).toBeDefined();
-            expect(model.info).toBeDefined();
-        });
-
-        it('should return specified model if valid model ID is provided', () => {
-            const model = handler.getModel();
-            expect(model.id).toBe(mockOptions.apiModelId);
-            expect(model.info).toBeDefined();
-            expect(model.info.maxTokens).toBe(8192);
-            expect(model.info.contextWindow).toBe(200_000);
-            expect(model.info.supportsImages).toBe(true);
-            expect(model.info.supportsPromptCache).toBe(true);
-        });
-    });
-});
+const mockBetaCreate = jest.fn()
+const mockCreate = jest.fn()
+jest.mock("@anthropic-ai/sdk", () => {
+	return {
+		Anthropic: jest.fn().mockImplementation(() => ({
+			beta: {
+				promptCaching: {
+					messages: {
+						create: mockBetaCreate.mockImplementation(async () => ({
+							async *[Symbol.asyncIterator]() {
+								yield {
+									type: "message_start",
+									message: {
+										usage: {
+											input_tokens: 100,
+											output_tokens: 50,
+											cache_creation_input_tokens: 20,
+											cache_read_input_tokens: 10,
+										},
+									},
+								}
+								yield {
+									type: "content_block_start",
+									index: 0,
+									content_block: {
+										type: "text",
+										text: "Hello",
+									},
+								}
+								yield {
+									type: "content_block_delta",
+									delta: {
+										type: "text_delta",
+										text: " world",
+									},
+								}
+							},
+						})),
+					},
+				},
+			},
+			messages: {
+				create: mockCreate.mockImplementation(async (options) => {
+					if (!options.stream) {
+						return {
+							id: "test-completion",
+							content: [{ type: "text", text: "Test response" }],
+							role: "assistant",
+							model: options.model,
+							usage: {
+								input_tokens: 10,
+								output_tokens: 5,
+							},
+						}
+					}
+					return {
+						async *[Symbol.asyncIterator]() {
+							yield {
+								type: "message_start",
+								message: {
+									usage: {
+										input_tokens: 10,
+										output_tokens: 5,
+									},
+								},
+							}
+							yield {
+								type: "content_block_start",
+								content_block: {
+									type: "text",
+									text: "Test response",
+								},
+							}
+						},
+					}
+				}),
+			},
+		})),
+	}
+})
+
+describe("AnthropicHandler", () => {
+	let handler: AnthropicHandler
+	let mockOptions: ApiHandlerOptions
+
+	beforeEach(() => {
+		mockOptions = {
+			apiKey: "test-api-key",
+			apiModelId: "claude-3-5-sonnet-20241022",
+		}
+		handler = new AnthropicHandler(mockOptions)
+		mockBetaCreate.mockClear()
+		mockCreate.mockClear()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(AnthropicHandler)
+			expect(handler.getModel().id).toBe(mockOptions.apiModelId)
+		})
+
+		it("should initialize with undefined API key", () => {
+			// The SDK will handle API key validation, so we just verify it initializes
+			const handlerWithoutKey = new AnthropicHandler({
+				...mockOptions,
+				apiKey: undefined,
+			})
+			expect(handlerWithoutKey).toBeInstanceOf(AnthropicHandler)
+		})
+
+		it("should use custom base URL if provided", () => {
+			const customBaseUrl = "https://custom.anthropic.com"
+			const handlerWithCustomUrl = new AnthropicHandler({
+				...mockOptions,
+				anthropicBaseUrl: customBaseUrl,
+			})
+			expect(handlerWithCustomUrl).toBeInstanceOf(AnthropicHandler)
+		})
+	})
+
+	describe("createMessage", () => {
+		const systemPrompt = "You are a helpful assistant."
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: [
+					{
+						type: "text" as const,
+						text: "Hello!",
+					},
+				],
+			},
+		]
+
+		it("should handle prompt caching for supported models", async () => {
+			const stream = handler.createMessage(systemPrompt, [
+				{
+					role: "user",
+					content: [{ type: "text" as const, text: "First message" }],
+				},
+				{
+					role: "assistant",
+					content: [{ type: "text" as const, text: "Response" }],
+				},
+				{
+					role: "user",
+					content: [{ type: "text" as const, text: "Second message" }],
+				},
+			])
+
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			// Verify usage information
+			const usageChunk = chunks.find((chunk) => chunk.type === "usage")
+			expect(usageChunk).toBeDefined()
+			expect(usageChunk?.inputTokens).toBe(100)
+			expect(usageChunk?.outputTokens).toBe(50)
+			expect(usageChunk?.cacheWriteTokens).toBe(20)
+			expect(usageChunk?.cacheReadTokens).toBe(10)
+
+			// Verify text content
+			const textChunks = chunks.filter((chunk) => chunk.type === "text")
+			expect(textChunks).toHaveLength(2)
+			expect(textChunks[0].text).toBe("Hello")
+			expect(textChunks[1].text).toBe(" world")
+
+			// Verify beta API was used
+			expect(mockBetaCreate).toHaveBeenCalled()
+			expect(mockCreate).not.toHaveBeenCalled()
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: mockOptions.apiModelId,
+				messages: [{ role: "user", content: "Test prompt" }],
+				max_tokens: 8192,
+				temperature: 0,
+				stream: false,
+			})
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow("Anthropic completion error: API Error")
+		})
+
+		it("should handle non-text content", async () => {
+			mockCreate.mockImplementationOnce(async () => ({
+				content: [{ type: "image" }],
+			}))
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+
+		it("should handle empty response", async () => {
+			mockCreate.mockImplementationOnce(async () => ({
+				content: [{ type: "text", text: "" }],
+			}))
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return default model if no model ID is provided", () => {
+			const handlerWithoutModel = new AnthropicHandler({
+				...mockOptions,
+				apiModelId: undefined,
+			})
+			const model = handlerWithoutModel.getModel()
+			expect(model.id).toBeDefined()
+			expect(model.info).toBeDefined()
+		})
+
+		it("should return specified model if valid model ID is provided", () => {
+			const model = handler.getModel()
+			expect(model.id).toBe(mockOptions.apiModelId)
+			expect(model.info).toBeDefined()
+			expect(model.info.maxTokens).toBe(8192)
+			expect(model.info.contextWindow).toBe(200_000)
+			expect(model.info.supportsImages).toBe(true)
+			expect(model.info.supportsPromptCache).toBe(true)
+		})
+	})
+})

+ 259 - 246
src/api/providers/__tests__/bedrock.test.ts

@@ -1,246 +1,259 @@
-import { AwsBedrockHandler } from '../bedrock';
-import { MessageContent } from '../../../shared/api';
-import { BedrockRuntimeClient } from '@aws-sdk/client-bedrock-runtime';
-import { Anthropic } from '@anthropic-ai/sdk';
-
-describe('AwsBedrockHandler', () => {
-    let handler: AwsBedrockHandler;
-
-    beforeEach(() => {
-        handler = new AwsBedrockHandler({
-            apiModelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
-            awsAccessKey: 'test-access-key',
-            awsSecretKey: 'test-secret-key',
-            awsRegion: 'us-east-1'
-        });
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided config', () => {
-            expect(handler['options'].awsAccessKey).toBe('test-access-key');
-            expect(handler['options'].awsSecretKey).toBe('test-secret-key');
-            expect(handler['options'].awsRegion).toBe('us-east-1');
-            expect(handler['options'].apiModelId).toBe('anthropic.claude-3-5-sonnet-20241022-v2:0');
-        });
-
-        it('should initialize with missing AWS credentials', () => {
-            const handlerWithoutCreds = new AwsBedrockHandler({
-                apiModelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
-                awsRegion: 'us-east-1'
-            });
-            expect(handlerWithoutCreds).toBeInstanceOf(AwsBedrockHandler);
-        });
-    });
-
-    describe('createMessage', () => {
-        const mockMessages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: 'Hello'
-            },
-            {
-                role: 'assistant',
-                content: 'Hi there!'
-            }
-        ];
-
-        const systemPrompt = 'You are a helpful assistant';
-
-        it('should handle text messages correctly', async () => {
-            const mockResponse = {
-                messages: [{
-                    role: 'assistant',
-                    content: [{ type: 'text', text: 'Hello! How can I help you?' }]
-                }],
-                usage: {
-                    input_tokens: 10,
-                    output_tokens: 5
-                }
-            };
-
-            // Mock AWS SDK invoke
-            const mockStream = {
-                [Symbol.asyncIterator]: async function* () {
-                    yield {
-                        metadata: {
-                            usage: {
-                                inputTokens: 10,
-                                outputTokens: 5
-                            }
-                        }
-                    };
-                }
-            };
-
-            const mockInvoke = jest.fn().mockResolvedValue({
-                stream: mockStream
-            });
-
-            handler['client'] = {
-                send: mockInvoke
-            } as unknown as BedrockRuntimeClient;
-
-            const stream = handler.createMessage(systemPrompt, mockMessages);
-            const chunks = [];
-            
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            expect(chunks[0]).toEqual({
-                type: 'usage',
-                inputTokens: 10,
-                outputTokens: 5
-            });
-
-            expect(mockInvoke).toHaveBeenCalledWith(expect.objectContaining({
-                input: expect.objectContaining({
-                    modelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0'
-                })
-            }));
-        });
-
-        it('should handle API errors', async () => {
-            // Mock AWS SDK invoke with error
-            const mockInvoke = jest.fn().mockRejectedValue(new Error('AWS Bedrock error'));
-
-            handler['client'] = {
-                send: mockInvoke
-            } as unknown as BedrockRuntimeClient;
-
-            const stream = handler.createMessage(systemPrompt, mockMessages);
-
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should throw before yielding any chunks
-                }
-            }).rejects.toThrow('AWS Bedrock error');
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const mockResponse = {
-                output: new TextEncoder().encode(JSON.stringify({
-                    content: 'Test response'
-                }))
-            };
-
-            const mockSend = jest.fn().mockResolvedValue(mockResponse);
-            handler['client'] = {
-                send: mockSend
-            } as unknown as BedrockRuntimeClient;
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockSend).toHaveBeenCalledWith(expect.objectContaining({
-                input: expect.objectContaining({
-                    modelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
-                    messages: expect.arrayContaining([
-                        expect.objectContaining({
-                            role: 'user',
-                            content: [{ text: 'Test prompt' }]
-                        })
-                    ]),
-                    inferenceConfig: expect.objectContaining({
-                        maxTokens: 5000,
-                        temperature: 0.3,
-                        topP: 0.1
-                    })
-                })
-            }));
-        });
-
-        it('should handle API errors', async () => {
-            const mockError = new Error('AWS Bedrock error');
-            const mockSend = jest.fn().mockRejectedValue(mockError);
-            handler['client'] = {
-                send: mockSend
-            } as unknown as BedrockRuntimeClient;
-
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Bedrock completion error: AWS Bedrock error');
-        });
-
-        it('should handle invalid response format', async () => {
-            const mockResponse = {
-                output: new TextEncoder().encode('invalid json')
-            };
-
-            const mockSend = jest.fn().mockResolvedValue(mockResponse);
-            handler['client'] = {
-                send: mockSend
-            } as unknown as BedrockRuntimeClient;
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-
-        it('should handle empty response', async () => {
-            const mockResponse = {
-                output: new TextEncoder().encode(JSON.stringify({}))
-            };
-
-            const mockSend = jest.fn().mockResolvedValue(mockResponse);
-            handler['client'] = {
-                send: mockSend
-            } as unknown as BedrockRuntimeClient;
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-
-        it('should handle cross-region inference', async () => {
-            handler = new AwsBedrockHandler({
-                apiModelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
-                awsAccessKey: 'test-access-key',
-                awsSecretKey: 'test-secret-key',
-                awsRegion: 'us-east-1',
-                awsUseCrossRegionInference: true
-            });
-
-            const mockResponse = {
-                output: new TextEncoder().encode(JSON.stringify({
-                    content: 'Test response'
-                }))
-            };
-
-            const mockSend = jest.fn().mockResolvedValue(mockResponse);
-            handler['client'] = {
-                send: mockSend
-            } as unknown as BedrockRuntimeClient;
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockSend).toHaveBeenCalledWith(expect.objectContaining({
-                input: expect.objectContaining({
-                    modelId: 'us.anthropic.claude-3-5-sonnet-20241022-v2:0'
-                })
-            }));
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return correct model info in test environment', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe('anthropic.claude-3-5-sonnet-20241022-v2:0');
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(5000); // Test environment value
-            expect(modelInfo.info.contextWindow).toBe(128_000); // Test environment value
-        });
-
-        it('should return test model info for invalid model in test environment', () => {
-            const invalidHandler = new AwsBedrockHandler({
-                apiModelId: 'invalid-model',
-                awsAccessKey: 'test-access-key',
-                awsSecretKey: 'test-secret-key',
-                awsRegion: 'us-east-1'
-            });
-            const modelInfo = invalidHandler.getModel();
-            expect(modelInfo.id).toBe('invalid-model'); // In test env, returns whatever is passed
-            expect(modelInfo.info.maxTokens).toBe(5000);
-            expect(modelInfo.info.contextWindow).toBe(128_000);
-        });
-    });
-});
+import { AwsBedrockHandler } from "../bedrock"
+import { MessageContent } from "../../../shared/api"
+import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"
+import { Anthropic } from "@anthropic-ai/sdk"
+
+describe("AwsBedrockHandler", () => {
+	let handler: AwsBedrockHandler
+
+	beforeEach(() => {
+		handler = new AwsBedrockHandler({
+			apiModelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
+			awsAccessKey: "test-access-key",
+			awsSecretKey: "test-secret-key",
+			awsRegion: "us-east-1",
+		})
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided config", () => {
+			expect(handler["options"].awsAccessKey).toBe("test-access-key")
+			expect(handler["options"].awsSecretKey).toBe("test-secret-key")
+			expect(handler["options"].awsRegion).toBe("us-east-1")
+			expect(handler["options"].apiModelId).toBe("anthropic.claude-3-5-sonnet-20241022-v2:0")
+		})
+
+		it("should initialize with missing AWS credentials", () => {
+			const handlerWithoutCreds = new AwsBedrockHandler({
+				apiModelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
+				awsRegion: "us-east-1",
+			})
+			expect(handlerWithoutCreds).toBeInstanceOf(AwsBedrockHandler)
+		})
+	})
+
+	describe("createMessage", () => {
+		const mockMessages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: "Hello",
+			},
+			{
+				role: "assistant",
+				content: "Hi there!",
+			},
+		]
+
+		const systemPrompt = "You are a helpful assistant"
+
+		it("should handle text messages correctly", async () => {
+			const mockResponse = {
+				messages: [
+					{
+						role: "assistant",
+						content: [{ type: "text", text: "Hello! How can I help you?" }],
+					},
+				],
+				usage: {
+					input_tokens: 10,
+					output_tokens: 5,
+				},
+			}
+
+			// Mock AWS SDK invoke
+			const mockStream = {
+				[Symbol.asyncIterator]: async function* () {
+					yield {
+						metadata: {
+							usage: {
+								inputTokens: 10,
+								outputTokens: 5,
+							},
+						},
+					}
+				},
+			}
+
+			const mockInvoke = jest.fn().mockResolvedValue({
+				stream: mockStream,
+			})
+
+			handler["client"] = {
+				send: mockInvoke,
+			} as unknown as BedrockRuntimeClient
+
+			const stream = handler.createMessage(systemPrompt, mockMessages)
+			const chunks = []
+
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			expect(chunks[0]).toEqual({
+				type: "usage",
+				inputTokens: 10,
+				outputTokens: 5,
+			})
+
+			expect(mockInvoke).toHaveBeenCalledWith(
+				expect.objectContaining({
+					input: expect.objectContaining({
+						modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
+					}),
+				}),
+			)
+		})
+
+		it("should handle API errors", async () => {
+			// Mock AWS SDK invoke with error
+			const mockInvoke = jest.fn().mockRejectedValue(new Error("AWS Bedrock error"))
+
+			handler["client"] = {
+				send: mockInvoke,
+			} as unknown as BedrockRuntimeClient
+
+			const stream = handler.createMessage(systemPrompt, mockMessages)
+
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should throw before yielding any chunks
+				}
+			}).rejects.toThrow("AWS Bedrock error")
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const mockResponse = {
+				output: new TextEncoder().encode(
+					JSON.stringify({
+						content: "Test response",
+					}),
+				),
+			}
+
+			const mockSend = jest.fn().mockResolvedValue(mockResponse)
+			handler["client"] = {
+				send: mockSend,
+			} as unknown as BedrockRuntimeClient
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockSend).toHaveBeenCalledWith(
+				expect.objectContaining({
+					input: expect.objectContaining({
+						modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
+						messages: expect.arrayContaining([
+							expect.objectContaining({
+								role: "user",
+								content: [{ text: "Test prompt" }],
+							}),
+						]),
+						inferenceConfig: expect.objectContaining({
+							maxTokens: 5000,
+							temperature: 0.3,
+							topP: 0.1,
+						}),
+					}),
+				}),
+			)
+		})
+
+		it("should handle API errors", async () => {
+			const mockError = new Error("AWS Bedrock error")
+			const mockSend = jest.fn().mockRejectedValue(mockError)
+			handler["client"] = {
+				send: mockSend,
+			} as unknown as BedrockRuntimeClient
+
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow(
+				"Bedrock completion error: AWS Bedrock error",
+			)
+		})
+
+		it("should handle invalid response format", async () => {
+			const mockResponse = {
+				output: new TextEncoder().encode("invalid json"),
+			}
+
+			const mockSend = jest.fn().mockResolvedValue(mockResponse)
+			handler["client"] = {
+				send: mockSend,
+			} as unknown as BedrockRuntimeClient
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+
+		it("should handle empty response", async () => {
+			const mockResponse = {
+				output: new TextEncoder().encode(JSON.stringify({})),
+			}
+
+			const mockSend = jest.fn().mockResolvedValue(mockResponse)
+			handler["client"] = {
+				send: mockSend,
+			} as unknown as BedrockRuntimeClient
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+
+		it("should handle cross-region inference", async () => {
+			handler = new AwsBedrockHandler({
+				apiModelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
+				awsAccessKey: "test-access-key",
+				awsSecretKey: "test-secret-key",
+				awsRegion: "us-east-1",
+				awsUseCrossRegionInference: true,
+			})
+
+			const mockResponse = {
+				output: new TextEncoder().encode(
+					JSON.stringify({
+						content: "Test response",
+					}),
+				),
+			}
+
+			const mockSend = jest.fn().mockResolvedValue(mockResponse)
+			handler["client"] = {
+				send: mockSend,
+			} as unknown as BedrockRuntimeClient
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockSend).toHaveBeenCalledWith(
+				expect.objectContaining({
+					input: expect.objectContaining({
+						modelId: "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
+					}),
+				}),
+			)
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return correct model info in test environment", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe("anthropic.claude-3-5-sonnet-20241022-v2:0")
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(5000) // Test environment value
+			expect(modelInfo.info.contextWindow).toBe(128_000) // Test environment value
+		})
+
+		it("should return test model info for invalid model in test environment", () => {
+			const invalidHandler = new AwsBedrockHandler({
+				apiModelId: "invalid-model",
+				awsAccessKey: "test-access-key",
+				awsSecretKey: "test-secret-key",
+				awsRegion: "us-east-1",
+			})
+			const modelInfo = invalidHandler.getModel()
+			expect(modelInfo.id).toBe("invalid-model") // In test env, returns whatever is passed
+			expect(modelInfo.info.maxTokens).toBe(5000)
+			expect(modelInfo.info.contextWindow).toBe(128_000)
+		})
+	})
+})

+ 215 - 201
src/api/providers/__tests__/deepseek.test.ts

@@ -1,203 +1,217 @@
-import { DeepSeekHandler } from '../deepseek';
-import { ApiHandlerOptions, deepSeekDefaultModelId } from '../../../shared/api';
-import OpenAI from 'openai';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { DeepSeekHandler } from "../deepseek"
+import { ApiHandlerOptions, deepSeekDefaultModelId } from "../../../shared/api"
+import OpenAI from "openai"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock OpenAI client
-const mockCreate = jest.fn();
-jest.mock('openai', () => {
-    return {
-        __esModule: true,
-        default: jest.fn().mockImplementation(() => ({
-            chat: {
-                completions: {
-                    create: mockCreate.mockImplementation(async (options) => {
-                        if (!options.stream) {
-                            return {
-                                id: 'test-completion',
-                                choices: [{
-                                    message: { role: 'assistant', content: 'Test response', refusal: null },
-                                    finish_reason: 'stop',
-                                    index: 0
-                                }],
-                                usage: {
-                                    prompt_tokens: 10,
-                                    completion_tokens: 5,
-                                    total_tokens: 15
-                                }
-                            };
-                        }
-                        
-                        // Return async iterator for streaming
-                        return {
-                            [Symbol.asyncIterator]: async function* () {
-                                yield {
-                                    choices: [{
-                                        delta: { content: 'Test response' },
-                                        index: 0
-                                    }],
-                                    usage: null
-                                };
-                                yield {
-                                    choices: [{
-                                        delta: {},
-                                        index: 0
-                                    }],
-                                    usage: {
-                                        prompt_tokens: 10,
-                                        completion_tokens: 5,
-                                        total_tokens: 15
-                                    }
-                                };
-                            }
-                        };
-                    })
-                }
-            }
-        }))
-    };
-});
-
-describe('DeepSeekHandler', () => {
-    let handler: DeepSeekHandler;
-    let mockOptions: ApiHandlerOptions;
-
-    beforeEach(() => {
-        mockOptions = {
-            deepSeekApiKey: 'test-api-key',
-            deepSeekModelId: 'deepseek-chat',
-            deepSeekBaseUrl: 'https://api.deepseek.com/v1'
-        };
-        handler = new DeepSeekHandler(mockOptions);
-        mockCreate.mockClear();
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(DeepSeekHandler);
-            expect(handler.getModel().id).toBe(mockOptions.deepSeekModelId);
-        });
-
-        it('should throw error if API key is missing', () => {
-            expect(() => {
-                new DeepSeekHandler({
-                    ...mockOptions,
-                    deepSeekApiKey: undefined
-                });
-            }).toThrow('DeepSeek API key is required');
-        });
-
-        it('should use default model ID if not provided', () => {
-            const handlerWithoutModel = new DeepSeekHandler({
-                ...mockOptions,
-                deepSeekModelId: undefined
-            });
-            expect(handlerWithoutModel.getModel().id).toBe(deepSeekDefaultModelId);
-        });
-
-        it('should use default base URL if not provided', () => {
-            const handlerWithoutBaseUrl = new DeepSeekHandler({
-                ...mockOptions,
-                deepSeekBaseUrl: undefined
-            });
-            expect(handlerWithoutBaseUrl).toBeInstanceOf(DeepSeekHandler);
-            // The base URL is passed to OpenAI client internally
-            expect(OpenAI).toHaveBeenCalledWith(expect.objectContaining({
-                baseURL: 'https://api.deepseek.com/v1'
-            }));
-        });
-
-        it('should use custom base URL if provided', () => {
-            const customBaseUrl = 'https://custom.deepseek.com/v1';
-            const handlerWithCustomUrl = new DeepSeekHandler({
-                ...mockOptions,
-                deepSeekBaseUrl: customBaseUrl
-            });
-            expect(handlerWithCustomUrl).toBeInstanceOf(DeepSeekHandler);
-            // The custom base URL is passed to OpenAI client
-            expect(OpenAI).toHaveBeenCalledWith(expect.objectContaining({
-                baseURL: customBaseUrl
-            }));
-        });
-
-        it('should set includeMaxTokens to true', () => {
-            // Create a new handler and verify OpenAI client was called with includeMaxTokens
-            new DeepSeekHandler(mockOptions);
-            expect(OpenAI).toHaveBeenCalledWith(expect.objectContaining({
-                apiKey: mockOptions.deepSeekApiKey
-            }));
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return model info for valid model ID', () => {
-            const model = handler.getModel();
-            expect(model.id).toBe(mockOptions.deepSeekModelId);
-            expect(model.info).toBeDefined();
-            expect(model.info.maxTokens).toBe(8192);
-            expect(model.info.contextWindow).toBe(64_000);
-            expect(model.info.supportsImages).toBe(false);
-            expect(model.info.supportsPromptCache).toBe(false);
-        });
-
-        it('should return provided model ID with default model info if model does not exist', () => {
-            const handlerWithInvalidModel = new DeepSeekHandler({
-                ...mockOptions,
-                deepSeekModelId: 'invalid-model'
-            });
-            const model = handlerWithInvalidModel.getModel();
-            expect(model.id).toBe('invalid-model'); // Returns provided ID
-            expect(model.info).toBeDefined();
-            expect(model.info).toBe(handler.getModel().info); // But uses default model info
-        });
-
-        it('should return default model if no model ID is provided', () => {
-            const handlerWithoutModel = new DeepSeekHandler({
-                ...mockOptions,
-                deepSeekModelId: undefined
-            });
-            const model = handlerWithoutModel.getModel();
-            expect(model.id).toBe(deepSeekDefaultModelId);
-            expect(model.info).toBeDefined();
-        });
-    });
-
-    describe('createMessage', () => {
-        const systemPrompt = 'You are a helpful assistant.';
-        const messages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: [{ 
-                    type: 'text' as const,
-                    text: 'Hello!'
-                }]
-            }
-        ];
-
-        it('should handle streaming responses', async () => {
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            const textChunks = chunks.filter(chunk => chunk.type === 'text');
-            expect(textChunks).toHaveLength(1);
-            expect(textChunks[0].text).toBe('Test response');
-        });
-
-        it('should include usage information', async () => {
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            const usageChunks = chunks.filter(chunk => chunk.type === 'usage');
-            expect(usageChunks.length).toBeGreaterThan(0);
-            expect(usageChunks[0].inputTokens).toBe(10);
-            expect(usageChunks[0].outputTokens).toBe(5);
-        });
-    });
-});
+const mockCreate = jest.fn()
+jest.mock("openai", () => {
+	return {
+		__esModule: true,
+		default: jest.fn().mockImplementation(() => ({
+			chat: {
+				completions: {
+					create: mockCreate.mockImplementation(async (options) => {
+						if (!options.stream) {
+							return {
+								id: "test-completion",
+								choices: [
+									{
+										message: { role: "assistant", content: "Test response", refusal: null },
+										finish_reason: "stop",
+										index: 0,
+									},
+								],
+								usage: {
+									prompt_tokens: 10,
+									completion_tokens: 5,
+									total_tokens: 15,
+								},
+							}
+						}
+
+						// Return async iterator for streaming
+						return {
+							[Symbol.asyncIterator]: async function* () {
+								yield {
+									choices: [
+										{
+											delta: { content: "Test response" },
+											index: 0,
+										},
+									],
+									usage: null,
+								}
+								yield {
+									choices: [
+										{
+											delta: {},
+											index: 0,
+										},
+									],
+									usage: {
+										prompt_tokens: 10,
+										completion_tokens: 5,
+										total_tokens: 15,
+									},
+								}
+							},
+						}
+					}),
+				},
+			},
+		})),
+	}
+})
+
+describe("DeepSeekHandler", () => {
+	let handler: DeepSeekHandler
+	let mockOptions: ApiHandlerOptions
+
+	beforeEach(() => {
+		mockOptions = {
+			deepSeekApiKey: "test-api-key",
+			deepSeekModelId: "deepseek-chat",
+			deepSeekBaseUrl: "https://api.deepseek.com/v1",
+		}
+		handler = new DeepSeekHandler(mockOptions)
+		mockCreate.mockClear()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(DeepSeekHandler)
+			expect(handler.getModel().id).toBe(mockOptions.deepSeekModelId)
+		})
+
+		it("should throw error if API key is missing", () => {
+			expect(() => {
+				new DeepSeekHandler({
+					...mockOptions,
+					deepSeekApiKey: undefined,
+				})
+			}).toThrow("DeepSeek API key is required")
+		})
+
+		it("should use default model ID if not provided", () => {
+			const handlerWithoutModel = new DeepSeekHandler({
+				...mockOptions,
+				deepSeekModelId: undefined,
+			})
+			expect(handlerWithoutModel.getModel().id).toBe(deepSeekDefaultModelId)
+		})
+
+		it("should use default base URL if not provided", () => {
+			const handlerWithoutBaseUrl = new DeepSeekHandler({
+				...mockOptions,
+				deepSeekBaseUrl: undefined,
+			})
+			expect(handlerWithoutBaseUrl).toBeInstanceOf(DeepSeekHandler)
+			// The base URL is passed to OpenAI client internally
+			expect(OpenAI).toHaveBeenCalledWith(
+				expect.objectContaining({
+					baseURL: "https://api.deepseek.com/v1",
+				}),
+			)
+		})
+
+		it("should use custom base URL if provided", () => {
+			const customBaseUrl = "https://custom.deepseek.com/v1"
+			const handlerWithCustomUrl = new DeepSeekHandler({
+				...mockOptions,
+				deepSeekBaseUrl: customBaseUrl,
+			})
+			expect(handlerWithCustomUrl).toBeInstanceOf(DeepSeekHandler)
+			// The custom base URL is passed to OpenAI client
+			expect(OpenAI).toHaveBeenCalledWith(
+				expect.objectContaining({
+					baseURL: customBaseUrl,
+				}),
+			)
+		})
+
+		it("should set includeMaxTokens to true", () => {
+			// Create a new handler and verify OpenAI client was called with includeMaxTokens
+			new DeepSeekHandler(mockOptions)
+			expect(OpenAI).toHaveBeenCalledWith(
+				expect.objectContaining({
+					apiKey: mockOptions.deepSeekApiKey,
+				}),
+			)
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info for valid model ID", () => {
+			const model = handler.getModel()
+			expect(model.id).toBe(mockOptions.deepSeekModelId)
+			expect(model.info).toBeDefined()
+			expect(model.info.maxTokens).toBe(8192)
+			expect(model.info.contextWindow).toBe(64_000)
+			expect(model.info.supportsImages).toBe(false)
+			expect(model.info.supportsPromptCache).toBe(false)
+		})
+
+		it("should return provided model ID with default model info if model does not exist", () => {
+			const handlerWithInvalidModel = new DeepSeekHandler({
+				...mockOptions,
+				deepSeekModelId: "invalid-model",
+			})
+			const model = handlerWithInvalidModel.getModel()
+			expect(model.id).toBe("invalid-model") // Returns provided ID
+			expect(model.info).toBeDefined()
+			expect(model.info).toBe(handler.getModel().info) // But uses default model info
+		})
+
+		it("should return default model if no model ID is provided", () => {
+			const handlerWithoutModel = new DeepSeekHandler({
+				...mockOptions,
+				deepSeekModelId: undefined,
+			})
+			const model = handlerWithoutModel.getModel()
+			expect(model.id).toBe(deepSeekDefaultModelId)
+			expect(model.info).toBeDefined()
+		})
+	})
+
+	describe("createMessage", () => {
+		const systemPrompt = "You are a helpful assistant."
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: [
+					{
+						type: "text" as const,
+						text: "Hello!",
+					},
+				],
+			},
+		]
+
+		it("should handle streaming responses", async () => {
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			const textChunks = chunks.filter((chunk) => chunk.type === "text")
+			expect(textChunks).toHaveLength(1)
+			expect(textChunks[0].text).toBe("Test response")
+		})
+
+		it("should include usage information", async () => {
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			const usageChunks = chunks.filter((chunk) => chunk.type === "usage")
+			expect(usageChunks.length).toBeGreaterThan(0)
+			expect(usageChunks[0].inputTokens).toBe(10)
+			expect(usageChunks[0].outputTokens).toBe(5)
+		})
+	})
+})

+ 208 - 210
src/api/providers/__tests__/gemini.test.ts

@@ -1,212 +1,210 @@
-import { GeminiHandler } from '../gemini';
-import { Anthropic } from '@anthropic-ai/sdk';
-import { GoogleGenerativeAI } from '@google/generative-ai';
+import { GeminiHandler } from "../gemini"
+import { Anthropic } from "@anthropic-ai/sdk"
+import { GoogleGenerativeAI } from "@google/generative-ai"
 
 // Mock the Google Generative AI SDK
-jest.mock('@google/generative-ai', () => ({
-    GoogleGenerativeAI: jest.fn().mockImplementation(() => ({
-        getGenerativeModel: jest.fn().mockReturnValue({
-            generateContentStream: jest.fn(),
-            generateContent: jest.fn().mockResolvedValue({
-                response: {
-                    text: () => 'Test response'
-                }
-            })
-        })
-    }))
-}));
-
-describe('GeminiHandler', () => {
-    let handler: GeminiHandler;
-
-    beforeEach(() => {
-        handler = new GeminiHandler({
-            apiKey: 'test-key',
-            apiModelId: 'gemini-2.0-flash-thinking-exp-1219',
-            geminiApiKey: 'test-key'
-        });
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided config', () => {
-            expect(handler['options'].geminiApiKey).toBe('test-key');
-            expect(handler['options'].apiModelId).toBe('gemini-2.0-flash-thinking-exp-1219');
-        });
-
-        it('should throw if API key is missing', () => {
-            expect(() => {
-                new GeminiHandler({
-                    apiModelId: 'gemini-2.0-flash-thinking-exp-1219',
-                    geminiApiKey: ''
-                });
-            }).toThrow('API key is required for Google Gemini');
-        });
-    });
-
-    describe('createMessage', () => {
-        const mockMessages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: 'Hello'
-            },
-            {
-                role: 'assistant',
-                content: 'Hi there!'
-            }
-        ];
-
-        const systemPrompt = 'You are a helpful assistant';
-
-        it('should handle text messages correctly', async () => {
-            // Mock the stream response
-            const mockStream = {
-                stream: [
-                    { text: () => 'Hello' },
-                    { text: () => ' world!' }
-                ],
-                response: {
-                    usageMetadata: {
-                        promptTokenCount: 10,
-                        candidatesTokenCount: 5
-                    }
-                }
-            };
-
-            // Setup the mock implementation
-            const mockGenerateContentStream = jest.fn().mockResolvedValue(mockStream);
-            const mockGetGenerativeModel = jest.fn().mockReturnValue({
-                generateContentStream: mockGenerateContentStream
-            });
-
-            (handler['client'] as any).getGenerativeModel = mockGetGenerativeModel;
-
-            const stream = handler.createMessage(systemPrompt, mockMessages);
-            const chunks = [];
-            
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            // Should have 3 chunks: 'Hello', ' world!', and usage info
-            expect(chunks.length).toBe(3);
-            expect(chunks[0]).toEqual({
-                type: 'text',
-                text: 'Hello'
-            });
-            expect(chunks[1]).toEqual({
-                type: 'text',
-                text: ' world!'
-            });
-            expect(chunks[2]).toEqual({
-                type: 'usage',
-                inputTokens: 10,
-                outputTokens: 5
-            });
-
-            // Verify the model configuration
-            expect(mockGetGenerativeModel).toHaveBeenCalledWith({
-                model: 'gemini-2.0-flash-thinking-exp-1219',
-                systemInstruction: systemPrompt
-            });
-
-            // Verify generation config
-            expect(mockGenerateContentStream).toHaveBeenCalledWith(
-                expect.objectContaining({
-                    generationConfig: {
-                        temperature: 0
-                    }
-                })
-            );
-        });
-
-        it('should handle API errors', async () => {
-            const mockError = new Error('Gemini API error');
-            const mockGenerateContentStream = jest.fn().mockRejectedValue(mockError);
-            const mockGetGenerativeModel = jest.fn().mockReturnValue({
-                generateContentStream: mockGenerateContentStream
-            });
-
-            (handler['client'] as any).getGenerativeModel = mockGetGenerativeModel;
-
-            const stream = handler.createMessage(systemPrompt, mockMessages);
-
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should throw before yielding any chunks
-                }
-            }).rejects.toThrow('Gemini API error');
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const mockGenerateContent = jest.fn().mockResolvedValue({
-                response: {
-                    text: () => 'Test response'
-                }
-            });
-            const mockGetGenerativeModel = jest.fn().mockReturnValue({
-                generateContent: mockGenerateContent
-            });
-            (handler['client'] as any).getGenerativeModel = mockGetGenerativeModel;
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockGetGenerativeModel).toHaveBeenCalledWith({
-                model: 'gemini-2.0-flash-thinking-exp-1219'
-            });
-            expect(mockGenerateContent).toHaveBeenCalledWith({
-                contents: [{ role: 'user', parts: [{ text: 'Test prompt' }] }],
-                generationConfig: {
-                    temperature: 0
-                }
-            });
-        });
-
-        it('should handle API errors', async () => {
-            const mockError = new Error('Gemini API error');
-            const mockGenerateContent = jest.fn().mockRejectedValue(mockError);
-            const mockGetGenerativeModel = jest.fn().mockReturnValue({
-                generateContent: mockGenerateContent
-            });
-            (handler['client'] as any).getGenerativeModel = mockGetGenerativeModel;
-
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Gemini completion error: Gemini API error');
-        });
-
-        it('should handle empty response', async () => {
-            const mockGenerateContent = jest.fn().mockResolvedValue({
-                response: {
-                    text: () => ''
-                }
-            });
-            const mockGetGenerativeModel = jest.fn().mockReturnValue({
-                generateContent: mockGenerateContent
-            });
-            (handler['client'] as any).getGenerativeModel = mockGetGenerativeModel;
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return correct model info', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe('gemini-2.0-flash-thinking-exp-1219');
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(8192);
-            expect(modelInfo.info.contextWindow).toBe(32_767);
-        });
-
-        it('should return default model if invalid model specified', () => {
-            const invalidHandler = new GeminiHandler({
-                apiModelId: 'invalid-model',
-                geminiApiKey: 'test-key'
-            });
-            const modelInfo = invalidHandler.getModel();
-            expect(modelInfo.id).toBe('gemini-2.0-flash-thinking-exp-1219'); // Default model
-        });
-    });
-});
+jest.mock("@google/generative-ai", () => ({
+	GoogleGenerativeAI: jest.fn().mockImplementation(() => ({
+		getGenerativeModel: jest.fn().mockReturnValue({
+			generateContentStream: jest.fn(),
+			generateContent: jest.fn().mockResolvedValue({
+				response: {
+					text: () => "Test response",
+				},
+			}),
+		}),
+	})),
+}))
+
+describe("GeminiHandler", () => {
+	let handler: GeminiHandler
+
+	beforeEach(() => {
+		handler = new GeminiHandler({
+			apiKey: "test-key",
+			apiModelId: "gemini-2.0-flash-thinking-exp-1219",
+			geminiApiKey: "test-key",
+		})
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided config", () => {
+			expect(handler["options"].geminiApiKey).toBe("test-key")
+			expect(handler["options"].apiModelId).toBe("gemini-2.0-flash-thinking-exp-1219")
+		})
+
+		it("should throw if API key is missing", () => {
+			expect(() => {
+				new GeminiHandler({
+					apiModelId: "gemini-2.0-flash-thinking-exp-1219",
+					geminiApiKey: "",
+				})
+			}).toThrow("API key is required for Google Gemini")
+		})
+	})
+
+	describe("createMessage", () => {
+		const mockMessages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: "Hello",
+			},
+			{
+				role: "assistant",
+				content: "Hi there!",
+			},
+		]
+
+		const systemPrompt = "You are a helpful assistant"
+
+		it("should handle text messages correctly", async () => {
+			// Mock the stream response
+			const mockStream = {
+				stream: [{ text: () => "Hello" }, { text: () => " world!" }],
+				response: {
+					usageMetadata: {
+						promptTokenCount: 10,
+						candidatesTokenCount: 5,
+					},
+				},
+			}
+
+			// Setup the mock implementation
+			const mockGenerateContentStream = jest.fn().mockResolvedValue(mockStream)
+			const mockGetGenerativeModel = jest.fn().mockReturnValue({
+				generateContentStream: mockGenerateContentStream,
+			})
+
+			;(handler["client"] as any).getGenerativeModel = mockGetGenerativeModel
+
+			const stream = handler.createMessage(systemPrompt, mockMessages)
+			const chunks = []
+
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			// Should have 3 chunks: 'Hello', ' world!', and usage info
+			expect(chunks.length).toBe(3)
+			expect(chunks[0]).toEqual({
+				type: "text",
+				text: "Hello",
+			})
+			expect(chunks[1]).toEqual({
+				type: "text",
+				text: " world!",
+			})
+			expect(chunks[2]).toEqual({
+				type: "usage",
+				inputTokens: 10,
+				outputTokens: 5,
+			})
+
+			// Verify the model configuration
+			expect(mockGetGenerativeModel).toHaveBeenCalledWith({
+				model: "gemini-2.0-flash-thinking-exp-1219",
+				systemInstruction: systemPrompt,
+			})
+
+			// Verify generation config
+			expect(mockGenerateContentStream).toHaveBeenCalledWith(
+				expect.objectContaining({
+					generationConfig: {
+						temperature: 0,
+					},
+				}),
+			)
+		})
+
+		it("should handle API errors", async () => {
+			const mockError = new Error("Gemini API error")
+			const mockGenerateContentStream = jest.fn().mockRejectedValue(mockError)
+			const mockGetGenerativeModel = jest.fn().mockReturnValue({
+				generateContentStream: mockGenerateContentStream,
+			})
+
+			;(handler["client"] as any).getGenerativeModel = mockGetGenerativeModel
+
+			const stream = handler.createMessage(systemPrompt, mockMessages)
+
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should throw before yielding any chunks
+				}
+			}).rejects.toThrow("Gemini API error")
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const mockGenerateContent = jest.fn().mockResolvedValue({
+				response: {
+					text: () => "Test response",
+				},
+			})
+			const mockGetGenerativeModel = jest.fn().mockReturnValue({
+				generateContent: mockGenerateContent,
+			})
+			;(handler["client"] as any).getGenerativeModel = mockGetGenerativeModel
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockGetGenerativeModel).toHaveBeenCalledWith({
+				model: "gemini-2.0-flash-thinking-exp-1219",
+			})
+			expect(mockGenerateContent).toHaveBeenCalledWith({
+				contents: [{ role: "user", parts: [{ text: "Test prompt" }] }],
+				generationConfig: {
+					temperature: 0,
+				},
+			})
+		})
+
+		it("should handle API errors", async () => {
+			const mockError = new Error("Gemini API error")
+			const mockGenerateContent = jest.fn().mockRejectedValue(mockError)
+			const mockGetGenerativeModel = jest.fn().mockReturnValue({
+				generateContent: mockGenerateContent,
+			})
+			;(handler["client"] as any).getGenerativeModel = mockGetGenerativeModel
+
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow(
+				"Gemini completion error: Gemini API error",
+			)
+		})
+
+		it("should handle empty response", async () => {
+			const mockGenerateContent = jest.fn().mockResolvedValue({
+				response: {
+					text: () => "",
+				},
+			})
+			const mockGetGenerativeModel = jest.fn().mockReturnValue({
+				generateContent: mockGenerateContent,
+			})
+			;(handler["client"] as any).getGenerativeModel = mockGetGenerativeModel
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return correct model info", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe("gemini-2.0-flash-thinking-exp-1219")
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(8192)
+			expect(modelInfo.info.contextWindow).toBe(32_767)
+		})
+
+		it("should return default model if invalid model specified", () => {
+			const invalidHandler = new GeminiHandler({
+				apiModelId: "invalid-model",
+				geminiApiKey: "test-key",
+			})
+			const modelInfo = invalidHandler.getModel()
+			expect(modelInfo.id).toBe("gemini-2.0-flash-thinking-exp-1219") // Default model
+		})
+	})
+})

+ 236 - 224
src/api/providers/__tests__/glama.test.ts

@@ -1,226 +1,238 @@
-import { GlamaHandler } from '../glama';
-import { ApiHandlerOptions } from '../../../shared/api';
-import OpenAI from 'openai';
-import { Anthropic } from '@anthropic-ai/sdk';
-import axios from 'axios';
+import { GlamaHandler } from "../glama"
+import { ApiHandlerOptions } from "../../../shared/api"
+import OpenAI from "openai"
+import { Anthropic } from "@anthropic-ai/sdk"
+import axios from "axios"
 
 // Mock OpenAI client
-const mockCreate = jest.fn();
-const mockWithResponse = jest.fn();
-
-jest.mock('openai', () => {
-    return {
-        __esModule: true,
-        default: jest.fn().mockImplementation(() => ({
-            chat: {
-                completions: {
-                    create: (...args: any[]) => {
-                        const stream = {
-                            [Symbol.asyncIterator]: async function* () {
-                                yield {
-                                    choices: [{
-                                        delta: { content: 'Test response' },
-                                        index: 0
-                                    }],
-                                    usage: null
-                                };
-                                yield {
-                                    choices: [{
-                                        delta: {},
-                                        index: 0
-                                    }],
-                                    usage: {
-                                        prompt_tokens: 10,
-                                        completion_tokens: 5,
-                                        total_tokens: 15
-                                    }
-                                };
-                            }
-                        };
-
-                        const result = mockCreate(...args);
-                        if (args[0].stream) {
-                            mockWithResponse.mockReturnValue(Promise.resolve({
-                                data: stream,
-                                response: {
-                                    headers: {
-                                        get: (name: string) => name === 'x-completion-request-id' ? 'test-request-id' : null
-                                    }
-                                }
-                            }));
-                            result.withResponse = mockWithResponse;
-                        }
-                        return result;
-                    }
-                }
-            }
-        }))
-    };
-});
-
-describe('GlamaHandler', () => {
-    let handler: GlamaHandler;
-    let mockOptions: ApiHandlerOptions;
-
-    beforeEach(() => {
-        mockOptions = {
-            apiModelId: 'anthropic/claude-3-5-sonnet',
-            glamaModelId: 'anthropic/claude-3-5-sonnet',
-            glamaApiKey: 'test-api-key'
-        };
-        handler = new GlamaHandler(mockOptions);
-        mockCreate.mockClear();
-        mockWithResponse.mockClear();
-
-        // Default mock implementation for non-streaming responses
-        mockCreate.mockResolvedValue({
-            id: 'test-completion',
-            choices: [{
-                message: { role: 'assistant', content: 'Test response' },
-                finish_reason: 'stop',
-                index: 0
-            }],
-            usage: {
-                prompt_tokens: 10,
-                completion_tokens: 5,
-                total_tokens: 15
-            }
-        });
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(GlamaHandler);
-            expect(handler.getModel().id).toBe(mockOptions.apiModelId);
-        });
-    });
-
-    describe('createMessage', () => {
-        const systemPrompt = 'You are a helpful assistant.';
-        const messages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: 'Hello!'
-            }
-        ];
-
-        it('should handle streaming responses', async () => {
-            // Mock axios for token usage request
-            const mockAxios = jest.spyOn(axios, 'get').mockResolvedValueOnce({
-                data: {
-                    tokenUsage: {
-                        promptTokens: 10,
-                        completionTokens: 5,
-                        cacheCreationInputTokens: 0,
-                        cacheReadInputTokens: 0
-                    },
-                    totalCostUsd: "0.00"
-                }
-            });
-
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBe(2); // Text chunk and usage chunk
-            expect(chunks[0]).toEqual({
-                type: 'text',
-                text: 'Test response'
-            });
-            expect(chunks[1]).toEqual({
-                type: 'usage',
-                inputTokens: 10,
-                outputTokens: 5,
-                cacheWriteTokens: 0,
-                cacheReadTokens: 0,
-                totalCost: 0
-            });
-
-            mockAxios.mockRestore();
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockImplementationOnce(() => {
-                throw new Error('API Error');
-            });
-
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks = [];
-
-            try {
-                for await (const chunk of stream) {
-                    chunks.push(chunk);
-                }
-                fail('Expected error to be thrown');
-            } catch (error) {
-                expect(error).toBeInstanceOf(Error);
-                expect(error.message).toBe('API Error');
-            }
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({
-                model: mockOptions.apiModelId,
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                temperature: 0,
-                max_tokens: 8192
-            }));
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Glama completion error: API Error');
-        });
-
-        it('should handle empty response', async () => {
-            mockCreate.mockResolvedValueOnce({
-                choices: [{ message: { content: '' } }]
-            });
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-
-        it('should not set max_tokens for non-Anthropic models', async () => {
-            // Reset mock to clear any previous calls
-            mockCreate.mockClear();
-            
-            const nonAnthropicOptions = {
-                apiModelId: 'openai/gpt-4',
-                glamaModelId: 'openai/gpt-4',
-                glamaApiKey: 'test-key',
-                glamaModelInfo: {
-                    maxTokens: 4096,
-                    contextWindow: 8192,
-                    supportsImages: true,
-                    supportsPromptCache: false
-                }
-            };
-            const nonAnthropicHandler = new GlamaHandler(nonAnthropicOptions);
-
-            await nonAnthropicHandler.completePrompt('Test prompt');
-            expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({
-                model: 'openai/gpt-4',
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                temperature: 0
-            }));
-            expect(mockCreate.mock.calls[0][0]).not.toHaveProperty('max_tokens');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return model info', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe(mockOptions.apiModelId);
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(8192);
-            expect(modelInfo.info.contextWindow).toBe(200_000);
-        });
-    });
-});
+const mockCreate = jest.fn()
+const mockWithResponse = jest.fn()
+
+jest.mock("openai", () => {
+	return {
+		__esModule: true,
+		default: jest.fn().mockImplementation(() => ({
+			chat: {
+				completions: {
+					create: (...args: any[]) => {
+						const stream = {
+							[Symbol.asyncIterator]: async function* () {
+								yield {
+									choices: [
+										{
+											delta: { content: "Test response" },
+											index: 0,
+										},
+									],
+									usage: null,
+								}
+								yield {
+									choices: [
+										{
+											delta: {},
+											index: 0,
+										},
+									],
+									usage: {
+										prompt_tokens: 10,
+										completion_tokens: 5,
+										total_tokens: 15,
+									},
+								}
+							},
+						}
+
+						const result = mockCreate(...args)
+						if (args[0].stream) {
+							mockWithResponse.mockReturnValue(
+								Promise.resolve({
+									data: stream,
+									response: {
+										headers: {
+											get: (name: string) =>
+												name === "x-completion-request-id" ? "test-request-id" : null,
+										},
+									},
+								}),
+							)
+							result.withResponse = mockWithResponse
+						}
+						return result
+					},
+				},
+			},
+		})),
+	}
+})
+
+describe("GlamaHandler", () => {
+	let handler: GlamaHandler
+	let mockOptions: ApiHandlerOptions
+
+	beforeEach(() => {
+		mockOptions = {
+			apiModelId: "anthropic/claude-3-5-sonnet",
+			glamaModelId: "anthropic/claude-3-5-sonnet",
+			glamaApiKey: "test-api-key",
+		}
+		handler = new GlamaHandler(mockOptions)
+		mockCreate.mockClear()
+		mockWithResponse.mockClear()
+
+		// Default mock implementation for non-streaming responses
+		mockCreate.mockResolvedValue({
+			id: "test-completion",
+			choices: [
+				{
+					message: { role: "assistant", content: "Test response" },
+					finish_reason: "stop",
+					index: 0,
+				},
+			],
+			usage: {
+				prompt_tokens: 10,
+				completion_tokens: 5,
+				total_tokens: 15,
+			},
+		})
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(GlamaHandler)
+			expect(handler.getModel().id).toBe(mockOptions.apiModelId)
+		})
+	})
+
+	describe("createMessage", () => {
+		const systemPrompt = "You are a helpful assistant."
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: "Hello!",
+			},
+		]
+
+		it("should handle streaming responses", async () => {
+			// Mock axios for token usage request
+			const mockAxios = jest.spyOn(axios, "get").mockResolvedValueOnce({
+				data: {
+					tokenUsage: {
+						promptTokens: 10,
+						completionTokens: 5,
+						cacheCreationInputTokens: 0,
+						cacheReadInputTokens: 0,
+					},
+					totalCostUsd: "0.00",
+				},
+			})
+
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBe(2) // Text chunk and usage chunk
+			expect(chunks[0]).toEqual({
+				type: "text",
+				text: "Test response",
+			})
+			expect(chunks[1]).toEqual({
+				type: "usage",
+				inputTokens: 10,
+				outputTokens: 5,
+				cacheWriteTokens: 0,
+				cacheReadTokens: 0,
+				totalCost: 0,
+			})
+
+			mockAxios.mockRestore()
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockImplementationOnce(() => {
+				throw new Error("API Error")
+			})
+
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks = []
+
+			try {
+				for await (const chunk of stream) {
+					chunks.push(chunk)
+				}
+				fail("Expected error to be thrown")
+			} catch (error) {
+				expect(error).toBeInstanceOf(Error)
+				expect(error.message).toBe("API Error")
+			}
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith(
+				expect.objectContaining({
+					model: mockOptions.apiModelId,
+					messages: [{ role: "user", content: "Test prompt" }],
+					temperature: 0,
+					max_tokens: 8192,
+				}),
+			)
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow("Glama completion error: API Error")
+		})
+
+		it("should handle empty response", async () => {
+			mockCreate.mockResolvedValueOnce({
+				choices: [{ message: { content: "" } }],
+			})
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+
+		it("should not set max_tokens for non-Anthropic models", async () => {
+			// Reset mock to clear any previous calls
+			mockCreate.mockClear()
+
+			const nonAnthropicOptions = {
+				apiModelId: "openai/gpt-4",
+				glamaModelId: "openai/gpt-4",
+				glamaApiKey: "test-key",
+				glamaModelInfo: {
+					maxTokens: 4096,
+					contextWindow: 8192,
+					supportsImages: true,
+					supportsPromptCache: false,
+				},
+			}
+			const nonAnthropicHandler = new GlamaHandler(nonAnthropicOptions)
+
+			await nonAnthropicHandler.completePrompt("Test prompt")
+			expect(mockCreate).toHaveBeenCalledWith(
+				expect.objectContaining({
+					model: "openai/gpt-4",
+					messages: [{ role: "user", content: "Test prompt" }],
+					temperature: 0,
+				}),
+			)
+			expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("max_tokens")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe(mockOptions.apiModelId)
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(8192)
+			expect(modelInfo.info.contextWindow).toBe(200_000)
+		})
+	})
+})

+ 165 - 158
src/api/providers/__tests__/lmstudio.test.ts

@@ -1,160 +1,167 @@
-import { LmStudioHandler } from '../lmstudio';
-import { ApiHandlerOptions } from '../../../shared/api';
-import OpenAI from 'openai';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { LmStudioHandler } from "../lmstudio"
+import { ApiHandlerOptions } from "../../../shared/api"
+import OpenAI from "openai"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock OpenAI client
-const mockCreate = jest.fn();
-jest.mock('openai', () => {
-    return {
-        __esModule: true,
-        default: jest.fn().mockImplementation(() => ({
-            chat: {
-                completions: {
-                    create: mockCreate.mockImplementation(async (options) => {
-                        if (!options.stream) {
-                            return {
-                                id: 'test-completion',
-                                choices: [{
-                                    message: { role: 'assistant', content: 'Test response' },
-                                    finish_reason: 'stop',
-                                    index: 0
-                                }],
-                                usage: {
-                                    prompt_tokens: 10,
-                                    completion_tokens: 5,
-                                    total_tokens: 15
-                                }
-                            };
-                        }
-                        
-                        return {
-                            [Symbol.asyncIterator]: async function* () {
-                                yield {
-                                    choices: [{
-                                        delta: { content: 'Test response' },
-                                        index: 0
-                                    }],
-                                    usage: null
-                                };
-                                yield {
-                                    choices: [{
-                                        delta: {},
-                                        index: 0
-                                    }],
-                                    usage: {
-                                        prompt_tokens: 10,
-                                        completion_tokens: 5,
-                                        total_tokens: 15
-                                    }
-                                };
-                            }
-                        };
-                    })
-                }
-            }
-        }))
-    };
-});
-
-describe('LmStudioHandler', () => {
-    let handler: LmStudioHandler;
-    let mockOptions: ApiHandlerOptions;
-
-    beforeEach(() => {
-        mockOptions = {
-            apiModelId: 'local-model',
-            lmStudioModelId: 'local-model',
-            lmStudioBaseUrl: 'http://localhost:1234/v1'
-        };
-        handler = new LmStudioHandler(mockOptions);
-        mockCreate.mockClear();
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(LmStudioHandler);
-            expect(handler.getModel().id).toBe(mockOptions.lmStudioModelId);
-        });
-
-        it('should use default base URL if not provided', () => {
-            const handlerWithoutUrl = new LmStudioHandler({
-                apiModelId: 'local-model',
-                lmStudioModelId: 'local-model'
-            });
-            expect(handlerWithoutUrl).toBeInstanceOf(LmStudioHandler);
-        });
-    });
-
-    describe('createMessage', () => {
-        const systemPrompt = 'You are a helpful assistant.';
-        const messages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: 'Hello!'
-            }
-        ];
-
-        it('should handle streaming responses', async () => {
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            const textChunks = chunks.filter(chunk => chunk.type === 'text');
-            expect(textChunks).toHaveLength(1);
-            expect(textChunks[0].text).toBe('Test response');
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-
-            const stream = handler.createMessage(systemPrompt, messages);
-
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should not reach here
-                }
-            }).rejects.toThrow('Please check the LM Studio developer logs to debug what went wrong');
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: mockOptions.lmStudioModelId,
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                temperature: 0,
-                stream: false
-            });
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Please check the LM Studio developer logs to debug what went wrong');
-        });
-
-        it('should handle empty response', async () => {
-            mockCreate.mockResolvedValueOnce({
-                choices: [{ message: { content: '' } }]
-            });
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return model info', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe(mockOptions.lmStudioModelId);
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(-1);
-            expect(modelInfo.info.contextWindow).toBe(128_000);
-        });
-    });
-});
+const mockCreate = jest.fn()
+jest.mock("openai", () => {
+	return {
+		__esModule: true,
+		default: jest.fn().mockImplementation(() => ({
+			chat: {
+				completions: {
+					create: mockCreate.mockImplementation(async (options) => {
+						if (!options.stream) {
+							return {
+								id: "test-completion",
+								choices: [
+									{
+										message: { role: "assistant", content: "Test response" },
+										finish_reason: "stop",
+										index: 0,
+									},
+								],
+								usage: {
+									prompt_tokens: 10,
+									completion_tokens: 5,
+									total_tokens: 15,
+								},
+							}
+						}
+
+						return {
+							[Symbol.asyncIterator]: async function* () {
+								yield {
+									choices: [
+										{
+											delta: { content: "Test response" },
+											index: 0,
+										},
+									],
+									usage: null,
+								}
+								yield {
+									choices: [
+										{
+											delta: {},
+											index: 0,
+										},
+									],
+									usage: {
+										prompt_tokens: 10,
+										completion_tokens: 5,
+										total_tokens: 15,
+									},
+								}
+							},
+						}
+					}),
+				},
+			},
+		})),
+	}
+})
+
+describe("LmStudioHandler", () => {
+	let handler: LmStudioHandler
+	let mockOptions: ApiHandlerOptions
+
+	beforeEach(() => {
+		mockOptions = {
+			apiModelId: "local-model",
+			lmStudioModelId: "local-model",
+			lmStudioBaseUrl: "http://localhost:1234/v1",
+		}
+		handler = new LmStudioHandler(mockOptions)
+		mockCreate.mockClear()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(LmStudioHandler)
+			expect(handler.getModel().id).toBe(mockOptions.lmStudioModelId)
+		})
+
+		it("should use default base URL if not provided", () => {
+			const handlerWithoutUrl = new LmStudioHandler({
+				apiModelId: "local-model",
+				lmStudioModelId: "local-model",
+			})
+			expect(handlerWithoutUrl).toBeInstanceOf(LmStudioHandler)
+		})
+	})
+
+	describe("createMessage", () => {
+		const systemPrompt = "You are a helpful assistant."
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: "Hello!",
+			},
+		]
+
+		it("should handle streaming responses", async () => {
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			const textChunks = chunks.filter((chunk) => chunk.type === "text")
+			expect(textChunks).toHaveLength(1)
+			expect(textChunks[0].text).toBe("Test response")
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+
+			const stream = handler.createMessage(systemPrompt, messages)
+
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should not reach here
+				}
+			}).rejects.toThrow("Please check the LM Studio developer logs to debug what went wrong")
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: mockOptions.lmStudioModelId,
+				messages: [{ role: "user", content: "Test prompt" }],
+				temperature: 0,
+				stream: false,
+			})
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow(
+				"Please check the LM Studio developer logs to debug what went wrong",
+			)
+		})
+
+		it("should handle empty response", async () => {
+			mockCreate.mockResolvedValueOnce({
+				choices: [{ message: { content: "" } }],
+			})
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe(mockOptions.lmStudioModelId)
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(-1)
+			expect(modelInfo.info.contextWindow).toBe(128_000)
+		})
+	})
+})

+ 163 - 158
src/api/providers/__tests__/ollama.test.ts

@@ -1,160 +1,165 @@
-import { OllamaHandler } from '../ollama';
-import { ApiHandlerOptions } from '../../../shared/api';
-import OpenAI from 'openai';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { OllamaHandler } from "../ollama"
+import { ApiHandlerOptions } from "../../../shared/api"
+import OpenAI from "openai"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock OpenAI client
-const mockCreate = jest.fn();
-jest.mock('openai', () => {
-    return {
-        __esModule: true,
-        default: jest.fn().mockImplementation(() => ({
-            chat: {
-                completions: {
-                    create: mockCreate.mockImplementation(async (options) => {
-                        if (!options.stream) {
-                            return {
-                                id: 'test-completion',
-                                choices: [{
-                                    message: { role: 'assistant', content: 'Test response' },
-                                    finish_reason: 'stop',
-                                    index: 0
-                                }],
-                                usage: {
-                                    prompt_tokens: 10,
-                                    completion_tokens: 5,
-                                    total_tokens: 15
-                                }
-                            };
-                        }
-                        
-                        return {
-                            [Symbol.asyncIterator]: async function* () {
-                                yield {
-                                    choices: [{
-                                        delta: { content: 'Test response' },
-                                        index: 0
-                                    }],
-                                    usage: null
-                                };
-                                yield {
-                                    choices: [{
-                                        delta: {},
-                                        index: 0
-                                    }],
-                                    usage: {
-                                        prompt_tokens: 10,
-                                        completion_tokens: 5,
-                                        total_tokens: 15
-                                    }
-                                };
-                            }
-                        };
-                    })
-                }
-            }
-        }))
-    };
-});
-
-describe('OllamaHandler', () => {
-    let handler: OllamaHandler;
-    let mockOptions: ApiHandlerOptions;
-
-    beforeEach(() => {
-        mockOptions = {
-            apiModelId: 'llama2',
-            ollamaModelId: 'llama2',
-            ollamaBaseUrl: 'http://localhost:11434/v1'
-        };
-        handler = new OllamaHandler(mockOptions);
-        mockCreate.mockClear();
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(OllamaHandler);
-            expect(handler.getModel().id).toBe(mockOptions.ollamaModelId);
-        });
-
-        it('should use default base URL if not provided', () => {
-            const handlerWithoutUrl = new OllamaHandler({
-                apiModelId: 'llama2',
-                ollamaModelId: 'llama2'
-            });
-            expect(handlerWithoutUrl).toBeInstanceOf(OllamaHandler);
-        });
-    });
-
-    describe('createMessage', () => {
-        const systemPrompt = 'You are a helpful assistant.';
-        const messages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: 'Hello!'
-            }
-        ];
-
-        it('should handle streaming responses', async () => {
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            const textChunks = chunks.filter(chunk => chunk.type === 'text');
-            expect(textChunks).toHaveLength(1);
-            expect(textChunks[0].text).toBe('Test response');
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-
-            const stream = handler.createMessage(systemPrompt, messages);
-
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should not reach here
-                }
-            }).rejects.toThrow('API Error');
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: mockOptions.ollamaModelId,
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                temperature: 0,
-                stream: false
-            });
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Ollama completion error: API Error');
-        });
-
-        it('should handle empty response', async () => {
-            mockCreate.mockResolvedValueOnce({
-                choices: [{ message: { content: '' } }]
-            });
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return model info', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe(mockOptions.ollamaModelId);
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(-1);
-            expect(modelInfo.info.contextWindow).toBe(128_000);
-        });
-    });
-});
+const mockCreate = jest.fn()
+jest.mock("openai", () => {
+	return {
+		__esModule: true,
+		default: jest.fn().mockImplementation(() => ({
+			chat: {
+				completions: {
+					create: mockCreate.mockImplementation(async (options) => {
+						if (!options.stream) {
+							return {
+								id: "test-completion",
+								choices: [
+									{
+										message: { role: "assistant", content: "Test response" },
+										finish_reason: "stop",
+										index: 0,
+									},
+								],
+								usage: {
+									prompt_tokens: 10,
+									completion_tokens: 5,
+									total_tokens: 15,
+								},
+							}
+						}
+
+						return {
+							[Symbol.asyncIterator]: async function* () {
+								yield {
+									choices: [
+										{
+											delta: { content: "Test response" },
+											index: 0,
+										},
+									],
+									usage: null,
+								}
+								yield {
+									choices: [
+										{
+											delta: {},
+											index: 0,
+										},
+									],
+									usage: {
+										prompt_tokens: 10,
+										completion_tokens: 5,
+										total_tokens: 15,
+									},
+								}
+							},
+						}
+					}),
+				},
+			},
+		})),
+	}
+})
+
+describe("OllamaHandler", () => {
+	let handler: OllamaHandler
+	let mockOptions: ApiHandlerOptions
+
+	beforeEach(() => {
+		mockOptions = {
+			apiModelId: "llama2",
+			ollamaModelId: "llama2",
+			ollamaBaseUrl: "http://localhost:11434/v1",
+		}
+		handler = new OllamaHandler(mockOptions)
+		mockCreate.mockClear()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(OllamaHandler)
+			expect(handler.getModel().id).toBe(mockOptions.ollamaModelId)
+		})
+
+		it("should use default base URL if not provided", () => {
+			const handlerWithoutUrl = new OllamaHandler({
+				apiModelId: "llama2",
+				ollamaModelId: "llama2",
+			})
+			expect(handlerWithoutUrl).toBeInstanceOf(OllamaHandler)
+		})
+	})
+
+	describe("createMessage", () => {
+		const systemPrompt = "You are a helpful assistant."
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: "Hello!",
+			},
+		]
+
+		it("should handle streaming responses", async () => {
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			const textChunks = chunks.filter((chunk) => chunk.type === "text")
+			expect(textChunks).toHaveLength(1)
+			expect(textChunks[0].text).toBe("Test response")
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+
+			const stream = handler.createMessage(systemPrompt, messages)
+
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should not reach here
+				}
+			}).rejects.toThrow("API Error")
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: mockOptions.ollamaModelId,
+				messages: [{ role: "user", content: "Test prompt" }],
+				temperature: 0,
+				stream: false,
+			})
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow("Ollama completion error: API Error")
+		})
+
+		it("should handle empty response", async () => {
+			mockCreate.mockResolvedValueOnce({
+				choices: [{ message: { content: "" } }],
+			})
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe(mockOptions.ollamaModelId)
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(-1)
+			expect(modelInfo.info.contextWindow).toBe(128_000)
+		})
+	})
+})

+ 324 - 317
src/api/providers/__tests__/openai-native.test.ts

@@ -1,319 +1,326 @@
-import { OpenAiNativeHandler } from '../openai-native';
-import { ApiHandlerOptions } from '../../../shared/api';
-import OpenAI from 'openai';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { OpenAiNativeHandler } from "../openai-native"
+import { ApiHandlerOptions } from "../../../shared/api"
+import OpenAI from "openai"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock OpenAI client
-const mockCreate = jest.fn();
-jest.mock('openai', () => {
-    return {
-        __esModule: true,
-        default: jest.fn().mockImplementation(() => ({
-            chat: {
-                completions: {
-                    create: mockCreate.mockImplementation(async (options) => {
-                        if (!options.stream) {
-                            return {
-                                id: 'test-completion',
-                                choices: [{
-                                    message: { role: 'assistant', content: 'Test response' },
-                                    finish_reason: 'stop',
-                                    index: 0
-                                }],
-                                usage: {
-                                    prompt_tokens: 10,
-                                    completion_tokens: 5,
-                                    total_tokens: 15
-                                }
-                            };
-                        }
-                        
-                        return {
-                            [Symbol.asyncIterator]: async function* () {
-                                yield {
-                                    choices: [{
-                                        delta: { content: 'Test response' },
-                                        index: 0
-                                    }],
-                                    usage: null
-                                };
-                                yield {
-                                    choices: [{
-                                        delta: {},
-                                        index: 0
-                                    }],
-                                    usage: {
-                                        prompt_tokens: 10,
-                                        completion_tokens: 5,
-                                        total_tokens: 15
-                                    }
-                                };
-                            }
-                        };
-                    })
-                }
-            }
-        }))
-    };
-});
-
-describe('OpenAiNativeHandler', () => {
-    let handler: OpenAiNativeHandler;
-    let mockOptions: ApiHandlerOptions;
-    const systemPrompt = 'You are a helpful assistant.';
-    const messages: Anthropic.Messages.MessageParam[] = [
-        {
-            role: 'user',
-            content: 'Hello!'
-        }
-    ];
-
-    beforeEach(() => {
-        mockOptions = {
-            apiModelId: 'gpt-4o',
-            openAiNativeApiKey: 'test-api-key'
-        };
-        handler = new OpenAiNativeHandler(mockOptions);
-        mockCreate.mockClear();
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(OpenAiNativeHandler);
-            expect(handler.getModel().id).toBe(mockOptions.apiModelId);
-        });
-
-        it('should initialize with empty API key', () => {
-            const handlerWithoutKey = new OpenAiNativeHandler({
-                apiModelId: 'gpt-4o',
-                openAiNativeApiKey: ''
-            });
-            expect(handlerWithoutKey).toBeInstanceOf(OpenAiNativeHandler);
-        });
-    });
-
-    describe('createMessage', () => {
-        it('should handle streaming responses', async () => {
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            const textChunks = chunks.filter(chunk => chunk.type === 'text');
-            expect(textChunks).toHaveLength(1);
-            expect(textChunks[0].text).toBe('Test response');
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            const stream = handler.createMessage(systemPrompt, messages);
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should not reach here
-                }
-            }).rejects.toThrow('API Error');
-        });
-
-        it('should handle missing content in response for o1 model', async () => {
-            // Use o1 model which supports developer role
-            handler = new OpenAiNativeHandler({
-                ...mockOptions,
-                apiModelId: 'o1'
-            });
-
-            mockCreate.mockResolvedValueOnce({
-                choices: [{ message: { content: null } }],
-                usage: {
-                    prompt_tokens: 0,
-                    completion_tokens: 0,
-                    total_tokens: 0
-                }
-            });
-
-            const generator = handler.createMessage(systemPrompt, messages);
-            const results = [];
-            for await (const result of generator) {
-                results.push(result);
-            }
-
-            expect(results).toEqual([
-                { type: 'text', text: '' },
-                { type: 'usage', inputTokens: 0, outputTokens: 0 }
-            ]);
-
-            // Verify developer role is used for system prompt with o1 model
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'o1',
-                messages: [
-                    { role: 'developer', content: systemPrompt },
-                    { role: 'user', content: 'Hello!' }
-                ]
-            });
-        });
-    });
-
-    describe('streaming models', () => {
-        beforeEach(() => {
-            handler = new OpenAiNativeHandler({
-                ...mockOptions,
-                apiModelId: 'gpt-4o',
-            });
-        });
-
-        it('should handle streaming response', async () => {
-            const mockStream = [
-                { choices: [{ delta: { content: 'Hello' } }], usage: null },
-                { choices: [{ delta: { content: ' there' } }], usage: null },
-                { choices: [{ delta: { content: '!' } }], usage: { prompt_tokens: 10, completion_tokens: 5 } },
-            ];
-
-            mockCreate.mockResolvedValueOnce(
-                (async function* () {
-                    for (const chunk of mockStream) {
-                        yield chunk;
-                    }
-                })()
-            );
-
-            const generator = handler.createMessage(systemPrompt, messages);
-            const results = [];
-            for await (const result of generator) {
-                results.push(result);
-            }
-
-            expect(results).toEqual([
-                { type: 'text', text: 'Hello' },
-                { type: 'text', text: ' there' },
-                { type: 'text', text: '!' },
-                { type: 'usage', inputTokens: 10, outputTokens: 5 },
-            ]);
-
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'gpt-4o',
-                temperature: 0,
-                messages: [
-                    { role: 'system', content: systemPrompt },
-                    { role: 'user', content: 'Hello!' },
-                ],
-                stream: true,
-                stream_options: { include_usage: true },
-            });
-        });
-
-        it('should handle empty delta content', async () => {
-            const mockStream = [
-                { choices: [{ delta: {} }], usage: null },
-                { choices: [{ delta: { content: null } }], usage: null },
-                { choices: [{ delta: { content: 'Hello' } }], usage: { prompt_tokens: 10, completion_tokens: 5 } },
-            ];
-
-            mockCreate.mockResolvedValueOnce(
-                (async function* () {
-                    for (const chunk of mockStream) {
-                        yield chunk;
-                    }
-                })()
-            );
-
-            const generator = handler.createMessage(systemPrompt, messages);
-            const results = [];
-            for await (const result of generator) {
-                results.push(result);
-            }
-
-            expect(results).toEqual([
-                { type: 'text', text: 'Hello' },
-                { type: 'usage', inputTokens: 10, outputTokens: 5 },
-            ]);
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully with gpt-4o model', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'gpt-4o',
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                temperature: 0
-            });
-        });
-
-        it('should complete prompt successfully with o1 model', async () => {
-            handler = new OpenAiNativeHandler({
-                apiModelId: 'o1',
-                openAiNativeApiKey: 'test-api-key'
-            });
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'o1',
-                messages: [{ role: 'user', content: 'Test prompt' }]
-            });
-        });
-
-        it('should complete prompt successfully with o1-preview model', async () => {
-            handler = new OpenAiNativeHandler({
-                apiModelId: 'o1-preview',
-                openAiNativeApiKey: 'test-api-key'
-            });
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'o1-preview',
-                messages: [{ role: 'user', content: 'Test prompt' }]
-            });
-        });
-
-        it('should complete prompt successfully with o1-mini model', async () => {
-            handler = new OpenAiNativeHandler({
-                apiModelId: 'o1-mini',
-                openAiNativeApiKey: 'test-api-key'
-            });
-
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'o1-mini',
-                messages: [{ role: 'user', content: 'Test prompt' }]
-            });
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('OpenAI Native completion error: API Error');
-        });
-
-        it('should handle empty response', async () => {
-            mockCreate.mockResolvedValueOnce({
-                choices: [{ message: { content: '' } }]
-            });
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return model info', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe(mockOptions.apiModelId);
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(4096);
-            expect(modelInfo.info.contextWindow).toBe(128_000);
-        });
-
-        it('should handle undefined model ID', () => {
-            const handlerWithoutModel = new OpenAiNativeHandler({
-                openAiNativeApiKey: 'test-api-key'
-            });
-            const modelInfo = handlerWithoutModel.getModel();
-            expect(modelInfo.id).toBe('gpt-4o'); // Default model
-            expect(modelInfo.info).toBeDefined();
-        });
-    });
-});
+const mockCreate = jest.fn()
+jest.mock("openai", () => {
+	return {
+		__esModule: true,
+		default: jest.fn().mockImplementation(() => ({
+			chat: {
+				completions: {
+					create: mockCreate.mockImplementation(async (options) => {
+						if (!options.stream) {
+							return {
+								id: "test-completion",
+								choices: [
+									{
+										message: { role: "assistant", content: "Test response" },
+										finish_reason: "stop",
+										index: 0,
+									},
+								],
+								usage: {
+									prompt_tokens: 10,
+									completion_tokens: 5,
+									total_tokens: 15,
+								},
+							}
+						}
+
+						return {
+							[Symbol.asyncIterator]: async function* () {
+								yield {
+									choices: [
+										{
+											delta: { content: "Test response" },
+											index: 0,
+										},
+									],
+									usage: null,
+								}
+								yield {
+									choices: [
+										{
+											delta: {},
+											index: 0,
+										},
+									],
+									usage: {
+										prompt_tokens: 10,
+										completion_tokens: 5,
+										total_tokens: 15,
+									},
+								}
+							},
+						}
+					}),
+				},
+			},
+		})),
+	}
+})
+
+describe("OpenAiNativeHandler", () => {
+	let handler: OpenAiNativeHandler
+	let mockOptions: ApiHandlerOptions
+	const systemPrompt = "You are a helpful assistant."
+	const messages: Anthropic.Messages.MessageParam[] = [
+		{
+			role: "user",
+			content: "Hello!",
+		},
+	]
+
+	beforeEach(() => {
+		mockOptions = {
+			apiModelId: "gpt-4o",
+			openAiNativeApiKey: "test-api-key",
+		}
+		handler = new OpenAiNativeHandler(mockOptions)
+		mockCreate.mockClear()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(OpenAiNativeHandler)
+			expect(handler.getModel().id).toBe(mockOptions.apiModelId)
+		})
+
+		it("should initialize with empty API key", () => {
+			const handlerWithoutKey = new OpenAiNativeHandler({
+				apiModelId: "gpt-4o",
+				openAiNativeApiKey: "",
+			})
+			expect(handlerWithoutKey).toBeInstanceOf(OpenAiNativeHandler)
+		})
+	})
+
+	describe("createMessage", () => {
+		it("should handle streaming responses", async () => {
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			const textChunks = chunks.filter((chunk) => chunk.type === "text")
+			expect(textChunks).toHaveLength(1)
+			expect(textChunks[0].text).toBe("Test response")
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			const stream = handler.createMessage(systemPrompt, messages)
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should not reach here
+				}
+			}).rejects.toThrow("API Error")
+		})
+
+		it("should handle missing content in response for o1 model", async () => {
+			// Use o1 model which supports developer role
+			handler = new OpenAiNativeHandler({
+				...mockOptions,
+				apiModelId: "o1",
+			})
+
+			mockCreate.mockResolvedValueOnce({
+				choices: [{ message: { content: null } }],
+				usage: {
+					prompt_tokens: 0,
+					completion_tokens: 0,
+					total_tokens: 0,
+				},
+			})
+
+			const generator = handler.createMessage(systemPrompt, messages)
+			const results = []
+			for await (const result of generator) {
+				results.push(result)
+			}
+
+			expect(results).toEqual([
+				{ type: "text", text: "" },
+				{ type: "usage", inputTokens: 0, outputTokens: 0 },
+			])
+
+			// Verify developer role is used for system prompt with o1 model
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "o1",
+				messages: [
+					{ role: "developer", content: systemPrompt },
+					{ role: "user", content: "Hello!" },
+				],
+			})
+		})
+	})
+
+	describe("streaming models", () => {
+		beforeEach(() => {
+			handler = new OpenAiNativeHandler({
+				...mockOptions,
+				apiModelId: "gpt-4o",
+			})
+		})
+
+		it("should handle streaming response", async () => {
+			const mockStream = [
+				{ choices: [{ delta: { content: "Hello" } }], usage: null },
+				{ choices: [{ delta: { content: " there" } }], usage: null },
+				{ choices: [{ delta: { content: "!" } }], usage: { prompt_tokens: 10, completion_tokens: 5 } },
+			]
+
+			mockCreate.mockResolvedValueOnce(
+				(async function* () {
+					for (const chunk of mockStream) {
+						yield chunk
+					}
+				})(),
+			)
+
+			const generator = handler.createMessage(systemPrompt, messages)
+			const results = []
+			for await (const result of generator) {
+				results.push(result)
+			}
+
+			expect(results).toEqual([
+				{ type: "text", text: "Hello" },
+				{ type: "text", text: " there" },
+				{ type: "text", text: "!" },
+				{ type: "usage", inputTokens: 10, outputTokens: 5 },
+			])
+
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "gpt-4o",
+				temperature: 0,
+				messages: [
+					{ role: "system", content: systemPrompt },
+					{ role: "user", content: "Hello!" },
+				],
+				stream: true,
+				stream_options: { include_usage: true },
+			})
+		})
+
+		it("should handle empty delta content", async () => {
+			const mockStream = [
+				{ choices: [{ delta: {} }], usage: null },
+				{ choices: [{ delta: { content: null } }], usage: null },
+				{ choices: [{ delta: { content: "Hello" } }], usage: { prompt_tokens: 10, completion_tokens: 5 } },
+			]
+
+			mockCreate.mockResolvedValueOnce(
+				(async function* () {
+					for (const chunk of mockStream) {
+						yield chunk
+					}
+				})(),
+			)
+
+			const generator = handler.createMessage(systemPrompt, messages)
+			const results = []
+			for await (const result of generator) {
+				results.push(result)
+			}
+
+			expect(results).toEqual([
+				{ type: "text", text: "Hello" },
+				{ type: "usage", inputTokens: 10, outputTokens: 5 },
+			])
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully with gpt-4o model", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "gpt-4o",
+				messages: [{ role: "user", content: "Test prompt" }],
+				temperature: 0,
+			})
+		})
+
+		it("should complete prompt successfully with o1 model", async () => {
+			handler = new OpenAiNativeHandler({
+				apiModelId: "o1",
+				openAiNativeApiKey: "test-api-key",
+			})
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "o1",
+				messages: [{ role: "user", content: "Test prompt" }],
+			})
+		})
+
+		it("should complete prompt successfully with o1-preview model", async () => {
+			handler = new OpenAiNativeHandler({
+				apiModelId: "o1-preview",
+				openAiNativeApiKey: "test-api-key",
+			})
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "o1-preview",
+				messages: [{ role: "user", content: "Test prompt" }],
+			})
+		})
+
+		it("should complete prompt successfully with o1-mini model", async () => {
+			handler = new OpenAiNativeHandler({
+				apiModelId: "o1-mini",
+				openAiNativeApiKey: "test-api-key",
+			})
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "o1-mini",
+				messages: [{ role: "user", content: "Test prompt" }],
+			})
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow(
+				"OpenAI Native completion error: API Error",
+			)
+		})
+
+		it("should handle empty response", async () => {
+			mockCreate.mockResolvedValueOnce({
+				choices: [{ message: { content: "" } }],
+			})
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe(mockOptions.apiModelId)
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(4096)
+			expect(modelInfo.info.contextWindow).toBe(128_000)
+		})
+
+		it("should handle undefined model ID", () => {
+			const handlerWithoutModel = new OpenAiNativeHandler({
+				openAiNativeApiKey: "test-api-key",
+			})
+			const modelInfo = handlerWithoutModel.getModel()
+			expect(modelInfo.id).toBe("gpt-4o") // Default model
+			expect(modelInfo.info).toBeDefined()
+		})
+	})
+})

+ 231 - 222
src/api/providers/__tests__/openai.test.ts

@@ -1,224 +1,233 @@
-import { OpenAiHandler } from '../openai';
-import { ApiHandlerOptions } from '../../../shared/api';
-import { ApiStream } from '../../transform/stream';
-import OpenAI from 'openai';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { OpenAiHandler } from "../openai"
+import { ApiHandlerOptions } from "../../../shared/api"
+import { ApiStream } from "../../transform/stream"
+import OpenAI from "openai"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock OpenAI client
-const mockCreate = jest.fn();
-jest.mock('openai', () => {
-    return {
-        __esModule: true,
-        default: jest.fn().mockImplementation(() => ({
-            chat: {
-                completions: {
-                    create: mockCreate.mockImplementation(async (options) => {
-                        if (!options.stream) {
-                            return {
-                                id: 'test-completion',
-                                choices: [{
-                                    message: { role: 'assistant', content: 'Test response', refusal: null },
-                                    finish_reason: 'stop',
-                                    index: 0
-                                }],
-                                usage: {
-                                    prompt_tokens: 10,
-                                    completion_tokens: 5,
-                                    total_tokens: 15
-                                }
-                            };
-                        }
-                        
-                        return {
-                            [Symbol.asyncIterator]: async function* () {
-                                yield {
-                                    choices: [{
-                                        delta: { content: 'Test response' },
-                                        index: 0
-                                    }],
-                                    usage: null
-                                };
-                                yield {
-                                    choices: [{
-                                        delta: {},
-                                        index: 0
-                                    }],
-                                    usage: {
-                                        prompt_tokens: 10,
-                                        completion_tokens: 5,
-                                        total_tokens: 15
-                                    }
-                                };
-                            }
-                        };
-                    })
-                }
-            }
-        }))
-    };
-});
-
-describe('OpenAiHandler', () => {
-    let handler: OpenAiHandler;
-    let mockOptions: ApiHandlerOptions;
-
-    beforeEach(() => {
-        mockOptions = {
-            openAiApiKey: 'test-api-key',
-            openAiModelId: 'gpt-4',
-            openAiBaseUrl: 'https://api.openai.com/v1'
-        };
-        handler = new OpenAiHandler(mockOptions);
-        mockCreate.mockClear();
-    });
-
-    describe('constructor', () => {
-        it('should initialize with provided options', () => {
-            expect(handler).toBeInstanceOf(OpenAiHandler);
-            expect(handler.getModel().id).toBe(mockOptions.openAiModelId);
-        });
-
-        it('should use custom base URL if provided', () => {
-            const customBaseUrl = 'https://custom.openai.com/v1';
-            const handlerWithCustomUrl = new OpenAiHandler({
-                ...mockOptions,
-                openAiBaseUrl: customBaseUrl
-            });
-            expect(handlerWithCustomUrl).toBeInstanceOf(OpenAiHandler);
-        });
-    });
-
-    describe('createMessage', () => {
-        const systemPrompt = 'You are a helpful assistant.';
-        const messages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: [{ 
-                    type: 'text' as const,
-                    text: 'Hello!'
-                }]
-            }
-        ];
-
-        it('should handle non-streaming mode', async () => {
-            const handler = new OpenAiHandler({
-                ...mockOptions,
-                openAiStreamingEnabled: false
-            });
-
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            const textChunk = chunks.find(chunk => chunk.type === 'text');
-            const usageChunk = chunks.find(chunk => chunk.type === 'usage');
-            
-            expect(textChunk).toBeDefined();
-            expect(textChunk?.text).toBe('Test response');
-            expect(usageChunk).toBeDefined();
-            expect(usageChunk?.inputTokens).toBe(10);
-            expect(usageChunk?.outputTokens).toBe(5);
-        });
-
-        it('should handle streaming responses', async () => {
-            const stream = handler.createMessage(systemPrompt, messages);
-            const chunks: any[] = [];
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
-
-            expect(chunks.length).toBeGreaterThan(0);
-            const textChunks = chunks.filter(chunk => chunk.type === 'text');
-            expect(textChunks).toHaveLength(1);
-            expect(textChunks[0].text).toBe('Test response');
-        });
-    });
-
-    describe('error handling', () => {
-        const testMessages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: [{ 
-                    type: 'text' as const,
-                    text: 'Hello'
-                }]
-            }
-        ];
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-
-            const stream = handler.createMessage('system prompt', testMessages);
-
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should not reach here
-                }
-            }).rejects.toThrow('API Error');
-        });
-
-        it('should handle rate limiting', async () => {
-            const rateLimitError = new Error('Rate limit exceeded');
-            rateLimitError.name = 'Error';
-            (rateLimitError as any).status = 429;
-            mockCreate.mockRejectedValueOnce(rateLimitError);
-
-            const stream = handler.createMessage('system prompt', testMessages);
-
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should not reach here
-                }
-            }).rejects.toThrow('Rate limit exceeded');
-        });
-    });
-
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: mockOptions.openAiModelId,
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                temperature: 0
-            });
-        });
-
-        it('should handle API errors', async () => {
-            mockCreate.mockRejectedValueOnce(new Error('API Error'));
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('OpenAI completion error: API Error');
-        });
-
-        it('should handle empty response', async () => {
-            mockCreate.mockImplementationOnce(() => ({
-                choices: [{ message: { content: '' } }]
-            }));
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
-
-    describe('getModel', () => {
-        it('should return model info with sane defaults', () => {
-            const model = handler.getModel();
-            expect(model.id).toBe(mockOptions.openAiModelId);
-            expect(model.info).toBeDefined();
-            expect(model.info.contextWindow).toBe(128_000);
-            expect(model.info.supportsImages).toBe(true);
-        });
-
-        it('should handle undefined model ID', () => {
-            const handlerWithoutModel = new OpenAiHandler({
-                ...mockOptions,
-                openAiModelId: undefined
-            });
-            const model = handlerWithoutModel.getModel();
-            expect(model.id).toBe('');
-            expect(model.info).toBeDefined();
-        });
-    });
-});
+const mockCreate = jest.fn()
+jest.mock("openai", () => {
+	return {
+		__esModule: true,
+		default: jest.fn().mockImplementation(() => ({
+			chat: {
+				completions: {
+					create: mockCreate.mockImplementation(async (options) => {
+						if (!options.stream) {
+							return {
+								id: "test-completion",
+								choices: [
+									{
+										message: { role: "assistant", content: "Test response", refusal: null },
+										finish_reason: "stop",
+										index: 0,
+									},
+								],
+								usage: {
+									prompt_tokens: 10,
+									completion_tokens: 5,
+									total_tokens: 15,
+								},
+							}
+						}
+
+						return {
+							[Symbol.asyncIterator]: async function* () {
+								yield {
+									choices: [
+										{
+											delta: { content: "Test response" },
+											index: 0,
+										},
+									],
+									usage: null,
+								}
+								yield {
+									choices: [
+										{
+											delta: {},
+											index: 0,
+										},
+									],
+									usage: {
+										prompt_tokens: 10,
+										completion_tokens: 5,
+										total_tokens: 15,
+									},
+								}
+							},
+						}
+					}),
+				},
+			},
+		})),
+	}
+})
+
+describe("OpenAiHandler", () => {
+	let handler: OpenAiHandler
+	let mockOptions: ApiHandlerOptions
+
+	beforeEach(() => {
+		mockOptions = {
+			openAiApiKey: "test-api-key",
+			openAiModelId: "gpt-4",
+			openAiBaseUrl: "https://api.openai.com/v1",
+		}
+		handler = new OpenAiHandler(mockOptions)
+		mockCreate.mockClear()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeInstanceOf(OpenAiHandler)
+			expect(handler.getModel().id).toBe(mockOptions.openAiModelId)
+		})
+
+		it("should use custom base URL if provided", () => {
+			const customBaseUrl = "https://custom.openai.com/v1"
+			const handlerWithCustomUrl = new OpenAiHandler({
+				...mockOptions,
+				openAiBaseUrl: customBaseUrl,
+			})
+			expect(handlerWithCustomUrl).toBeInstanceOf(OpenAiHandler)
+		})
+	})
+
+	describe("createMessage", () => {
+		const systemPrompt = "You are a helpful assistant."
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: [
+					{
+						type: "text" as const,
+						text: "Hello!",
+					},
+				],
+			},
+		]
+
+		it("should handle non-streaming mode", async () => {
+			const handler = new OpenAiHandler({
+				...mockOptions,
+				openAiStreamingEnabled: false,
+			})
+
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			const textChunk = chunks.find((chunk) => chunk.type === "text")
+			const usageChunk = chunks.find((chunk) => chunk.type === "usage")
+
+			expect(textChunk).toBeDefined()
+			expect(textChunk?.text).toBe("Test response")
+			expect(usageChunk).toBeDefined()
+			expect(usageChunk?.inputTokens).toBe(10)
+			expect(usageChunk?.outputTokens).toBe(5)
+		})
+
+		it("should handle streaming responses", async () => {
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks: any[] = []
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
+
+			expect(chunks.length).toBeGreaterThan(0)
+			const textChunks = chunks.filter((chunk) => chunk.type === "text")
+			expect(textChunks).toHaveLength(1)
+			expect(textChunks[0].text).toBe("Test response")
+		})
+	})
+
+	describe("error handling", () => {
+		const testMessages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: [
+					{
+						type: "text" as const,
+						text: "Hello",
+					},
+				],
+			},
+		]
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+
+			const stream = handler.createMessage("system prompt", testMessages)
+
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should not reach here
+				}
+			}).rejects.toThrow("API Error")
+		})
+
+		it("should handle rate limiting", async () => {
+			const rateLimitError = new Error("Rate limit exceeded")
+			rateLimitError.name = "Error"
+			;(rateLimitError as any).status = 429
+			mockCreate.mockRejectedValueOnce(rateLimitError)
+
+			const stream = handler.createMessage("system prompt", testMessages)
+
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should not reach here
+				}
+			}).rejects.toThrow("Rate limit exceeded")
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: mockOptions.openAiModelId,
+				messages: [{ role: "user", content: "Test prompt" }],
+				temperature: 0,
+			})
+		})
+
+		it("should handle API errors", async () => {
+			mockCreate.mockRejectedValueOnce(new Error("API Error"))
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error: API Error")
+		})
+
+		it("should handle empty response", async () => {
+			mockCreate.mockImplementationOnce(() => ({
+				choices: [{ message: { content: "" } }],
+			}))
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info with sane defaults", () => {
+			const model = handler.getModel()
+			expect(model.id).toBe(mockOptions.openAiModelId)
+			expect(model.info).toBeDefined()
+			expect(model.info.contextWindow).toBe(128_000)
+			expect(model.info.supportsImages).toBe(true)
+		})
+
+		it("should handle undefined model ID", () => {
+			const handlerWithoutModel = new OpenAiHandler({
+				...mockOptions,
+				openAiModelId: undefined,
+			})
+			const model = handlerWithoutModel.getModel()
+			expect(model.id).toBe("")
+			expect(model.info).toBeDefined()
+		})
+	})
+})

+ 294 - 280
src/api/providers/__tests__/openrouter.test.ts

@@ -1,283 +1,297 @@
-import { OpenRouterHandler } from '../openrouter'
-import { ApiHandlerOptions, ModelInfo } from '../../../shared/api'
-import OpenAI from 'openai'
-import axios from 'axios'
-import { Anthropic } from '@anthropic-ai/sdk'
+import { OpenRouterHandler } from "../openrouter"
+import { ApiHandlerOptions, ModelInfo } from "../../../shared/api"
+import OpenAI from "openai"
+import axios from "axios"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock dependencies
-jest.mock('openai')
-jest.mock('axios')
-jest.mock('delay', () => jest.fn(() => Promise.resolve()))
-
-describe('OpenRouterHandler', () => {
-    const mockOptions: ApiHandlerOptions = {
-        openRouterApiKey: 'test-key',
-        openRouterModelId: 'test-model',
-        openRouterModelInfo: {
-            name: 'Test Model',
-            description: 'Test Description',
-            maxTokens: 1000,
-            contextWindow: 2000,
-            supportsPromptCache: true,
-            inputPrice: 0.01,
-            outputPrice: 0.02
-        } as ModelInfo
-    }
-
-    beforeEach(() => {
-        jest.clearAllMocks()
-    })
-
-    test('constructor initializes with correct options', () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        expect(handler).toBeInstanceOf(OpenRouterHandler)
-        expect(OpenAI).toHaveBeenCalledWith({
-            baseURL: 'https://openrouter.ai/api/v1',
-            apiKey: mockOptions.openRouterApiKey,
-            defaultHeaders: {
-                'HTTP-Referer': 'https://github.com/RooVetGit/Roo-Cline',
-                'X-Title': 'Roo-Cline',
-            },
-        })
-    })
-
-    test('getModel returns correct model info when options are provided', () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        const result = handler.getModel()
-        
-        expect(result).toEqual({
-            id: mockOptions.openRouterModelId,
-            info: mockOptions.openRouterModelInfo
-        })
-    })
-
-    test('getModel returns default model info when options are not provided', () => {
-        const handler = new OpenRouterHandler({})
-        const result = handler.getModel()
-        
-        expect(result.id).toBe('anthropic/claude-3.5-sonnet:beta')
-        expect(result.info.supportsPromptCache).toBe(true)
-    })
-
-    test('createMessage generates correct stream chunks', async () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        const mockStream = {
-            async *[Symbol.asyncIterator]() {
-                yield {
-                    id: 'test-id',
-                    choices: [{
-                        delta: {
-                            content: 'test response'
-                        }
-                    }]
-                }
-            }
-        }
-
-        // Mock OpenAI chat.completions.create
-        const mockCreate = jest.fn().mockResolvedValue(mockStream)
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-
-        // Mock axios.get for generation details
-        ;(axios.get as jest.Mock).mockResolvedValue({
-            data: {
-                data: {
-                    native_tokens_prompt: 10,
-                    native_tokens_completion: 20,
-                    total_cost: 0.001
-                }
-            }
-        })
-
-        const systemPrompt = 'test system prompt'
-        const messages: Anthropic.Messages.MessageParam[] = [{ role: 'user' as const, content: 'test message' }]
-
-        const generator = handler.createMessage(systemPrompt, messages)
-        const chunks = []
-        
-        for await (const chunk of generator) {
-            chunks.push(chunk)
-        }
-
-        // Verify stream chunks
-        expect(chunks).toHaveLength(2) // One text chunk and one usage chunk
-        expect(chunks[0]).toEqual({
-            type: 'text',
-            text: 'test response'
-        })
-        expect(chunks[1]).toEqual({
-            type: 'usage',
-            inputTokens: 10,
-            outputTokens: 20,
-            totalCost: 0.001,
-            fullResponseText: 'test response'
-        })
-
-        // Verify OpenAI client was called with correct parameters
-        expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({
-            model: mockOptions.openRouterModelId,
-            temperature: 0,
-            messages: expect.arrayContaining([
-                { role: 'system', content: systemPrompt },
-                { role: 'user', content: 'test message' }
-            ]),
-            stream: true
-        }))
-    })
-
-    test('createMessage with middle-out transform enabled', async () => {
-        const handler = new OpenRouterHandler({
-            ...mockOptions,
-            openRouterUseMiddleOutTransform: true
-        })
-        const mockStream = {
-            async *[Symbol.asyncIterator]() {
-                yield {
-                    id: 'test-id',
-                    choices: [{
-                        delta: {
-                            content: 'test response'
-                        }
-                    }]
-                }
-            }
-        }
-
-        const mockCreate = jest.fn().mockResolvedValue(mockStream)
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-        ;(axios.get as jest.Mock).mockResolvedValue({ data: { data: {} } })
-
-        await handler.createMessage('test', []).next()
-
-        expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({
-            transforms: ['middle-out']
-        }))
-    })
-
-    test('createMessage with Claude model adds cache control', async () => {
-        const handler = new OpenRouterHandler({
-            ...mockOptions,
-            openRouterModelId: 'anthropic/claude-3.5-sonnet'
-        })
-        const mockStream = {
-            async *[Symbol.asyncIterator]() {
-                yield {
-                    id: 'test-id',
-                    choices: [{
-                        delta: {
-                            content: 'test response'
-                        }
-                    }]
-                }
-            }
-        }
-
-        const mockCreate = jest.fn().mockResolvedValue(mockStream)
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-        ;(axios.get as jest.Mock).mockResolvedValue({ data: { data: {} } })
-
-        const messages: Anthropic.Messages.MessageParam[] = [
-            { role: 'user', content: 'message 1' },
-            { role: 'assistant', content: 'response 1' },
-            { role: 'user', content: 'message 2' }
-        ]
-
-        await handler.createMessage('test system', messages).next()
-
-        expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({
-            messages: expect.arrayContaining([
-                expect.objectContaining({
-                    role: 'system',
-                    content: expect.arrayContaining([
-                        expect.objectContaining({
-                            cache_control: { type: 'ephemeral' }
-                        })
-                    ])
-                })
-            ])
-        }))
-    })
-
-    test('createMessage handles API errors', async () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        const mockStream = {
-            async *[Symbol.asyncIterator]() {
-                yield {
-                    error: {
-                        message: 'API Error',
-                        code: 500
-                    }
-                }
-            }
-        }
-
-        const mockCreate = jest.fn().mockResolvedValue(mockStream)
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-
-        const generator = handler.createMessage('test', [])
-        await expect(generator.next()).rejects.toThrow('OpenRouter API Error 500: API Error')
-    })
-
-    test('completePrompt returns correct response', async () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        const mockResponse = {
-            choices: [{
-                message: {
-                    content: 'test completion'
-                }
-            }]
-        }
-
-        const mockCreate = jest.fn().mockResolvedValue(mockResponse)
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-
-        const result = await handler.completePrompt('test prompt')
-
-        expect(result).toBe('test completion')
-        expect(mockCreate).toHaveBeenCalledWith({
-            model: mockOptions.openRouterModelId,
-            messages: [{ role: 'user', content: 'test prompt' }],
-            temperature: 0,
-            stream: false
-        })
-    })
-
-    test('completePrompt handles API errors', async () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        const mockError = {
-            error: {
-                message: 'API Error',
-                code: 500
-            }
-        }
-
-        const mockCreate = jest.fn().mockResolvedValue(mockError)
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-
-        await expect(handler.completePrompt('test prompt'))
-            .rejects.toThrow('OpenRouter API Error 500: API Error')
-    })
-
-    test('completePrompt handles unexpected errors', async () => {
-        const handler = new OpenRouterHandler(mockOptions)
-        const mockCreate = jest.fn().mockRejectedValue(new Error('Unexpected error'))
-        ;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
-            completions: { create: mockCreate }
-        } as any
-
-        await expect(handler.completePrompt('test prompt'))
-            .rejects.toThrow('OpenRouter completion error: Unexpected error')
-    })
+jest.mock("openai")
+jest.mock("axios")
+jest.mock("delay", () => jest.fn(() => Promise.resolve()))
+
+describe("OpenRouterHandler", () => {
+	const mockOptions: ApiHandlerOptions = {
+		openRouterApiKey: "test-key",
+		openRouterModelId: "test-model",
+		openRouterModelInfo: {
+			name: "Test Model",
+			description: "Test Description",
+			maxTokens: 1000,
+			contextWindow: 2000,
+			supportsPromptCache: true,
+			inputPrice: 0.01,
+			outputPrice: 0.02,
+		} as ModelInfo,
+	}
+
+	beforeEach(() => {
+		jest.clearAllMocks()
+	})
+
+	test("constructor initializes with correct options", () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		expect(handler).toBeInstanceOf(OpenRouterHandler)
+		expect(OpenAI).toHaveBeenCalledWith({
+			baseURL: "https://openrouter.ai/api/v1",
+			apiKey: mockOptions.openRouterApiKey,
+			defaultHeaders: {
+				"HTTP-Referer": "https://github.com/RooVetGit/Roo-Cline",
+				"X-Title": "Roo-Cline",
+			},
+		})
+	})
+
+	test("getModel returns correct model info when options are provided", () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		const result = handler.getModel()
+
+		expect(result).toEqual({
+			id: mockOptions.openRouterModelId,
+			info: mockOptions.openRouterModelInfo,
+		})
+	})
+
+	test("getModel returns default model info when options are not provided", () => {
+		const handler = new OpenRouterHandler({})
+		const result = handler.getModel()
+
+		expect(result.id).toBe("anthropic/claude-3.5-sonnet:beta")
+		expect(result.info.supportsPromptCache).toBe(true)
+	})
+
+	test("createMessage generates correct stream chunks", async () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		const mockStream = {
+			async *[Symbol.asyncIterator]() {
+				yield {
+					id: "test-id",
+					choices: [
+						{
+							delta: {
+								content: "test response",
+							},
+						},
+					],
+				}
+			},
+		}
+
+		// Mock OpenAI chat.completions.create
+		const mockCreate = jest.fn().mockResolvedValue(mockStream)
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+
+		// Mock axios.get for generation details
+		;(axios.get as jest.Mock).mockResolvedValue({
+			data: {
+				data: {
+					native_tokens_prompt: 10,
+					native_tokens_completion: 20,
+					total_cost: 0.001,
+				},
+			},
+		})
+
+		const systemPrompt = "test system prompt"
+		const messages: Anthropic.Messages.MessageParam[] = [{ role: "user" as const, content: "test message" }]
+
+		const generator = handler.createMessage(systemPrompt, messages)
+		const chunks = []
+
+		for await (const chunk of generator) {
+			chunks.push(chunk)
+		}
+
+		// Verify stream chunks
+		expect(chunks).toHaveLength(2) // One text chunk and one usage chunk
+		expect(chunks[0]).toEqual({
+			type: "text",
+			text: "test response",
+		})
+		expect(chunks[1]).toEqual({
+			type: "usage",
+			inputTokens: 10,
+			outputTokens: 20,
+			totalCost: 0.001,
+			fullResponseText: "test response",
+		})
+
+		// Verify OpenAI client was called with correct parameters
+		expect(mockCreate).toHaveBeenCalledWith(
+			expect.objectContaining({
+				model: mockOptions.openRouterModelId,
+				temperature: 0,
+				messages: expect.arrayContaining([
+					{ role: "system", content: systemPrompt },
+					{ role: "user", content: "test message" },
+				]),
+				stream: true,
+			}),
+		)
+	})
+
+	test("createMessage with middle-out transform enabled", async () => {
+		const handler = new OpenRouterHandler({
+			...mockOptions,
+			openRouterUseMiddleOutTransform: true,
+		})
+		const mockStream = {
+			async *[Symbol.asyncIterator]() {
+				yield {
+					id: "test-id",
+					choices: [
+						{
+							delta: {
+								content: "test response",
+							},
+						},
+					],
+				}
+			},
+		}
+
+		const mockCreate = jest.fn().mockResolvedValue(mockStream)
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+		;(axios.get as jest.Mock).mockResolvedValue({ data: { data: {} } })
+
+		await handler.createMessage("test", []).next()
+
+		expect(mockCreate).toHaveBeenCalledWith(
+			expect.objectContaining({
+				transforms: ["middle-out"],
+			}),
+		)
+	})
+
+	test("createMessage with Claude model adds cache control", async () => {
+		const handler = new OpenRouterHandler({
+			...mockOptions,
+			openRouterModelId: "anthropic/claude-3.5-sonnet",
+		})
+		const mockStream = {
+			async *[Symbol.asyncIterator]() {
+				yield {
+					id: "test-id",
+					choices: [
+						{
+							delta: {
+								content: "test response",
+							},
+						},
+					],
+				}
+			},
+		}
+
+		const mockCreate = jest.fn().mockResolvedValue(mockStream)
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+		;(axios.get as jest.Mock).mockResolvedValue({ data: { data: {} } })
+
+		const messages: Anthropic.Messages.MessageParam[] = [
+			{ role: "user", content: "message 1" },
+			{ role: "assistant", content: "response 1" },
+			{ role: "user", content: "message 2" },
+		]
+
+		await handler.createMessage("test system", messages).next()
+
+		expect(mockCreate).toHaveBeenCalledWith(
+			expect.objectContaining({
+				messages: expect.arrayContaining([
+					expect.objectContaining({
+						role: "system",
+						content: expect.arrayContaining([
+							expect.objectContaining({
+								cache_control: { type: "ephemeral" },
+							}),
+						]),
+					}),
+				]),
+			}),
+		)
+	})
+
+	test("createMessage handles API errors", async () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		const mockStream = {
+			async *[Symbol.asyncIterator]() {
+				yield {
+					error: {
+						message: "API Error",
+						code: 500,
+					},
+				}
+			},
+		}
+
+		const mockCreate = jest.fn().mockResolvedValue(mockStream)
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+
+		const generator = handler.createMessage("test", [])
+		await expect(generator.next()).rejects.toThrow("OpenRouter API Error 500: API Error")
+	})
+
+	test("completePrompt returns correct response", async () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		const mockResponse = {
+			choices: [
+				{
+					message: {
+						content: "test completion",
+					},
+				},
+			],
+		}
+
+		const mockCreate = jest.fn().mockResolvedValue(mockResponse)
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+
+		const result = await handler.completePrompt("test prompt")
+
+		expect(result).toBe("test completion")
+		expect(mockCreate).toHaveBeenCalledWith({
+			model: mockOptions.openRouterModelId,
+			messages: [{ role: "user", content: "test prompt" }],
+			temperature: 0,
+			stream: false,
+		})
+	})
+
+	test("completePrompt handles API errors", async () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		const mockError = {
+			error: {
+				message: "API Error",
+				code: 500,
+			},
+		}
+
+		const mockCreate = jest.fn().mockResolvedValue(mockError)
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+
+		await expect(handler.completePrompt("test prompt")).rejects.toThrow("OpenRouter API Error 500: API Error")
+	})
+
+	test("completePrompt handles unexpected errors", async () => {
+		const handler = new OpenRouterHandler(mockOptions)
+		const mockCreate = jest.fn().mockRejectedValue(new Error("Unexpected error"))
+		;(OpenAI as jest.MockedClass<typeof OpenAI>).prototype.chat = {
+			completions: { create: mockCreate },
+		} as any
+
+		await expect(handler.completePrompt("test prompt")).rejects.toThrow(
+			"OpenRouter completion error: Unexpected error",
+		)
+	})
 })

+ 265 - 266
src/api/providers/__tests__/vertex.test.ts

@@ -1,296 +1,295 @@
-import { VertexHandler } from '../vertex';
-import { Anthropic } from '@anthropic-ai/sdk';
-import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
+import { VertexHandler } from "../vertex"
+import { Anthropic } from "@anthropic-ai/sdk"
+import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"
 
 // Mock Vertex SDK
-jest.mock('@anthropic-ai/vertex-sdk', () => ({
-    AnthropicVertex: jest.fn().mockImplementation(() => ({
-        messages: {
-            create: jest.fn().mockImplementation(async (options) => {
-                if (!options.stream) {
-                    return {
-                        id: 'test-completion',
-                        content: [
-                            { type: 'text', text: 'Test response' }
-                        ],
-                        role: 'assistant',
-                        model: options.model,
-                        usage: {
-                            input_tokens: 10,
-                            output_tokens: 5
-                        }
-                    }
-                }
-                return {
-                    async *[Symbol.asyncIterator]() {
-                        yield {
-                            type: 'message_start',
-                            message: {
-                                usage: {
-                                    input_tokens: 10,
-                                    output_tokens: 5
-                                }
-                            }
-                        }
-                        yield {
-                            type: 'content_block_start',
-                            content_block: {
-                                type: 'text',
-                                text: 'Test response'
-                            }
-                        }
-                    }
-                }
-            })
-        }
-    }))
-}));
+jest.mock("@anthropic-ai/vertex-sdk", () => ({
+	AnthropicVertex: jest.fn().mockImplementation(() => ({
+		messages: {
+			create: jest.fn().mockImplementation(async (options) => {
+				if (!options.stream) {
+					return {
+						id: "test-completion",
+						content: [{ type: "text", text: "Test response" }],
+						role: "assistant",
+						model: options.model,
+						usage: {
+							input_tokens: 10,
+							output_tokens: 5,
+						},
+					}
+				}
+				return {
+					async *[Symbol.asyncIterator]() {
+						yield {
+							type: "message_start",
+							message: {
+								usage: {
+									input_tokens: 10,
+									output_tokens: 5,
+								},
+							},
+						}
+						yield {
+							type: "content_block_start",
+							content_block: {
+								type: "text",
+								text: "Test response",
+							},
+						}
+					},
+				}
+			}),
+		},
+	})),
+}))
 
-describe('VertexHandler', () => {
-    let handler: VertexHandler;
+describe("VertexHandler", () => {
+	let handler: VertexHandler
 
-    beforeEach(() => {
-        handler = new VertexHandler({
-            apiModelId: 'claude-3-5-sonnet-v2@20241022',
-            vertexProjectId: 'test-project',
-            vertexRegion: 'us-central1'
-        });
-    });
+	beforeEach(() => {
+		handler = new VertexHandler({
+			apiModelId: "claude-3-5-sonnet-v2@20241022",
+			vertexProjectId: "test-project",
+			vertexRegion: "us-central1",
+		})
+	})
 
-    describe('constructor', () => {
-        it('should initialize with provided config', () => {
-            expect(AnthropicVertex).toHaveBeenCalledWith({
-                projectId: 'test-project',
-                region: 'us-central1'
-            });
-        });
-    });
+	describe("constructor", () => {
+		it("should initialize with provided config", () => {
+			expect(AnthropicVertex).toHaveBeenCalledWith({
+				projectId: "test-project",
+				region: "us-central1",
+			})
+		})
+	})
 
-    describe('createMessage', () => {
-        const mockMessages: Anthropic.Messages.MessageParam[] = [
-            {
-                role: 'user',
-                content: 'Hello'
-            },
-            {
-                role: 'assistant',
-                content: 'Hi there!'
-            }
-        ];
+	describe("createMessage", () => {
+		const mockMessages: Anthropic.Messages.MessageParam[] = [
+			{
+				role: "user",
+				content: "Hello",
+			},
+			{
+				role: "assistant",
+				content: "Hi there!",
+			},
+		]
 
-        const systemPrompt = 'You are a helpful assistant';
+		const systemPrompt = "You are a helpful assistant"
 
-        it('should handle streaming responses correctly', async () => {
-            const mockStream = [
-                {
-                    type: 'message_start',
-                    message: {
-                        usage: {
-                            input_tokens: 10,
-                            output_tokens: 0
-                        }
-                    }
-                },
-                {
-                    type: 'content_block_start',
-                    index: 0,
-                    content_block: {
-                        type: 'text',
-                        text: 'Hello'
-                    }
-                },
-                {
-                    type: 'content_block_delta',
-                    delta: {
-                        type: 'text_delta',
-                        text: ' world!'
-                    }
-                },
-                {
-                    type: 'message_delta',
-                    usage: {
-                        output_tokens: 5
-                    }
-                }
-            ];
+		it("should handle streaming responses correctly", async () => {
+			const mockStream = [
+				{
+					type: "message_start",
+					message: {
+						usage: {
+							input_tokens: 10,
+							output_tokens: 0,
+						},
+					},
+				},
+				{
+					type: "content_block_start",
+					index: 0,
+					content_block: {
+						type: "text",
+						text: "Hello",
+					},
+				},
+				{
+					type: "content_block_delta",
+					delta: {
+						type: "text_delta",
+						text: " world!",
+					},
+				},
+				{
+					type: "message_delta",
+					usage: {
+						output_tokens: 5,
+					},
+				},
+			]
 
-            // Setup async iterator for mock stream
-            const asyncIterator = {
-                async *[Symbol.asyncIterator]() {
-                    for (const chunk of mockStream) {
-                        yield chunk;
-                    }
-                }
-            };
+			// Setup async iterator for mock stream
+			const asyncIterator = {
+				async *[Symbol.asyncIterator]() {
+					for (const chunk of mockStream) {
+						yield chunk
+					}
+				},
+			}
 
-            const mockCreate = jest.fn().mockResolvedValue(asyncIterator);
-            (handler['client'].messages as any).create = mockCreate;
+			const mockCreate = jest.fn().mockResolvedValue(asyncIterator)
+			;(handler["client"].messages as any).create = mockCreate
 
-            const stream = handler.createMessage(systemPrompt, mockMessages);
-            const chunks = [];
-            
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
+			const stream = handler.createMessage(systemPrompt, mockMessages)
+			const chunks = []
 
-            expect(chunks.length).toBe(4);
-            expect(chunks[0]).toEqual({
-                type: 'usage',
-                inputTokens: 10,
-                outputTokens: 0
-            });
-            expect(chunks[1]).toEqual({
-                type: 'text',
-                text: 'Hello'
-            });
-            expect(chunks[2]).toEqual({
-                type: 'text',
-                text: ' world!'
-            });
-            expect(chunks[3]).toEqual({
-                type: 'usage',
-                inputTokens: 0,
-                outputTokens: 5
-            });
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
 
-            expect(mockCreate).toHaveBeenCalledWith({
-                model: 'claude-3-5-sonnet-v2@20241022',
-                max_tokens: 8192,
-                temperature: 0,
-                system: systemPrompt,
-                messages: mockMessages,
-                stream: true
-            });
-        });
+			expect(chunks.length).toBe(4)
+			expect(chunks[0]).toEqual({
+				type: "usage",
+				inputTokens: 10,
+				outputTokens: 0,
+			})
+			expect(chunks[1]).toEqual({
+				type: "text",
+				text: "Hello",
+			})
+			expect(chunks[2]).toEqual({
+				type: "text",
+				text: " world!",
+			})
+			expect(chunks[3]).toEqual({
+				type: "usage",
+				inputTokens: 0,
+				outputTokens: 5,
+			})
 
-        it('should handle multiple content blocks with line breaks', async () => {
-            const mockStream = [
-                {
-                    type: 'content_block_start',
-                    index: 0,
-                    content_block: {
-                        type: 'text',
-                        text: 'First line'
-                    }
-                },
-                {
-                    type: 'content_block_start',
-                    index: 1,
-                    content_block: {
-                        type: 'text',
-                        text: 'Second line'
-                    }
-                }
-            ];
+			expect(mockCreate).toHaveBeenCalledWith({
+				model: "claude-3-5-sonnet-v2@20241022",
+				max_tokens: 8192,
+				temperature: 0,
+				system: systemPrompt,
+				messages: mockMessages,
+				stream: true,
+			})
+		})
 
-            const asyncIterator = {
-                async *[Symbol.asyncIterator]() {
-                    for (const chunk of mockStream) {
-                        yield chunk;
-                    }
-                }
-            };
+		it("should handle multiple content blocks with line breaks", async () => {
+			const mockStream = [
+				{
+					type: "content_block_start",
+					index: 0,
+					content_block: {
+						type: "text",
+						text: "First line",
+					},
+				},
+				{
+					type: "content_block_start",
+					index: 1,
+					content_block: {
+						type: "text",
+						text: "Second line",
+					},
+				},
+			]
 
-            const mockCreate = jest.fn().mockResolvedValue(asyncIterator);
-            (handler['client'].messages as any).create = mockCreate;
+			const asyncIterator = {
+				async *[Symbol.asyncIterator]() {
+					for (const chunk of mockStream) {
+						yield chunk
+					}
+				},
+			}
 
-            const stream = handler.createMessage(systemPrompt, mockMessages);
-            const chunks = [];
-            
-            for await (const chunk of stream) {
-                chunks.push(chunk);
-            }
+			const mockCreate = jest.fn().mockResolvedValue(asyncIterator)
+			;(handler["client"].messages as any).create = mockCreate
 
-            expect(chunks.length).toBe(3);
-            expect(chunks[0]).toEqual({
-                type: 'text',
-                text: 'First line'
-            });
-            expect(chunks[1]).toEqual({
-                type: 'text',
-                text: '\n'
-            });
-            expect(chunks[2]).toEqual({
-                type: 'text',
-                text: 'Second line'
-            });
-        });
+			const stream = handler.createMessage(systemPrompt, mockMessages)
+			const chunks = []
 
-        it('should handle API errors', async () => {
-            const mockError = new Error('Vertex API error');
-            const mockCreate = jest.fn().mockRejectedValue(mockError);
-            (handler['client'].messages as any).create = mockCreate;
+			for await (const chunk of stream) {
+				chunks.push(chunk)
+			}
 
-            const stream = handler.createMessage(systemPrompt, mockMessages);
+			expect(chunks.length).toBe(3)
+			expect(chunks[0]).toEqual({
+				type: "text",
+				text: "First line",
+			})
+			expect(chunks[1]).toEqual({
+				type: "text",
+				text: "\n",
+			})
+			expect(chunks[2]).toEqual({
+				type: "text",
+				text: "Second line",
+			})
+		})
 
-            await expect(async () => {
-                for await (const chunk of stream) {
-                    // Should throw before yielding any chunks
-                }
-            }).rejects.toThrow('Vertex API error');
-        });
-    });
+		it("should handle API errors", async () => {
+			const mockError = new Error("Vertex API error")
+			const mockCreate = jest.fn().mockRejectedValue(mockError)
+			;(handler["client"].messages as any).create = mockCreate
 
-    describe('completePrompt', () => {
-        it('should complete prompt successfully', async () => {
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('Test response');
-            expect(handler['client'].messages.create).toHaveBeenCalledWith({
-                model: 'claude-3-5-sonnet-v2@20241022',
-                max_tokens: 8192,
-                temperature: 0,
-                messages: [{ role: 'user', content: 'Test prompt' }],
-                stream: false
-            });
-        });
+			const stream = handler.createMessage(systemPrompt, mockMessages)
 
-        it('should handle API errors', async () => {
-            const mockError = new Error('Vertex API error');
-            const mockCreate = jest.fn().mockRejectedValue(mockError);
-            (handler['client'].messages as any).create = mockCreate;
+			await expect(async () => {
+				for await (const chunk of stream) {
+					// Should throw before yielding any chunks
+				}
+			}).rejects.toThrow("Vertex API error")
+		})
+	})
 
-            await expect(handler.completePrompt('Test prompt'))
-                .rejects.toThrow('Vertex completion error: Vertex API error');
-        });
+	describe("completePrompt", () => {
+		it("should complete prompt successfully", async () => {
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("Test response")
+			expect(handler["client"].messages.create).toHaveBeenCalledWith({
+				model: "claude-3-5-sonnet-v2@20241022",
+				max_tokens: 8192,
+				temperature: 0,
+				messages: [{ role: "user", content: "Test prompt" }],
+				stream: false,
+			})
+		})
 
-        it('should handle non-text content', async () => {
-            const mockCreate = jest.fn().mockResolvedValue({
-                content: [{ type: 'image' }]
-            });
-            (handler['client'].messages as any).create = mockCreate;
+		it("should handle API errors", async () => {
+			const mockError = new Error("Vertex API error")
+			const mockCreate = jest.fn().mockRejectedValue(mockError)
+			;(handler["client"].messages as any).create = mockCreate
 
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow(
+				"Vertex completion error: Vertex API error",
+			)
+		})
 
-        it('should handle empty response', async () => {
-            const mockCreate = jest.fn().mockResolvedValue({
-                content: [{ type: 'text', text: '' }]
-            });
-            (handler['client'].messages as any).create = mockCreate;
+		it("should handle non-text content", async () => {
+			const mockCreate = jest.fn().mockResolvedValue({
+				content: [{ type: "image" }],
+			})
+			;(handler["client"].messages as any).create = mockCreate
 
-            const result = await handler.completePrompt('Test prompt');
-            expect(result).toBe('');
-        });
-    });
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
 
-    describe('getModel', () => {
-        it('should return correct model info', () => {
-            const modelInfo = handler.getModel();
-            expect(modelInfo.id).toBe('claude-3-5-sonnet-v2@20241022');
-            expect(modelInfo.info).toBeDefined();
-            expect(modelInfo.info.maxTokens).toBe(8192);
-            expect(modelInfo.info.contextWindow).toBe(200_000);
-        });
+		it("should handle empty response", async () => {
+			const mockCreate = jest.fn().mockResolvedValue({
+				content: [{ type: "text", text: "" }],
+			})
+			;(handler["client"].messages as any).create = mockCreate
 
-        it('should return default model if invalid model specified', () => {
-            const invalidHandler = new VertexHandler({
-                apiModelId: 'invalid-model',
-                vertexProjectId: 'test-project',
-                vertexRegion: 'us-central1'
-            });
-            const modelInfo = invalidHandler.getModel();
-            expect(modelInfo.id).toBe('claude-3-5-sonnet-v2@20241022'); // Default model
-        });
-    });
-});
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe("")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return correct model info", () => {
+			const modelInfo = handler.getModel()
+			expect(modelInfo.id).toBe("claude-3-5-sonnet-v2@20241022")
+			expect(modelInfo.info).toBeDefined()
+			expect(modelInfo.info.maxTokens).toBe(8192)
+			expect(modelInfo.info.contextWindow).toBe(200_000)
+		})
+
+		it("should return default model if invalid model specified", () => {
+			const invalidHandler = new VertexHandler({
+				apiModelId: "invalid-model",
+				vertexProjectId: "test-project",
+				vertexRegion: "us-central1",
+			})
+			const modelInfo = invalidHandler.getModel()
+			expect(modelInfo.id).toBe("claude-3-5-sonnet-v2@20241022") // Default model
+		})
+	})
+})

+ 210 - 204
src/api/providers/__tests__/vscode-lm.test.ts

@@ -1,289 +1,295 @@
-import * as vscode from 'vscode';
-import { VsCodeLmHandler } from '../vscode-lm';
-import { ApiHandlerOptions } from '../../../shared/api';
-import { Anthropic } from '@anthropic-ai/sdk';
+import * as vscode from "vscode"
+import { VsCodeLmHandler } from "../vscode-lm"
+import { ApiHandlerOptions } from "../../../shared/api"
+import { Anthropic } from "@anthropic-ai/sdk"
 
 // Mock vscode namespace
-jest.mock('vscode', () => {
+jest.mock("vscode", () => {
 	class MockLanguageModelTextPart {
-		type = 'text';
+		type = "text"
 		constructor(public value: string) {}
 	}
 
 	class MockLanguageModelToolCallPart {
-		type = 'tool_call';
+		type = "tool_call"
 		constructor(
 			public callId: string,
 			public name: string,
-			public input: any
+			public input: any,
 		) {}
 	}
 
 	return {
 		workspace: {
 			onDidChangeConfiguration: jest.fn((callback) => ({
-				dispose: jest.fn()
-			}))
+				dispose: jest.fn(),
+			})),
 		},
 		CancellationTokenSource: jest.fn(() => ({
 			token: {
 				isCancellationRequested: false,
-				onCancellationRequested: jest.fn()
+				onCancellationRequested: jest.fn(),
 			},
 			cancel: jest.fn(),
-			dispose: jest.fn()
+			dispose: jest.fn(),
 		})),
 		CancellationError: class CancellationError extends Error {
 			constructor() {
-				super('Operation cancelled');
-				this.name = 'CancellationError';
+				super("Operation cancelled")
+				this.name = "CancellationError"
 			}
 		},
 		LanguageModelChatMessage: {
 			Assistant: jest.fn((content) => ({
-				role: 'assistant',
-				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)]
+				role: "assistant",
+				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)],
 			})),
 			User: jest.fn((content) => ({
-				role: 'user',
-				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)]
-			}))
+				role: "user",
+				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)],
+			})),
 		},
 		LanguageModelTextPart: MockLanguageModelTextPart,
 		LanguageModelToolCallPart: MockLanguageModelToolCallPart,
 		lm: {
-			selectChatModels: jest.fn()
-		}
-	};
-});
+			selectChatModels: jest.fn(),
+		},
+	}
+})
 
 const mockLanguageModelChat = {
-	id: 'test-model',
-	name: 'Test Model',
-	vendor: 'test-vendor',
-	family: 'test-family',
-	version: '1.0',
+	id: "test-model",
+	name: "Test Model",
+	vendor: "test-vendor",
+	family: "test-family",
+	version: "1.0",
 	maxInputTokens: 4096,
 	sendRequest: jest.fn(),
-	countTokens: jest.fn()
-};
+	countTokens: jest.fn(),
+}
 
-describe('VsCodeLmHandler', () => {
-	let handler: VsCodeLmHandler;
+describe("VsCodeLmHandler", () => {
+	let handler: VsCodeLmHandler
 	const defaultOptions: ApiHandlerOptions = {
 		vsCodeLmModelSelector: {
-			vendor: 'test-vendor',
-			family: 'test-family'
-		}
-	};
+			vendor: "test-vendor",
+			family: "test-family",
+		},
+	}
 
 	beforeEach(() => {
-		jest.clearAllMocks();
-		handler = new VsCodeLmHandler(defaultOptions);
-	});
+		jest.clearAllMocks()
+		handler = new VsCodeLmHandler(defaultOptions)
+	})
 
 	afterEach(() => {
-		handler.dispose();
-	});
-
-	describe('constructor', () => {
-		it('should initialize with provided options', () => {
-			expect(handler).toBeDefined();
-			expect(vscode.workspace.onDidChangeConfiguration).toHaveBeenCalled();
-		});
-
-		it('should handle configuration changes', () => {
-			const callback = (vscode.workspace.onDidChangeConfiguration as jest.Mock).mock.calls[0][0];
-			callback({ affectsConfiguration: () => true });
+		handler.dispose()
+	})
+
+	describe("constructor", () => {
+		it("should initialize with provided options", () => {
+			expect(handler).toBeDefined()
+			expect(vscode.workspace.onDidChangeConfiguration).toHaveBeenCalled()
+		})
+
+		it("should handle configuration changes", () => {
+			const callback = (vscode.workspace.onDidChangeConfiguration as jest.Mock).mock.calls[0][0]
+			callback({ affectsConfiguration: () => true })
 			// Should reset client when config changes
-			expect(handler['client']).toBeNull();
-		});
-	});
-
-	describe('createClient', () => {
-		it('should create client with selector', async () => {
-			const mockModel = { ...mockLanguageModelChat };
-			(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel]);
-
-			const client = await handler['createClient']({
-				vendor: 'test-vendor',
-				family: 'test-family'
-			});
-
-			expect(client).toBeDefined();
-			expect(client.id).toBe('test-model');
+			expect(handler["client"]).toBeNull()
+		})
+	})
+
+	describe("createClient", () => {
+		it("should create client with selector", async () => {
+			const mockModel = { ...mockLanguageModelChat }
+			;(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel])
+
+			const client = await handler["createClient"]({
+				vendor: "test-vendor",
+				family: "test-family",
+			})
+
+			expect(client).toBeDefined()
+			expect(client.id).toBe("test-model")
 			expect(vscode.lm.selectChatModels).toHaveBeenCalledWith({
-				vendor: 'test-vendor',
-				family: 'test-family'
-			});
-		});
-
-		it('should return default client when no models available', async () => {
-			(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([]);
-
-			const client = await handler['createClient']({});
-			
-			expect(client).toBeDefined();
-			expect(client.id).toBe('default-lm');
-			expect(client.vendor).toBe('vscode');
-		});
-	});
-
-	describe('createMessage', () => {
+				vendor: "test-vendor",
+				family: "test-family",
+			})
+		})
+
+		it("should return default client when no models available", async () => {
+			;(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([])
+
+			const client = await handler["createClient"]({})
+
+			expect(client).toBeDefined()
+			expect(client.id).toBe("default-lm")
+			expect(client.vendor).toBe("vscode")
+		})
+	})
+
+	describe("createMessage", () => {
 		beforeEach(() => {
-			const mockModel = { ...mockLanguageModelChat };
-			(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel]);
-			mockLanguageModelChat.countTokens.mockResolvedValue(10);
-		});
-
-		it('should stream text responses', async () => {
-			const systemPrompt = 'You are a helpful assistant';
-			const messages: Anthropic.Messages.MessageParam[] = [{
-				role: 'user' as const,
-				content: 'Hello'
-			}];
-
-			const responseText = 'Hello! How can I help you?';
+			const mockModel = { ...mockLanguageModelChat }
+			;(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel])
+			mockLanguageModelChat.countTokens.mockResolvedValue(10)
+		})
+
+		it("should stream text responses", async () => {
+			const systemPrompt = "You are a helpful assistant"
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user" as const,
+					content: "Hello",
+				},
+			]
+
+			const responseText = "Hello! How can I help you?"
 			mockLanguageModelChat.sendRequest.mockResolvedValueOnce({
 				stream: (async function* () {
-					yield new vscode.LanguageModelTextPart(responseText);
-					return;
+					yield new vscode.LanguageModelTextPart(responseText)
+					return
 				})(),
 				text: (async function* () {
-					yield responseText;
-					return;
-				})()
-			});
+					yield responseText
+					return
+				})(),
+			})
 
-			const stream = handler.createMessage(systemPrompt, messages);
-			const chunks = [];
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks = []
 			for await (const chunk of stream) {
-				chunks.push(chunk);
+				chunks.push(chunk)
 			}
 
-			expect(chunks).toHaveLength(2); // Text chunk + usage chunk
+			expect(chunks).toHaveLength(2) // Text chunk + usage chunk
 			expect(chunks[0]).toEqual({
-				type: 'text',
-				text: responseText
-			});
+				type: "text",
+				text: responseText,
+			})
 			expect(chunks[1]).toMatchObject({
-				type: 'usage',
+				type: "usage",
 				inputTokens: expect.any(Number),
-				outputTokens: expect.any(Number)
-			});
-		});
-
-		it('should handle tool calls', async () => {
-			const systemPrompt = 'You are a helpful assistant';
-			const messages: Anthropic.Messages.MessageParam[] = [{
-				role: 'user' as const,
-				content: 'Calculate 2+2'
-			}];
+				outputTokens: expect.any(Number),
+			})
+		})
+
+		it("should handle tool calls", async () => {
+			const systemPrompt = "You are a helpful assistant"
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user" as const,
+					content: "Calculate 2+2",
+				},
+			]
 
 			const toolCallData = {
-				name: 'calculator',
-				arguments: { operation: 'add', numbers: [2, 2] },
-				callId: 'call-1'
-			};
+				name: "calculator",
+				arguments: { operation: "add", numbers: [2, 2] },
+				callId: "call-1",
+			}
 
 			mockLanguageModelChat.sendRequest.mockResolvedValueOnce({
 				stream: (async function* () {
 					yield new vscode.LanguageModelToolCallPart(
 						toolCallData.callId,
 						toolCallData.name,
-						toolCallData.arguments
-					);
-					return;
+						toolCallData.arguments,
+					)
+					return
 				})(),
 				text: (async function* () {
-					yield JSON.stringify({ type: 'tool_call', ...toolCallData });
-					return;
-				})()
-			});
+					yield JSON.stringify({ type: "tool_call", ...toolCallData })
+					return
+				})(),
+			})
 
-			const stream = handler.createMessage(systemPrompt, messages);
-			const chunks = [];
+			const stream = handler.createMessage(systemPrompt, messages)
+			const chunks = []
 			for await (const chunk of stream) {
-				chunks.push(chunk);
+				chunks.push(chunk)
 			}
 
-			expect(chunks).toHaveLength(2); // Tool call chunk + usage chunk
+			expect(chunks).toHaveLength(2) // Tool call chunk + usage chunk
 			expect(chunks[0]).toEqual({
-				type: 'text',
-				text: JSON.stringify({ type: 'tool_call', ...toolCallData })
-			});
-		});
-
-		it('should handle errors', async () => {
-			const systemPrompt = 'You are a helpful assistant';
-			const messages: Anthropic.Messages.MessageParam[] = [{
-				role: 'user' as const,
-				content: 'Hello'
-			}];
-
-			mockLanguageModelChat.sendRequest.mockRejectedValueOnce(new Error('API Error'));
+				type: "text",
+				text: JSON.stringify({ type: "tool_call", ...toolCallData }),
+			})
+		})
+
+		it("should handle errors", async () => {
+			const systemPrompt = "You are a helpful assistant"
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user" as const,
+					content: "Hello",
+				},
+			]
+
+			mockLanguageModelChat.sendRequest.mockRejectedValueOnce(new Error("API Error"))
 
 			await expect(async () => {
-				const stream = handler.createMessage(systemPrompt, messages);
+				const stream = handler.createMessage(systemPrompt, messages)
 				for await (const _ of stream) {
 					// consume stream
 				}
-			}).rejects.toThrow('API Error');
-		});
-	});
-
-	describe('getModel', () => {
-		it('should return model info when client exists', async () => {
-			const mockModel = { ...mockLanguageModelChat };
-			(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel]);
-			
+			}).rejects.toThrow("API Error")
+		})
+	})
+
+	describe("getModel", () => {
+		it("should return model info when client exists", async () => {
+			const mockModel = { ...mockLanguageModelChat }
+			;(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel])
+
 			// Initialize client
-			await handler['getClient']();
-			
-			const model = handler.getModel();
-			expect(model.id).toBe('test-model');
-			expect(model.info).toBeDefined();
-			expect(model.info.contextWindow).toBe(4096);
-		});
-
-		it('should return fallback model info when no client exists', () => {
-			const model = handler.getModel();
-			expect(model.id).toBe('test-vendor/test-family');
-			expect(model.info).toBeDefined();
-		});
-	});
-
-	describe('completePrompt', () => {
-		it('should complete single prompt', async () => {
-			const mockModel = { ...mockLanguageModelChat };
-			(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel]);
-
-			const responseText = 'Completed text';
+			await handler["getClient"]()
+
+			const model = handler.getModel()
+			expect(model.id).toBe("test-model")
+			expect(model.info).toBeDefined()
+			expect(model.info.contextWindow).toBe(4096)
+		})
+
+		it("should return fallback model info when no client exists", () => {
+			const model = handler.getModel()
+			expect(model.id).toBe("test-vendor/test-family")
+			expect(model.info).toBeDefined()
+		})
+	})
+
+	describe("completePrompt", () => {
+		it("should complete single prompt", async () => {
+			const mockModel = { ...mockLanguageModelChat }
+			;(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel])
+
+			const responseText = "Completed text"
 			mockLanguageModelChat.sendRequest.mockResolvedValueOnce({
 				stream: (async function* () {
-					yield new vscode.LanguageModelTextPart(responseText);
-					return;
+					yield new vscode.LanguageModelTextPart(responseText)
+					return
 				})(),
 				text: (async function* () {
-					yield responseText;
-					return;
-				})()
-			});
-
-			const result = await handler.completePrompt('Test prompt');
-			expect(result).toBe(responseText);
-			expect(mockLanguageModelChat.sendRequest).toHaveBeenCalled();
-		});
-
-		it('should handle errors during completion', async () => {
-			const mockModel = { ...mockLanguageModelChat };
-			(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel]);
-
-			mockLanguageModelChat.sendRequest.mockRejectedValueOnce(new Error('Completion failed'));
-
-			await expect(handler.completePrompt('Test prompt'))
-				.rejects
-				.toThrow('VSCode LM completion error: Completion failed');
-		});
-	});
-});
+					yield responseText
+					return
+				})(),
+			})
+
+			const result = await handler.completePrompt("Test prompt")
+			expect(result).toBe(responseText)
+			expect(mockLanguageModelChat.sendRequest).toHaveBeenCalled()
+		})
+
+		it("should handle errors during completion", async () => {
+			const mockModel = { ...mockLanguageModelChat }
+			;(vscode.lm.selectChatModels as jest.Mock).mockResolvedValueOnce([mockModel])
+
+			mockLanguageModelChat.sendRequest.mockRejectedValueOnce(new Error("Completion failed"))
+
+			await expect(handler.completePrompt("Test prompt")).rejects.toThrow(
+				"VSCode LM completion error: Completion failed",
+			)
+		})
+	})
+})

+ 3 - 3
src/api/providers/anthropic.ts

@@ -181,14 +181,14 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
 				max_tokens: this.getModel().info.maxTokens || 8192,
 				temperature: 0,
 				messages: [{ role: "user", content: prompt }],
-				stream: false
+				stream: false,
 			})
 
 			const content = response.content[0]
-			if (content.type === 'text') {
+			if (content.type === "text") {
 				return content.text
 			}
-			return ''
+			return ""
 		} catch (error) {
 			if (error instanceof Error) {
 				throw new Error(`Anthropic completion error: ${error.message}`)

+ 255 - 249
src/api/providers/bedrock.ts

@@ -1,4 +1,9 @@
-import { BedrockRuntimeClient, ConverseStreamCommand, ConverseCommand, BedrockRuntimeClientConfig } from "@aws-sdk/client-bedrock-runtime"
+import {
+	BedrockRuntimeClient,
+	ConverseStreamCommand,
+	ConverseCommand,
+	BedrockRuntimeClientConfig,
+} from "@aws-sdk/client-bedrock-runtime"
 import { Anthropic } from "@anthropic-ai/sdk"
 import { ApiHandler, SingleCompletionHandler } from "../"
 import { ApiHandlerOptions, BedrockModelId, ModelInfo, bedrockDefaultModelId, bedrockModels } from "../../shared/api"
@@ -7,275 +12,276 @@ import { convertToBedrockConverseMessages, convertToAnthropicMessage } from "../
 
 // Define types for stream events based on AWS SDK
 export interface StreamEvent {
-    messageStart?: {
-        role?: string;
-    };
-    messageStop?: {
-        stopReason?: "end_turn" | "tool_use" | "max_tokens" | "stop_sequence";
-        additionalModelResponseFields?: Record<string, unknown>;
-    };
-    contentBlockStart?: {
-        start?: {
-            text?: string;
-        };
-        contentBlockIndex?: number;
-    };
-    contentBlockDelta?: {
-        delta?: {
-            text?: string;
-        };
-        contentBlockIndex?: number;
-    };
-    metadata?: {
-        usage?: {
-            inputTokens: number;
-            outputTokens: number;
-            totalTokens?: number; // Made optional since we don't use it
-        };
-        metrics?: {
-            latencyMs: number;
-        };
-    };
+	messageStart?: {
+		role?: string
+	}
+	messageStop?: {
+		stopReason?: "end_turn" | "tool_use" | "max_tokens" | "stop_sequence"
+		additionalModelResponseFields?: Record<string, unknown>
+	}
+	contentBlockStart?: {
+		start?: {
+			text?: string
+		}
+		contentBlockIndex?: number
+	}
+	contentBlockDelta?: {
+		delta?: {
+			text?: string
+		}
+		contentBlockIndex?: number
+	}
+	metadata?: {
+		usage?: {
+			inputTokens: number
+			outputTokens: number
+			totalTokens?: number // Made optional since we don't use it
+		}
+		metrics?: {
+			latencyMs: number
+		}
+	}
 }
 
 export class AwsBedrockHandler implements ApiHandler, SingleCompletionHandler {
-    private options: ApiHandlerOptions
-    private client: BedrockRuntimeClient
+	private options: ApiHandlerOptions
+	private client: BedrockRuntimeClient
 
-    constructor(options: ApiHandlerOptions) {
-        this.options = options
-        
-        // Only include credentials if they actually exist
-        const clientConfig: BedrockRuntimeClientConfig = {
-            region: this.options.awsRegion || "us-east-1"
-        }
+	constructor(options: ApiHandlerOptions) {
+		this.options = options
 
-        if (this.options.awsAccessKey && this.options.awsSecretKey) {
-            // Create credentials object with all properties at once
-            clientConfig.credentials = {
-                accessKeyId: this.options.awsAccessKey,
-                secretAccessKey: this.options.awsSecretKey,
-                ...(this.options.awsSessionToken ? { sessionToken: this.options.awsSessionToken } : {})
-            }
-        }
+		// Only include credentials if they actually exist
+		const clientConfig: BedrockRuntimeClientConfig = {
+			region: this.options.awsRegion || "us-east-1",
+		}
 
-        this.client = new BedrockRuntimeClient(clientConfig)
-    }
+		if (this.options.awsAccessKey && this.options.awsSecretKey) {
+			// Create credentials object with all properties at once
+			clientConfig.credentials = {
+				accessKeyId: this.options.awsAccessKey,
+				secretAccessKey: this.options.awsSecretKey,
+				...(this.options.awsSessionToken ? { sessionToken: this.options.awsSessionToken } : {}),
+			}
+		}
 
-    async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
-        const modelConfig = this.getModel()
-        
-        // Handle cross-region inference
-        let modelId: string
-        if (this.options.awsUseCrossRegionInference) {
-            let regionPrefix = (this.options.awsRegion || "").slice(0, 3)
-            switch (regionPrefix) {
-                case "us-":
-                    modelId = `us.${modelConfig.id}`
-                    break
-                case "eu-":
-                    modelId = `eu.${modelConfig.id}`
-                    break
-                default:
-                    modelId = modelConfig.id
-                    break
-            }
-        } else {
-            modelId = modelConfig.id
-        }
+		this.client = new BedrockRuntimeClient(clientConfig)
+	}
 
-        // Convert messages to Bedrock format
-        const formattedMessages = convertToBedrockConverseMessages(messages)
+	async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
+		const modelConfig = this.getModel()
 
-        // Construct the payload
-        const payload = {
-            modelId,
-            messages: formattedMessages,
-            system: [{ text: systemPrompt }],
-            inferenceConfig: {
-                maxTokens: modelConfig.info.maxTokens || 5000,
-                temperature: 0.3,
-                topP: 0.1,
-                ...(this.options.awsUsePromptCache ? {
-                    promptCache: {
-                        promptCacheId: this.options.awspromptCacheId || ""
-                    }
-                } : {})
-            }
-        }
+		// Handle cross-region inference
+		let modelId: string
+		if (this.options.awsUseCrossRegionInference) {
+			let regionPrefix = (this.options.awsRegion || "").slice(0, 3)
+			switch (regionPrefix) {
+				case "us-":
+					modelId = `us.${modelConfig.id}`
+					break
+				case "eu-":
+					modelId = `eu.${modelConfig.id}`
+					break
+				default:
+					modelId = modelConfig.id
+					break
+			}
+		} else {
+			modelId = modelConfig.id
+		}
 
-        try {
-            const command = new ConverseStreamCommand(payload)
-            const response = await this.client.send(command)
+		// Convert messages to Bedrock format
+		const formattedMessages = convertToBedrockConverseMessages(messages)
 
-            if (!response.stream) {
-                throw new Error('No stream available in the response')
-            }
+		// Construct the payload
+		const payload = {
+			modelId,
+			messages: formattedMessages,
+			system: [{ text: systemPrompt }],
+			inferenceConfig: {
+				maxTokens: modelConfig.info.maxTokens || 5000,
+				temperature: 0.3,
+				topP: 0.1,
+				...(this.options.awsUsePromptCache
+					? {
+							promptCache: {
+								promptCacheId: this.options.awspromptCacheId || "",
+							},
+						}
+					: {}),
+			},
+		}
 
-            for await (const chunk of response.stream) {
-                // Parse the chunk as JSON if it's a string (for tests)
-                let streamEvent: StreamEvent
-                try {
-                    streamEvent = typeof chunk === 'string' ? 
-                        JSON.parse(chunk) : 
-                        chunk as unknown as StreamEvent
-                } catch (e) {
-                    console.error('Failed to parse stream event:', e)
-                    continue
-                }
+		try {
+			const command = new ConverseStreamCommand(payload)
+			const response = await this.client.send(command)
 
-                // Handle metadata events first
-                if (streamEvent.metadata?.usage) {
-                    yield {
-                        type: "usage",
-                        inputTokens: streamEvent.metadata.usage.inputTokens || 0,
-                        outputTokens: streamEvent.metadata.usage.outputTokens || 0
-                    }
-                    continue
-                }
+			if (!response.stream) {
+				throw new Error("No stream available in the response")
+			}
 
-                // Handle message start
-                if (streamEvent.messageStart) {
-                    continue
-                }
+			for await (const chunk of response.stream) {
+				// Parse the chunk as JSON if it's a string (for tests)
+				let streamEvent: StreamEvent
+				try {
+					streamEvent = typeof chunk === "string" ? JSON.parse(chunk) : (chunk as unknown as StreamEvent)
+				} catch (e) {
+					console.error("Failed to parse stream event:", e)
+					continue
+				}
 
-                // Handle content blocks
-                if (streamEvent.contentBlockStart?.start?.text) {
-                    yield {
-                        type: "text",
-                        text: streamEvent.contentBlockStart.start.text
-                    }
-                    continue
-                }
+				// Handle metadata events first
+				if (streamEvent.metadata?.usage) {
+					yield {
+						type: "usage",
+						inputTokens: streamEvent.metadata.usage.inputTokens || 0,
+						outputTokens: streamEvent.metadata.usage.outputTokens || 0,
+					}
+					continue
+				}
 
-                // Handle content deltas
-                if (streamEvent.contentBlockDelta?.delta?.text) {
-                    yield {
-                        type: "text",
-                        text: streamEvent.contentBlockDelta.delta.text
-                    }
-                    continue
-                }
+				// Handle message start
+				if (streamEvent.messageStart) {
+					continue
+				}
 
-                // Handle message stop
-                if (streamEvent.messageStop) {
-                    continue
-                }
-            }
+				// Handle content blocks
+				if (streamEvent.contentBlockStart?.start?.text) {
+					yield {
+						type: "text",
+						text: streamEvent.contentBlockStart.start.text,
+					}
+					continue
+				}
 
-        } catch (error: unknown) {
-            console.error('Bedrock Runtime API Error:', error)
-            // Only access stack if error is an Error object
-            if (error instanceof Error) {
-                console.error('Error stack:', error.stack)
-                yield {
-                    type: "text",
-                    text: `Error: ${error.message}`
-                }
-                yield {
-                    type: "usage",
-                    inputTokens: 0,
-                    outputTokens: 0
-                }
-                throw error
-            } else {
-                const unknownError = new Error("An unknown error occurred")
-                yield {
-                    type: "text",
-                    text: unknownError.message
-                }
-                yield {
-                    type: "usage",
-                    inputTokens: 0,
-                    outputTokens: 0
-                }
-                throw unknownError
-            }
-        }
-    }
+				// Handle content deltas
+				if (streamEvent.contentBlockDelta?.delta?.text) {
+					yield {
+						type: "text",
+						text: streamEvent.contentBlockDelta.delta.text,
+					}
+					continue
+				}
 
-    getModel(): { id: BedrockModelId | string; info: ModelInfo } {
-        const modelId = this.options.apiModelId
-        if (modelId) {
-            // For tests, allow any model ID
-            if (process.env.NODE_ENV === 'test') {
-                return {
-                    id: modelId,
-                    info: {
-                        maxTokens: 5000,
-                        contextWindow: 128_000,
-                        supportsPromptCache: false
-                    }
-                }
-            }
-            // For production, validate against known models
-            if (modelId in bedrockModels) {
-                const id = modelId as BedrockModelId
-                return { id, info: bedrockModels[id] }
-            }
-        }
-        return {
-            id: bedrockDefaultModelId,
-            info: bedrockModels[bedrockDefaultModelId]
-        }
-    }
+				// Handle message stop
+				if (streamEvent.messageStop) {
+					continue
+				}
+			}
+		} catch (error: unknown) {
+			console.error("Bedrock Runtime API Error:", error)
+			// Only access stack if error is an Error object
+			if (error instanceof Error) {
+				console.error("Error stack:", error.stack)
+				yield {
+					type: "text",
+					text: `Error: ${error.message}`,
+				}
+				yield {
+					type: "usage",
+					inputTokens: 0,
+					outputTokens: 0,
+				}
+				throw error
+			} else {
+				const unknownError = new Error("An unknown error occurred")
+				yield {
+					type: "text",
+					text: unknownError.message,
+				}
+				yield {
+					type: "usage",
+					inputTokens: 0,
+					outputTokens: 0,
+				}
+				throw unknownError
+			}
+		}
+	}
 
-    async completePrompt(prompt: string): Promise<string> {
-        try {
-            const modelConfig = this.getModel()
-            
-            // Handle cross-region inference
-            let modelId: string
-            if (this.options.awsUseCrossRegionInference) {
-                let regionPrefix = (this.options.awsRegion || "").slice(0, 3)
-                switch (regionPrefix) {
-                    case "us-":
-                        modelId = `us.${modelConfig.id}`
-                        break
-                    case "eu-":
-                        modelId = `eu.${modelConfig.id}`
-                        break
-                    default:
-                        modelId = modelConfig.id
-                        break
-                }
-            } else {
-                modelId = modelConfig.id
-            }
+	getModel(): { id: BedrockModelId | string; info: ModelInfo } {
+		const modelId = this.options.apiModelId
+		if (modelId) {
+			// For tests, allow any model ID
+			if (process.env.NODE_ENV === "test") {
+				return {
+					id: modelId,
+					info: {
+						maxTokens: 5000,
+						contextWindow: 128_000,
+						supportsPromptCache: false,
+					},
+				}
+			}
+			// For production, validate against known models
+			if (modelId in bedrockModels) {
+				const id = modelId as BedrockModelId
+				return { id, info: bedrockModels[id] }
+			}
+		}
+		return {
+			id: bedrockDefaultModelId,
+			info: bedrockModels[bedrockDefaultModelId],
+		}
+	}
 
-            const payload = {
-                modelId,
-                messages: convertToBedrockConverseMessages([{
-                    role: "user",
-                    content: prompt
-                }]),
-                inferenceConfig: {
-                    maxTokens: modelConfig.info.maxTokens || 5000,
-                    temperature: 0.3,
-                    topP: 0.1
-                }
-            }
+	async completePrompt(prompt: string): Promise<string> {
+		try {
+			const modelConfig = this.getModel()
 
-            const command = new ConverseCommand(payload)
-            const response = await this.client.send(command)
+			// Handle cross-region inference
+			let modelId: string
+			if (this.options.awsUseCrossRegionInference) {
+				let regionPrefix = (this.options.awsRegion || "").slice(0, 3)
+				switch (regionPrefix) {
+					case "us-":
+						modelId = `us.${modelConfig.id}`
+						break
+					case "eu-":
+						modelId = `eu.${modelConfig.id}`
+						break
+					default:
+						modelId = modelConfig.id
+						break
+				}
+			} else {
+				modelId = modelConfig.id
+			}
 
-            if (response.output && response.output instanceof Uint8Array) {
-                try {
-                    const outputStr = new TextDecoder().decode(response.output)
-                    const output = JSON.parse(outputStr)
-                    if (output.content) {
-                        return output.content
-                    }
-                } catch (parseError) {
-                    console.error('Failed to parse Bedrock response:', parseError)
-                }
-            }
-            return ''
-        } catch (error) {
-            if (error instanceof Error) {
-                throw new Error(`Bedrock completion error: ${error.message}`)
-            }
-            throw error
-        }
-    }
+			const payload = {
+				modelId,
+				messages: convertToBedrockConverseMessages([
+					{
+						role: "user",
+						content: prompt,
+					},
+				]),
+				inferenceConfig: {
+					maxTokens: modelConfig.info.maxTokens || 5000,
+					temperature: 0.3,
+					topP: 0.1,
+				},
+			}
+
+			const command = new ConverseCommand(payload)
+			const response = await this.client.send(command)
+
+			if (response.output && response.output instanceof Uint8Array) {
+				try {
+					const outputStr = new TextDecoder().decode(response.output)
+					const output = JSON.parse(outputStr)
+					if (output.content) {
+						return output.content
+					}
+				} catch (parseError) {
+					console.error("Failed to parse Bedrock response:", parseError)
+				}
+			}
+			return ""
+		} catch (error) {
+			if (error instanceof Error) {
+				throw new Error(`Bedrock completion error: ${error.message}`)
+			}
+			throw error
+		}
+	}
 }

+ 19 - 19
src/api/providers/deepseek.ts

@@ -3,24 +3,24 @@ import { ApiHandlerOptions, ModelInfo } from "../../shared/api"
 import { deepSeekModels, deepSeekDefaultModelId } from "../../shared/api"
 
 export class DeepSeekHandler extends OpenAiHandler {
-    constructor(options: ApiHandlerOptions) {
-        if (!options.deepSeekApiKey) {
-            throw new Error("DeepSeek API key is required. Please provide it in the settings.")
-        }
-        super({
-            ...options,
-            openAiApiKey: options.deepSeekApiKey,
-            openAiModelId: options.deepSeekModelId ?? deepSeekDefaultModelId,
-            openAiBaseUrl: options.deepSeekBaseUrl ?? "https://api.deepseek.com/v1",
-            includeMaxTokens: true
-        })
-    }
+	constructor(options: ApiHandlerOptions) {
+		if (!options.deepSeekApiKey) {
+			throw new Error("DeepSeek API key is required. Please provide it in the settings.")
+		}
+		super({
+			...options,
+			openAiApiKey: options.deepSeekApiKey,
+			openAiModelId: options.deepSeekModelId ?? deepSeekDefaultModelId,
+			openAiBaseUrl: options.deepSeekBaseUrl ?? "https://api.deepseek.com/v1",
+			includeMaxTokens: true,
+		})
+	}
 
-    override getModel(): { id: string; info: ModelInfo } {
-        const modelId = this.options.deepSeekModelId ?? deepSeekDefaultModelId
-        return {
-            id: modelId,
-            info: deepSeekModels[modelId as keyof typeof deepSeekModels] || deepSeekModels[deepSeekDefaultModelId]
-        }
-    }
+	override getModel(): { id: string; info: ModelInfo } {
+		const modelId = this.options.deepSeekModelId ?? deepSeekDefaultModelId
+		return {
+			id: modelId,
+			info: deepSeekModels[modelId as keyof typeof deepSeekModels] || deepSeekModels[deepSeekDefaultModelId],
+		}
+	}
 }

+ 22 - 19
src/api/providers/glama.ts

@@ -72,17 +72,17 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
 			maxTokens = 8_192
 		}
 
-		const { data: completion, response } = await this.client.chat.completions.create({
-			model: this.getModel().id,
-			max_tokens: maxTokens,
-			temperature: 0,
-			messages: openAiMessages,
-			stream: true,
-		}).withResponse();
-
-		const completionRequestId = response.headers.get(
-			'x-completion-request-id',
-		);
+		const { data: completion, response } = await this.client.chat.completions
+			.create({
+				model: this.getModel().id,
+				max_tokens: maxTokens,
+				temperature: 0,
+				messages: openAiMessages,
+				stream: true,
+			})
+			.withResponse()
+
+		const completionRequestId = response.headers.get("x-completion-request-id")
 
 		for await (const chunk of completion) {
 			const delta = chunk.choices[0]?.delta
@@ -96,13 +96,16 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
 		}
 
 		try {
-			const response = await axios.get(`https://glama.ai/api/gateway/v1/completion-requests/${completionRequestId}`, {
-				headers: {
-					Authorization: `Bearer ${this.options.glamaApiKey}`,
+			const response = await axios.get(
+				`https://glama.ai/api/gateway/v1/completion-requests/${completionRequestId}`,
+				{
+					headers: {
+						Authorization: `Bearer ${this.options.glamaApiKey}`,
+					},
 				},
-			})
+			)
 
-			const completionRequest = response.data;
+			const completionRequest = response.data
 
 			if (completionRequest.tokenUsage) {
 				yield {
@@ -113,7 +116,7 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
 					outputTokens: completionRequest.tokenUsage.completionTokens,
 					totalCost: parseFloat(completionRequest.totalCostUsd),
 				}
-			}			
+			}
 		} catch (error) {
 			console.error("Error fetching Glama completion details", error)
 		}
@@ -126,7 +129,7 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
 		if (modelId && modelInfo) {
 			return { id: modelId, info: modelInfo }
 		}
-		
+
 		return { id: glamaDefaultModelId, info: glamaDefaultModelInfo }
 	}
 
@@ -141,7 +144,7 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
 			if (this.getModel().id.startsWith("anthropic/")) {
 				requestOptions.max_tokens = 8192
 			}
-			
+
 			const response = await this.client.chat.completions.create(requestOptions)
 			return response.choices[0]?.message.content || ""
 		} catch (error) {

+ 1 - 1
src/api/providers/lmstudio.ts

@@ -60,7 +60,7 @@ export class LmStudioHandler implements ApiHandler, SingleCompletionHandler {
 				model: this.getModel().id,
 				messages: [{ role: "user", content: prompt }],
 				temperature: 0,
-				stream: false
+				stream: false,
 			})
 			return response.choices[0]?.message.content || ""
 		} catch (error) {

+ 1 - 1
src/api/providers/ollama.ts

@@ -53,7 +53,7 @@ export class OllamaHandler implements ApiHandler, SingleCompletionHandler {
 				model: this.getModel().id,
 				messages: [{ role: "user", content: prompt }],
 				temperature: 0,
-				stream: false
+				stream: false,
 			})
 			return response.choices[0]?.message.content || ""
 		} catch (error) {

+ 6 - 3
src/api/providers/openai-native.ts

@@ -32,7 +32,10 @@ export class OpenAiNativeHandler implements ApiHandler, SingleCompletionHandler
 				// o1 doesnt support streaming or non-1 temp but does support a developer prompt
 				const response = await this.client.chat.completions.create({
 					model: modelId,
-					messages: [{ role: modelId === "o1" ? "developer" : "user", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
+					messages: [
+						{ role: modelId === "o1" ? "developer" : "user", content: systemPrompt },
+						...convertToOpenAiMessages(messages),
+					],
 				})
 				yield {
 					type: "text",
@@ -98,14 +101,14 @@ export class OpenAiNativeHandler implements ApiHandler, SingleCompletionHandler
 					// o1 doesn't support non-1 temp
 					requestOptions = {
 						model: modelId,
-						messages: [{ role: "user", content: prompt }]
+						messages: [{ role: "user", content: prompt }],
 					}
 					break
 				default:
 					requestOptions = {
 						model: modelId,
 						messages: [{ role: "user", content: prompt }],
-						temperature: 0
+						temperature: 0,
 					}
 			}
 

+ 5 - 5
src/api/providers/openai.ts

@@ -17,7 +17,7 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
 	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
-		const urlHost = new URL(this.options.openAiBaseUrl ?? "").host;
+		const urlHost = new URL(this.options.openAiBaseUrl ?? "").host
 		if (urlHost === "azure.com" || urlHost.endsWith(".azure.com")) {
 			this.client = new AzureOpenAI({
 				baseURL: this.options.openAiBaseUrl,
@@ -39,7 +39,7 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
 		if (this.options.openAiStreamingEnabled ?? true) {
 			const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
 				role: "system",
-				content: systemPrompt
+				content: systemPrompt,
 			}
 			const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {
 				model: modelId,
@@ -74,14 +74,14 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
 			// o1 for instance doesnt support streaming, non-1 temp, or system prompt
 			const systemMessage: OpenAI.Chat.ChatCompletionUserMessageParam = {
 				role: "user",
-				content: systemPrompt
+				content: systemPrompt,
 			}
 			const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = {
 				model: modelId,
 				messages: [systemMessage, ...convertToOpenAiMessages(messages)],
 			}
 			const response = await this.client.chat.completions.create(requestOptions)
-			
+
 			yield {
 				type: "text",
 				text: response.choices[0]?.message.content || "",
@@ -108,7 +108,7 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
 				messages: [{ role: "user", content: prompt }],
 				temperature: 0,
 			}
-			
+
 			const response = await this.client.chat.completions.create(requestOptions)
 			return response.choices[0]?.message.content || ""
 		} catch (error) {

+ 14 - 12
src/api/providers/openrouter.ts

@@ -9,12 +9,12 @@ import delay from "delay"
 
 // Add custom interface for OpenRouter params
 type OpenRouterChatCompletionParams = OpenAI.Chat.ChatCompletionCreateParams & {
-    transforms?: string[];
+	transforms?: string[]
 }
 
 // Add custom interface for OpenRouter usage chunk
 interface OpenRouterApiStreamUsageChunk extends ApiStreamUsageChunk {
-    fullResponseText: string;
+	fullResponseText: string
 }
 
 import { SingleCompletionHandler } from ".."
@@ -35,7 +35,10 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
 		})
 	}
 
-	async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): AsyncGenerator<ApiStreamChunk> {
+	async *createMessage(
+		systemPrompt: string,
+		messages: Anthropic.Messages.MessageParam[],
+	): AsyncGenerator<ApiStreamChunk> {
 		// Convert Anthropic messages to OpenAI format
 		const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
 			{ role: "system", content: systemPrompt },
@@ -108,7 +111,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
 				break
 		}
 		// https://openrouter.ai/docs/transforms
-		let fullResponseText = "";
+		let fullResponseText = ""
 		const stream = await this.client.chat.completions.create({
 			model: this.getModel().id,
 			max_tokens: maxTokens,
@@ -116,8 +119,8 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
 			messages: openAiMessages,
 			stream: true,
 			// This way, the transforms field will only be included in the parameters when openRouterUseMiddleOutTransform is true.
-			...(this.options.openRouterUseMiddleOutTransform && { transforms: ["middle-out"] })
-		} as OpenRouterChatCompletionParams);
+			...(this.options.openRouterUseMiddleOutTransform && { transforms: ["middle-out"] }),
+		} as OpenRouterChatCompletionParams)
 
 		let genId: string | undefined
 
@@ -135,11 +138,11 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
 
 			const delta = chunk.choices[0]?.delta
 			if (delta?.content) {
-				fullResponseText += delta.content;
+				fullResponseText += delta.content
 				yield {
 					type: "text",
 					text: delta.content,
-				} as ApiStreamChunk;
+				} as ApiStreamChunk
 			}
 			// if (chunk.usage) {
 			// 	yield {
@@ -170,13 +173,12 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
 				inputTokens: generation?.native_tokens_prompt || 0,
 				outputTokens: generation?.native_tokens_completion || 0,
 				totalCost: generation?.total_cost || 0,
-				fullResponseText
-			} as OpenRouterApiStreamUsageChunk;
+				fullResponseText,
+			} as OpenRouterApiStreamUsageChunk
 		} catch (error) {
 			// ignore if fails
 			console.error("Error fetching OpenRouter generation details:", error)
 		}
-
 	}
 	getModel(): { id: string; info: ModelInfo } {
 		const modelId = this.options.openRouterModelId
@@ -193,7 +195,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
 				model: this.getModel().id,
 				messages: [{ role: "user", content: prompt }],
 				temperature: 0,
-				stream: false
+				stream: false,
 			})
 
 			if ("error" in response) {

+ 3 - 3
src/api/providers/vertex.ts

@@ -91,14 +91,14 @@ export class VertexHandler implements ApiHandler, SingleCompletionHandler {
 				max_tokens: this.getModel().info.maxTokens || 8192,
 				temperature: 0,
 				messages: [{ role: "user", content: prompt }],
-				stream: false
+				stream: false,
 			})
 
 			const content = response.content[0]
-			if (content.type === 'text') {
+			if (content.type === "text") {
 				return content.text
 			}
-			return ''
+			return ""
 		} catch (error) {
 			if (error instanceof Error) {
 				throw new Error(`Vertex completion error: ${error.message}`)

+ 221 - 238
src/api/providers/vscode-lm.ts

@@ -1,31 +1,31 @@
-import { Anthropic } from "@anthropic-ai/sdk";
-import * as vscode from 'vscode';
-import { ApiHandler, SingleCompletionHandler } from "../";
-import { calculateApiCost } from "../../utils/cost";
-import { ApiStream } from "../transform/stream";
-import { convertToVsCodeLmMessages } from "../transform/vscode-lm-format";
-import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "../../shared/vsCodeSelectorUtils";
-import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api";
+import { Anthropic } from "@anthropic-ai/sdk"
+import * as vscode from "vscode"
+import { ApiHandler, SingleCompletionHandler } from "../"
+import { calculateApiCost } from "../../utils/cost"
+import { ApiStream } from "../transform/stream"
+import { convertToVsCodeLmMessages } from "../transform/vscode-lm-format"
+import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "../../shared/vsCodeSelectorUtils"
+import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api"
 
 /**
  * Handles interaction with VS Code's Language Model API for chat-based operations.
  * This handler implements the ApiHandler interface to provide VS Code LM specific functionality.
- * 
+ *
  * @implements {ApiHandler}
- * 
+ *
  * @remarks
  * The handler manages a VS Code language model chat client and provides methods to:
  * - Create and manage chat client instances
  * - Stream messages using VS Code's Language Model API
  * - Retrieve model information
- * 
+ *
  * @example
  * ```typescript
  * const options = {
  *   vsCodeLmModelSelector: { vendor: "copilot", family: "gpt-4" }
  * };
  * const handler = new VsCodeLmHandler(options);
- * 
+ *
  * // Stream a conversation
  * const systemPrompt = "You are a helpful assistant";
  * const messages = [{ role: "user", content: "Hello!" }];
@@ -35,39 +35,36 @@ import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../..
  * ```
  */
 export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
-
-	private options: ApiHandlerOptions;
-	private client: vscode.LanguageModelChat | null;
-	private disposable: vscode.Disposable | null;
-	private currentRequestCancellation: vscode.CancellationTokenSource | null;
+	private options: ApiHandlerOptions
+	private client: vscode.LanguageModelChat | null
+	private disposable: vscode.Disposable | null
+	private currentRequestCancellation: vscode.CancellationTokenSource | null
 
 	constructor(options: ApiHandlerOptions) {
-		this.options = options;
-		this.client = null;
-		this.disposable = null;
-		this.currentRequestCancellation = null;
+		this.options = options
+		this.client = null
+		this.disposable = null
+		this.currentRequestCancellation = null
 
 		try {
 			// Listen for model changes and reset client
-			this.disposable = vscode.workspace.onDidChangeConfiguration(event => {
-				if (event.affectsConfiguration('lm')) {
+			this.disposable = vscode.workspace.onDidChangeConfiguration((event) => {
+				if (event.affectsConfiguration("lm")) {
 					try {
-						this.client = null;
-						this.ensureCleanState();
-					}
-					catch (error) {
-						console.error('Error during configuration change cleanup:', error);
+						this.client = null
+						this.ensureCleanState()
+					} catch (error) {
+						console.error("Error during configuration change cleanup:", error)
 					}
 				}
-			});
-		}
-		catch (error) {
+			})
+		} catch (error) {
 			// Ensure cleanup if constructor fails
-			this.dispose();
+			this.dispose()
 
 			throw new Error(
-				`Cline <Language Model API>: Failed to initialize handler: ${error instanceof Error ? error.message : 'Unknown error'}`
-			);
+				`Cline <Language Model API>: Failed to initialize handler: ${error instanceof Error ? error.message : "Unknown error"}`,
+			)
 		}
 	}
 
@@ -77,46 +74,46 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
 	 * @param selector - Selector criteria to filter language model chat instances
 	 * @returns Promise resolving to the first matching language model chat instance
 	 * @throws Error when no matching models are found with the given selector
-	 * 
+	 *
 	 * @example
 	 * const selector = { vendor: "copilot", family: "gpt-4o" };
 	 * const chatClient = await createClient(selector);
 	 */
 	async createClient(selector: vscode.LanguageModelChatSelector): Promise<vscode.LanguageModelChat> {
 		try {
-			const models = await vscode.lm.selectChatModels(selector);
+			const models = await vscode.lm.selectChatModels(selector)
 
 			// Use first available model or create a minimal model object
 			if (models && Array.isArray(models) && models.length > 0) {
-				return models[0];
+				return models[0]
 			}
 
 			// Create a minimal model if no models are available
 			return {
-				id: 'default-lm',
-				name: 'Default Language Model',
-				vendor: 'vscode',
-				family: 'lm',
-				version: '1.0',
+				id: "default-lm",
+				name: "Default Language Model",
+				vendor: "vscode",
+				family: "lm",
+				version: "1.0",
 				maxInputTokens: 8192,
 				sendRequest: async (messages, options, token) => {
 					// Provide a minimal implementation
 					return {
 						stream: (async function* () {
 							yield new vscode.LanguageModelTextPart(
-								"Language model functionality is limited. Please check VS Code configuration."
-							);
+								"Language model functionality is limited. Please check VS Code configuration.",
+							)
 						})(),
 						text: (async function* () {
-							yield "Language model functionality is limited. Please check VS Code configuration.";
-						})()
-					};
+							yield "Language model functionality is limited. Please check VS Code configuration."
+						})(),
+					}
 				},
-				countTokens: async () => 0
-			};
+				countTokens: async () => 0,
+			}
 		} catch (error) {
-			const errorMessage = error instanceof Error ? error.message : 'Unknown error';
-			throw new Error(`Cline <Language Model API>: Failed to select model: ${errorMessage}`);
+			const errorMessage = error instanceof Error ? error.message : "Unknown error"
+			throw new Error(`Cline <Language Model API>: Failed to select model: ${errorMessage}`)
 		}
 	}
 
@@ -125,242 +122,234 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
 	 *
 	 * @param systemPrompt - The system prompt to initialize the conversation context
 	 * @param messages - An array of message parameters following the Anthropic message format
-	 * 
+	 *
 	 * @yields {ApiStream} An async generator that yields either text chunks or tool calls from the model response
-	 * 
+	 *
 	 * @throws {Error} When vsCodeLmModelSelector option is not provided
 	 * @throws {Error} When the response stream encounters an error
-	 * 
+	 *
 	 * @remarks
 	 * This method handles the initialization of the VS Code LM client if not already created,
 	 * converts the messages to VS Code LM format, and streams the response chunks.
 	 * Tool calls handling is currently a work in progress.
 	 */
 	dispose(): void {
-
 		if (this.disposable) {
-
-			this.disposable.dispose();
+			this.disposable.dispose()
 		}
 
 		if (this.currentRequestCancellation) {
-
-			this.currentRequestCancellation.cancel();
-			this.currentRequestCancellation.dispose();
+			this.currentRequestCancellation.cancel()
+			this.currentRequestCancellation.dispose()
 		}
 	}
 
 	private async countTokens(text: string | vscode.LanguageModelChatMessage): Promise<number> {
 		// Check for required dependencies
 		if (!this.client) {
-			console.warn('Cline <Language Model API>: No client available for token counting');
-			return 0;
+			console.warn("Cline <Language Model API>: No client available for token counting")
+			return 0
 		}
 
 		if (!this.currentRequestCancellation) {
-			console.warn('Cline <Language Model API>: No cancellation token available for token counting');
-			return 0;
+			console.warn("Cline <Language Model API>: No cancellation token available for token counting")
+			return 0
 		}
 
 		// Validate input
 		if (!text) {
-			console.debug('Cline <Language Model API>: Empty text provided for token counting');
-			return 0;
+			console.debug("Cline <Language Model API>: Empty text provided for token counting")
+			return 0
 		}
 
 		try {
 			// Handle different input types
-			let tokenCount: number;
+			let tokenCount: number
 
-			if (typeof text === 'string') {
-				tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token);
+			if (typeof text === "string") {
+				tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token)
 			} else if (text instanceof vscode.LanguageModelChatMessage) {
 				// For chat messages, ensure we have content
 				if (!text.content || (Array.isArray(text.content) && text.content.length === 0)) {
-					console.debug('Cline <Language Model API>: Empty chat message content');
-					return 0;
+					console.debug("Cline <Language Model API>: Empty chat message content")
+					return 0
 				}
-				tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token);
+				tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token)
 			} else {
-				console.warn('Cline <Language Model API>: Invalid input type for token counting');
-				return 0;
+				console.warn("Cline <Language Model API>: Invalid input type for token counting")
+				return 0
 			}
 
 			// Validate the result
-			if (typeof tokenCount !== 'number') {
-				console.warn('Cline <Language Model API>: Non-numeric token count received:', tokenCount);
-				return 0;
+			if (typeof tokenCount !== "number") {
+				console.warn("Cline <Language Model API>: Non-numeric token count received:", tokenCount)
+				return 0
 			}
 
 			if (tokenCount < 0) {
-				console.warn('Cline <Language Model API>: Negative token count received:', tokenCount);
-				return 0;
+				console.warn("Cline <Language Model API>: Negative token count received:", tokenCount)
+				return 0
 			}
 
-			return tokenCount;
-		}
-		catch (error) {
+			return tokenCount
+		} catch (error) {
 			// Handle specific error types
 			if (error instanceof vscode.CancellationError) {
-				console.debug('Cline <Language Model API>: Token counting cancelled by user');
-				return 0;
+				console.debug("Cline <Language Model API>: Token counting cancelled by user")
+				return 0
 			}
 
-			const errorMessage = error instanceof Error ? error.message : 'Unknown error';
-			console.warn('Cline <Language Model API>: Token counting failed:', errorMessage);
+			const errorMessage = error instanceof Error ? error.message : "Unknown error"
+			console.warn("Cline <Language Model API>: Token counting failed:", errorMessage)
 
 			// Log additional error details if available
 			if (error instanceof Error && error.stack) {
-				console.debug('Token counting error stack:', error.stack);
+				console.debug("Token counting error stack:", error.stack)
 			}
 
-			return 0; // Fallback to prevent stream interruption
+			return 0 // Fallback to prevent stream interruption
 		}
 	}
 
-	private async calculateTotalInputTokens(systemPrompt: string, vsCodeLmMessages: vscode.LanguageModelChatMessage[]): Promise<number> {
-
-		const systemTokens: number = await this.countTokens(systemPrompt);
+	private async calculateTotalInputTokens(
+		systemPrompt: string,
+		vsCodeLmMessages: vscode.LanguageModelChatMessage[],
+	): Promise<number> {
+		const systemTokens: number = await this.countTokens(systemPrompt)
 
-		const messageTokens: number[] = await Promise.all(
-			vsCodeLmMessages.map(msg => this.countTokens(msg))
-		);
+		const messageTokens: number[] = await Promise.all(vsCodeLmMessages.map((msg) => this.countTokens(msg)))
 
-		return systemTokens + messageTokens.reduce(
-			(sum: number, tokens: number): number => sum + tokens, 0
-		);
+		return systemTokens + messageTokens.reduce((sum: number, tokens: number): number => sum + tokens, 0)
 	}
 
 	private ensureCleanState(): void {
-
 		if (this.currentRequestCancellation) {
-
-			this.currentRequestCancellation.cancel();
-			this.currentRequestCancellation.dispose();
-			this.currentRequestCancellation = null;
+			this.currentRequestCancellation.cancel()
+			this.currentRequestCancellation.dispose()
+			this.currentRequestCancellation = null
 		}
 	}
 
 	private async getClient(): Promise<vscode.LanguageModelChat> {
 		if (!this.client) {
-			console.debug('Cline <Language Model API>: Getting client with options:', {
+			console.debug("Cline <Language Model API>: Getting client with options:", {
 				vsCodeLmModelSelector: this.options.vsCodeLmModelSelector,
 				hasOptions: !!this.options,
-				selectorKeys: this.options.vsCodeLmModelSelector ? Object.keys(this.options.vsCodeLmModelSelector) : []
-			});
+				selectorKeys: this.options.vsCodeLmModelSelector ? Object.keys(this.options.vsCodeLmModelSelector) : [],
+			})
 
 			try {
 				// Use default empty selector if none provided to get all available models
-				const selector = this.options?.vsCodeLmModelSelector || {};
-				console.debug('Cline <Language Model API>: Creating client with selector:', selector);
-				this.client = await this.createClient(selector);
+				const selector = this.options?.vsCodeLmModelSelector || {}
+				console.debug("Cline <Language Model API>: Creating client with selector:", selector)
+				this.client = await this.createClient(selector)
 			} catch (error) {
-				const message = error instanceof Error ? error.message : 'Unknown error';
-				console.error('Cline <Language Model API>: Client creation failed:', message);
-				throw new Error(`Cline <Language Model API>: Failed to create client: ${message}`);
+				const message = error instanceof Error ? error.message : "Unknown error"
+				console.error("Cline <Language Model API>: Client creation failed:", message)
+				throw new Error(`Cline <Language Model API>: Failed to create client: ${message}`)
 			}
 		}
 
-		return this.client;
+		return this.client
 	}
 
 	private cleanTerminalOutput(text: string): string {
 		if (!text) {
-			return '';
+			return ""
 		}
 
-		return text
-			// Нормализуем переносы строк
-			.replace(/\r\n/g, '\n')
-			.replace(/\r/g, '\n')
+		return (
+			text
+				// Нормализуем переносы строк
+				.replace(/\r\n/g, "\n")
+				.replace(/\r/g, "\n")
 
-			// Удаляем ANSI escape sequences
-			.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, '') // Полный набор ANSI sequences
-			.replace(/\x9B[0-?]*[ -/]*[@-~]/g, '')  // CSI sequences
+				// Удаляем ANSI escape sequences
+				.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "") // Полный набор ANSI sequences
+				.replace(/\x9B[0-?]*[ -/]*[@-~]/g, "") // CSI sequences
 
-			// Удаляем последовательности установки заголовка терминала и прочие OSC sequences
-			.replace(/\x1B\][0-9;]*(?:\x07|\x1B\\)/g, '')
+				// Удаляем последовательности установки заголовка терминала и прочие OSC sequences
+				.replace(/\x1B\][0-9;]*(?:\x07|\x1B\\)/g, "")
 
-			// Удаляем управляющие символы
-			.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F]/g, '')
+				// Удаляем управляющие символы
+				.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F]/g, "")
 
-			// Удаляем escape-последовательности VS Code
-			.replace(/\x1B[PD].*?\x1B\\/g, '')	  // DCS sequences
-			.replace(/\x1B_.*?\x1B\\/g, '')		 // APC sequences
-			.replace(/\x1B\^.*?\x1B\\/g, '')		// PM sequences
-			.replace(/\x1B\[[\d;]*[HfABCDEFGJKST]/g, '') // Cursor movement and clear screen
+				// Удаляем escape-последовательности VS Code
+				.replace(/\x1B[PD].*?\x1B\\/g, "") // DCS sequences
+				.replace(/\x1B_.*?\x1B\\/g, "") // APC sequences
+				.replace(/\x1B\^.*?\x1B\\/g, "") // PM sequences
+				.replace(/\x1B\[[\d;]*[HfABCDEFGJKST]/g, "") // Cursor movement and clear screen
 
-			// Удаляем пути Windows и служебную информацию
-			.replace(/^(?:PS )?[A-Z]:\\[^\n]*$/mg, '')
-			.replace(/^;?Cwd=.*$/mg, '')
+				// Удаляем пути Windows и служебную информацию
+				.replace(/^(?:PS )?[A-Z]:\\[^\n]*$/gm, "")
+				.replace(/^;?Cwd=.*$/gm, "")
 
-			// Очищаем экранированные последовательности
-			.replace(/\\x[0-9a-fA-F]{2}/g, '')
-			.replace(/\\u[0-9a-fA-F]{4}/g, '')
+				// Очищаем экранированные последовательности
+				.replace(/\\x[0-9a-fA-F]{2}/g, "")
+				.replace(/\\u[0-9a-fA-F]{4}/g, "")
 
-			// Финальная очистка
-			.replace(/\n{3,}/g, '\n\n')  // Убираем множественные пустые строки
-			.trim();
+				// Финальная очистка
+				.replace(/\n{3,}/g, "\n\n") // Убираем множественные пустые строки
+				.trim()
+		)
 	}
 
 	private cleanMessageContent(content: any): any {
 		if (!content) {
-			return content;
+			return content
 		}
 
-		if (typeof content === 'string') {
-			return this.cleanTerminalOutput(content);
+		if (typeof content === "string") {
+			return this.cleanTerminalOutput(content)
 		}
 
 		if (Array.isArray(content)) {
-			return content.map(item => this.cleanMessageContent(item));
+			return content.map((item) => this.cleanMessageContent(item))
 		}
 
-		if (typeof content === 'object') {
-			const cleaned: any = {};
+		if (typeof content === "object") {
+			const cleaned: any = {}
 			for (const [key, value] of Object.entries(content)) {
-				cleaned[key] = this.cleanMessageContent(value);
+				cleaned[key] = this.cleanMessageContent(value)
 			}
-			return cleaned;
+			return cleaned
 		}
 
-		return content;
+		return content
 	}
 
 	async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
-
 		// Ensure clean state before starting a new request
-		this.ensureCleanState();
-		const client: vscode.LanguageModelChat = await this.getClient();
+		this.ensureCleanState()
+		const client: vscode.LanguageModelChat = await this.getClient()
 
 		// Clean system prompt and messages
-		const cleanedSystemPrompt = this.cleanTerminalOutput(systemPrompt);
-		const cleanedMessages = messages.map(msg => ({
+		const cleanedSystemPrompt = this.cleanTerminalOutput(systemPrompt)
+		const cleanedMessages = messages.map((msg) => ({
 			...msg,
-			content: this.cleanMessageContent(msg.content)
-		}));
+			content: this.cleanMessageContent(msg.content),
+		}))
 
 		// Convert Anthropic messages to VS Code LM messages
 		const vsCodeLmMessages: vscode.LanguageModelChatMessage[] = [
 			vscode.LanguageModelChatMessage.Assistant(cleanedSystemPrompt),
 			...convertToVsCodeLmMessages(cleanedMessages),
-		];
+		]
 
 		// Initialize cancellation token for the request
-		this.currentRequestCancellation = new vscode.CancellationTokenSource();
+		this.currentRequestCancellation = new vscode.CancellationTokenSource()
 
 		// Calculate input tokens before starting the stream
-		const totalInputTokens: number = await this.calculateTotalInputTokens(systemPrompt, vsCodeLmMessages);
+		const totalInputTokens: number = await this.calculateTotalInputTokens(systemPrompt, vsCodeLmMessages)
 
 		// Accumulate the text and count at the end of the stream to reduce token counting overhead.
-		let accumulatedText: string = '';
+		let accumulatedText: string = ""
 
 		try {
-
 			// Create the response stream with minimal required options
 			const requestOptions: vscode.LanguageModelChatRequestOptions = {
-				justification: `Cline would like to use '${client.name}' from '${client.vendor}', Click 'Allow' to proceed.`
-			};
+				justification: `Cline would like to use '${client.name}' from '${client.vendor}', Click 'Allow' to proceed.`,
+			}
 
 			// Note: Tool support is currently provided by the VSCode Language Model API directly
 			// Extensions can register tools using vscode.lm.registerTool()
@@ -368,40 +357,40 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
 			const response: vscode.LanguageModelChatResponse = await client.sendRequest(
 				vsCodeLmMessages,
 				requestOptions,
-				this.currentRequestCancellation.token
-			);
+				this.currentRequestCancellation.token,
+			)
 
 			// Consume the stream and handle both text and tool call chunks
 			for await (const chunk of response.stream) {
 				if (chunk instanceof vscode.LanguageModelTextPart) {
 					// Validate text part value
-					if (typeof chunk.value !== 'string') {
-						console.warn('Cline <Language Model API>: Invalid text part value received:', chunk.value);
-						continue;
+					if (typeof chunk.value !== "string") {
+						console.warn("Cline <Language Model API>: Invalid text part value received:", chunk.value)
+						continue
 					}
 
-					accumulatedText += chunk.value;
+					accumulatedText += chunk.value
 					yield {
 						type: "text",
 						text: chunk.value,
-					};
+					}
 				} else if (chunk instanceof vscode.LanguageModelToolCallPart) {
 					try {
 						// Validate tool call parameters
-						if (!chunk.name || typeof chunk.name !== 'string') {
-							console.warn('Cline <Language Model API>: Invalid tool name received:', chunk.name);
-							continue;
+						if (!chunk.name || typeof chunk.name !== "string") {
+							console.warn("Cline <Language Model API>: Invalid tool name received:", chunk.name)
+							continue
 						}
 
-						if (!chunk.callId || typeof chunk.callId !== 'string') {
-							console.warn('Cline <Language Model API>: Invalid tool callId received:', chunk.callId);
-							continue;
+						if (!chunk.callId || typeof chunk.callId !== "string") {
+							console.warn("Cline <Language Model API>: Invalid tool callId received:", chunk.callId)
+							continue
 						}
 
 						// Ensure input is a valid object
-						if (!chunk.input || typeof chunk.input !== 'object') {
-							console.warn('Cline <Language Model API>: Invalid tool input received:', chunk.input);
-							continue;
+						if (!chunk.input || typeof chunk.input !== "object") {
+							console.warn("Cline <Language Model API>: Invalid tool input received:", chunk.input)
+							continue
 						}
 
 						// Convert tool calls to text format with proper error handling
@@ -409,82 +398,75 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
 							type: "tool_call",
 							name: chunk.name,
 							arguments: chunk.input,
-							callId: chunk.callId
-						};
+							callId: chunk.callId,
+						}
 
-						const toolCallText = JSON.stringify(toolCall);
-						accumulatedText += toolCallText;
+						const toolCallText = JSON.stringify(toolCall)
+						accumulatedText += toolCallText
 
 						// Log tool call for debugging
-						console.debug('Cline <Language Model API>: Processing tool call:', {
+						console.debug("Cline <Language Model API>: Processing tool call:", {
 							name: chunk.name,
 							callId: chunk.callId,
-							inputSize: JSON.stringify(chunk.input).length
-						});
+							inputSize: JSON.stringify(chunk.input).length,
+						})
 
 						yield {
 							type: "text",
 							text: toolCallText,
-						};
+						}
 					} catch (error) {
-						console.error('Cline <Language Model API>: Failed to process tool call:', error);
+						console.error("Cline <Language Model API>: Failed to process tool call:", error)
 						// Continue processing other chunks even if one fails
-						continue;
+						continue
 					}
 				} else {
-					console.warn('Cline <Language Model API>: Unknown chunk type received:', chunk);
+					console.warn("Cline <Language Model API>: Unknown chunk type received:", chunk)
 				}
 			}
 
 			// Count tokens in the accumulated text after stream completion
-			const totalOutputTokens: number = await this.countTokens(accumulatedText);
+			const totalOutputTokens: number = await this.countTokens(accumulatedText)
 
 			// Report final usage after stream completion
 			yield {
 				type: "usage",
 				inputTokens: totalInputTokens,
 				outputTokens: totalOutputTokens,
-				totalCost: calculateApiCost(
-					this.getModel().info,
-					totalInputTokens,
-					totalOutputTokens
-				)
-			};
-		}
-		catch (error: unknown) {
-
-			this.ensureCleanState();
+				totalCost: calculateApiCost(this.getModel().info, totalInputTokens, totalOutputTokens),
+			}
+		} catch (error: unknown) {
+			this.ensureCleanState()
 
 			if (error instanceof vscode.CancellationError) {
-
-				throw new Error("Cline <Language Model API>: Request cancelled by user");
+				throw new Error("Cline <Language Model API>: Request cancelled by user")
 			}
 
 			if (error instanceof Error) {
-				console.error('Cline <Language Model API>: Stream error details:', {
+				console.error("Cline <Language Model API>: Stream error details:", {
 					message: error.message,
 					stack: error.stack,
-					name: error.name
-				});
+					name: error.name,
+				})
 
 				// Return original error if it's already an Error instance
-				throw error;
-			} else if (typeof error === 'object' && error !== null) {
+				throw error
+			} else if (typeof error === "object" && error !== null) {
 				// Handle error-like objects
-				const errorDetails = JSON.stringify(error, null, 2);
-				console.error('Cline <Language Model API>: Stream error object:', errorDetails);
-				throw new Error(`Cline <Language Model API>: Response stream error: ${errorDetails}`);
+				const errorDetails = JSON.stringify(error, null, 2)
+				console.error("Cline <Language Model API>: Stream error object:", errorDetails)
+				throw new Error(`Cline <Language Model API>: Response stream error: ${errorDetails}`)
 			} else {
 				// Fallback for unknown error types
-				const errorMessage = String(error);
-				console.error('Cline <Language Model API>: Unknown stream error:', errorMessage);
-				throw new Error(`Cline <Language Model API>: Response stream error: ${errorMessage}`);
+				const errorMessage = String(error)
+				console.error("Cline <Language Model API>: Unknown stream error:", errorMessage)
+				throw new Error(`Cline <Language Model API>: Response stream error: ${errorMessage}`)
 			}
 		}
 	}
 
 	// Return model information based on the current client state
-	getModel(): { id: string; info: ModelInfo; } {
+	getModel(): { id: string; info: ModelInfo } {
 		if (this.client) {
 			// Validate client properties
 			const requiredProps = {
@@ -492,68 +474,69 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
 				vendor: this.client.vendor,
 				family: this.client.family,
 				version: this.client.version,
-				maxInputTokens: this.client.maxInputTokens
-			};
+				maxInputTokens: this.client.maxInputTokens,
+			}
 
 			// Log any missing properties for debugging
 			for (const [prop, value] of Object.entries(requiredProps)) {
 				if (!value && value !== 0) {
-					console.warn(`Cline <Language Model API>: Client missing ${prop} property`);
+					console.warn(`Cline <Language Model API>: Client missing ${prop} property`)
 				}
 			}
 
 			// Construct model ID using available information
-			const modelParts = [
-				this.client.vendor,
-				this.client.family,
-				this.client.version
-			].filter(Boolean);
+			const modelParts = [this.client.vendor, this.client.family, this.client.version].filter(Boolean)
 
-			const modelId = this.client.id || modelParts.join(SELECTOR_SEPARATOR);
+			const modelId = this.client.id || modelParts.join(SELECTOR_SEPARATOR)
 
 			// Build model info with conservative defaults for missing values
 			const modelInfo: ModelInfo = {
 				maxTokens: -1, // Unlimited tokens by default
-				contextWindow: typeof this.client.maxInputTokens === 'number'
-					? Math.max(0, this.client.maxInputTokens)
-					: openAiModelInfoSaneDefaults.contextWindow,
+				contextWindow:
+					typeof this.client.maxInputTokens === "number"
+						? Math.max(0, this.client.maxInputTokens)
+						: openAiModelInfoSaneDefaults.contextWindow,
 				supportsImages: false, // VSCode Language Model API currently doesn't support image inputs
 				supportsPromptCache: true,
 				inputPrice: 0,
 				outputPrice: 0,
-				description: `VSCode Language Model: ${modelId}`
-			};
+				description: `VSCode Language Model: ${modelId}`,
+			}
 
-			return { id: modelId, info: modelInfo };
+			return { id: modelId, info: modelInfo }
 		}
 
 		// Fallback when no client is available
 		const fallbackId = this.options.vsCodeLmModelSelector
 			? stringifyVsCodeLmModelSelector(this.options.vsCodeLmModelSelector)
-			: "vscode-lm";
+			: "vscode-lm"
 
-		console.debug('Cline <Language Model API>: No client available, using fallback model info');
+		console.debug("Cline <Language Model API>: No client available, using fallback model info")
 
 		return {
 			id: fallbackId,
 			info: {
 				...openAiModelInfoSaneDefaults,
-				description: `VSCode Language Model (Fallback): ${fallbackId}`
-			}
-		};
+				description: `VSCode Language Model (Fallback): ${fallbackId}`,
+			},
+		}
 	}
 
 	async completePrompt(prompt: string): Promise<string> {
 		try {
-			const client = await this.getClient();
-			const response = await client.sendRequest([vscode.LanguageModelChatMessage.User(prompt)], {}, new vscode.CancellationTokenSource().token);
-			let result = "";
+			const client = await this.getClient()
+			const response = await client.sendRequest(
+				[vscode.LanguageModelChatMessage.User(prompt)],
+				{},
+				new vscode.CancellationTokenSource().token,
+			)
+			let result = ""
 			for await (const chunk of response.stream) {
 				if (chunk instanceof vscode.LanguageModelTextPart) {
-					result += chunk.value;
+					result += chunk.value
 				}
 			}
-			return result;
+			return result
 		} catch (error) {
 			if (error instanceof Error) {
 				throw new Error(`VSCode LM completion error: ${error.message}`)

+ 249 - 251
src/api/transform/__tests__/bedrock-converse-format.test.ts

@@ -1,252 +1,250 @@
-import { convertToBedrockConverseMessages, convertToAnthropicMessage } from '../bedrock-converse-format'
-import { Anthropic } from '@anthropic-ai/sdk'
-import { ContentBlock, ToolResultContentBlock } from '@aws-sdk/client-bedrock-runtime'
-import { StreamEvent } from '../../providers/bedrock'
-
-describe('bedrock-converse-format', () => {
-    describe('convertToBedrockConverseMessages', () => {
-        test('converts simple text messages correctly', () => {
-            const messages: Anthropic.Messages.MessageParam[] = [
-                { role: 'user', content: 'Hello' },
-                { role: 'assistant', content: 'Hi there' }
-            ]
-
-            const result = convertToBedrockConverseMessages(messages)
-
-            expect(result).toEqual([
-                {
-                    role: 'user',
-                    content: [{ text: 'Hello' }]
-                },
-                {
-                    role: 'assistant',
-                    content: [{ text: 'Hi there' }]
-                }
-            ])
-        })
-
-        test('converts messages with images correctly', () => {
-            const messages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'user',
-                    content: [
-                        {
-                            type: 'text',
-                            text: 'Look at this image:'
-                        },
-                        {
-                            type: 'image',
-                            source: {
-                                type: 'base64',
-                                data: 'SGVsbG8=', // "Hello" in base64
-                                media_type: 'image/jpeg' as const
-                            }
-                        }
-                    ]
-                }
-            ]
-
-            const result = convertToBedrockConverseMessages(messages)
-
-            if (!result[0] || !result[0].content) {
-                fail('Expected result to have content')
-                return
-            }
-
-            expect(result[0].role).toBe('user')
-            expect(result[0].content).toHaveLength(2)
-            expect(result[0].content[0]).toEqual({ text: 'Look at this image:' })
-            
-            const imageBlock = result[0].content[1] as ContentBlock
-            if ('image' in imageBlock && imageBlock.image && imageBlock.image.source) {
-                expect(imageBlock.image.format).toBe('jpeg')
-                expect(imageBlock.image.source).toBeDefined()
-                expect(imageBlock.image.source.bytes).toBeDefined()
-            } else {
-                fail('Expected image block not found')
-            }
-        })
-
-        test('converts tool use messages correctly', () => {
-            const messages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'assistant',
-                    content: [
-                        {
-                            type: 'tool_use',
-                            id: 'test-id',
-                            name: 'read_file',
-                            input: {
-                                path: 'test.txt'
-                            }
-                        }
-                    ]
-                }
-            ]
-
-            const result = convertToBedrockConverseMessages(messages)
-
-            if (!result[0] || !result[0].content) {
-                fail('Expected result to have content')
-                return
-            }
-
-            expect(result[0].role).toBe('assistant')
-            const toolBlock = result[0].content[0] as ContentBlock
-            if ('toolUse' in toolBlock && toolBlock.toolUse) {
-                expect(toolBlock.toolUse).toEqual({
-                    toolUseId: 'test-id',
-                    name: 'read_file',
-                    input: '<read_file>\n<path>\ntest.txt\n</path>\n</read_file>'
-                })
-            } else {
-                fail('Expected tool use block not found')
-            }
-        })
-
-        test('converts tool result messages correctly', () => {
-            const messages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'assistant',
-                    content: [
-                        {
-                            type: 'tool_result',
-                            tool_use_id: 'test-id',
-                            content: [{ type: 'text', text: 'File contents here' }]
-                        }
-                    ]
-                }
-            ]
-
-            const result = convertToBedrockConverseMessages(messages)
-
-            if (!result[0] || !result[0].content) {
-                fail('Expected result to have content')
-                return
-            }
-
-            expect(result[0].role).toBe('assistant')
-            const resultBlock = result[0].content[0] as ContentBlock
-            if ('toolResult' in resultBlock && resultBlock.toolResult) {
-                const expectedContent: ToolResultContentBlock[] = [
-                    { text: 'File contents here' }
-                ]
-                expect(resultBlock.toolResult).toEqual({
-                    toolUseId: 'test-id',
-                    content: expectedContent,
-                    status: 'success'
-                })
-            } else {
-                fail('Expected tool result block not found')
-            }
-        })
-
-        test('handles text content correctly', () => {
-            const messages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'user',
-                    content: [
-                        {
-                            type: 'text',
-                            text: 'Hello world'
-                        }
-                    ]
-                }
-            ]
-
-            const result = convertToBedrockConverseMessages(messages)
-
-            if (!result[0] || !result[0].content) {
-                fail('Expected result to have content')
-                return
-            }
-
-            expect(result[0].role).toBe('user')
-            expect(result[0].content).toHaveLength(1)
-            const textBlock = result[0].content[0] as ContentBlock
-            expect(textBlock).toEqual({ text: 'Hello world' })
-        })
-    })
-
-    describe('convertToAnthropicMessage', () => {
-        test('converts metadata events correctly', () => {
-            const event: StreamEvent = {
-                metadata: {
-                    usage: {
-                        inputTokens: 10,
-                        outputTokens: 20
-                    }
-                }
-            }
-
-            const result = convertToAnthropicMessage(event, 'test-model')
-
-            expect(result).toEqual({
-                id: '',
-                type: 'message',
-                role: 'assistant',
-                model: 'test-model',
-                usage: {
-                    input_tokens: 10,
-                    output_tokens: 20
-                }
-            })
-        })
-
-        test('converts content block start events correctly', () => {
-            const event: StreamEvent = {
-                contentBlockStart: {
-                    start: {
-                        text: 'Hello'
-                    }
-                }
-            }
-
-            const result = convertToAnthropicMessage(event, 'test-model')
-
-            expect(result).toEqual({
-                type: 'message',
-                role: 'assistant',
-                content: [{ type: 'text', text: 'Hello' }],
-                model: 'test-model'
-            })
-        })
-
-        test('converts content block delta events correctly', () => {
-            const event: StreamEvent = {
-                contentBlockDelta: {
-                    delta: {
-                        text: ' world'
-                    }
-                }
-            }
-
-            const result = convertToAnthropicMessage(event, 'test-model')
-
-            expect(result).toEqual({
-                type: 'message',
-                role: 'assistant',
-                content: [{ type: 'text', text: ' world' }],
-                model: 'test-model'
-            })
-        })
-
-        test('converts message stop events correctly', () => {
-            const event: StreamEvent = {
-                messageStop: {
-                    stopReason: 'end_turn' as const
-                }
-            }
-
-            const result = convertToAnthropicMessage(event, 'test-model')
-
-            expect(result).toEqual({
-                type: 'message',
-                role: 'assistant',
-                stop_reason: 'end_turn',
-                stop_sequence: null,
-                model: 'test-model'
-            })
-        })
-    })
+import { convertToBedrockConverseMessages, convertToAnthropicMessage } from "../bedrock-converse-format"
+import { Anthropic } from "@anthropic-ai/sdk"
+import { ContentBlock, ToolResultContentBlock } from "@aws-sdk/client-bedrock-runtime"
+import { StreamEvent } from "../../providers/bedrock"
+
+describe("bedrock-converse-format", () => {
+	describe("convertToBedrockConverseMessages", () => {
+		test("converts simple text messages correctly", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{ role: "user", content: "Hello" },
+				{ role: "assistant", content: "Hi there" },
+			]
+
+			const result = convertToBedrockConverseMessages(messages)
+
+			expect(result).toEqual([
+				{
+					role: "user",
+					content: [{ text: "Hello" }],
+				},
+				{
+					role: "assistant",
+					content: [{ text: "Hi there" }],
+				},
+			])
+		})
+
+		test("converts messages with images correctly", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: [
+						{
+							type: "text",
+							text: "Look at this image:",
+						},
+						{
+							type: "image",
+							source: {
+								type: "base64",
+								data: "SGVsbG8=", // "Hello" in base64
+								media_type: "image/jpeg" as const,
+							},
+						},
+					],
+				},
+			]
+
+			const result = convertToBedrockConverseMessages(messages)
+
+			if (!result[0] || !result[0].content) {
+				fail("Expected result to have content")
+				return
+			}
+
+			expect(result[0].role).toBe("user")
+			expect(result[0].content).toHaveLength(2)
+			expect(result[0].content[0]).toEqual({ text: "Look at this image:" })
+
+			const imageBlock = result[0].content[1] as ContentBlock
+			if ("image" in imageBlock && imageBlock.image && imageBlock.image.source) {
+				expect(imageBlock.image.format).toBe("jpeg")
+				expect(imageBlock.image.source).toBeDefined()
+				expect(imageBlock.image.source.bytes).toBeDefined()
+			} else {
+				fail("Expected image block not found")
+			}
+		})
+
+		test("converts tool use messages correctly", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "assistant",
+					content: [
+						{
+							type: "tool_use",
+							id: "test-id",
+							name: "read_file",
+							input: {
+								path: "test.txt",
+							},
+						},
+					],
+				},
+			]
+
+			const result = convertToBedrockConverseMessages(messages)
+
+			if (!result[0] || !result[0].content) {
+				fail("Expected result to have content")
+				return
+			}
+
+			expect(result[0].role).toBe("assistant")
+			const toolBlock = result[0].content[0] as ContentBlock
+			if ("toolUse" in toolBlock && toolBlock.toolUse) {
+				expect(toolBlock.toolUse).toEqual({
+					toolUseId: "test-id",
+					name: "read_file",
+					input: "<read_file>\n<path>\ntest.txt\n</path>\n</read_file>",
+				})
+			} else {
+				fail("Expected tool use block not found")
+			}
+		})
+
+		test("converts tool result messages correctly", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "assistant",
+					content: [
+						{
+							type: "tool_result",
+							tool_use_id: "test-id",
+							content: [{ type: "text", text: "File contents here" }],
+						},
+					],
+				},
+			]
+
+			const result = convertToBedrockConverseMessages(messages)
+
+			if (!result[0] || !result[0].content) {
+				fail("Expected result to have content")
+				return
+			}
+
+			expect(result[0].role).toBe("assistant")
+			const resultBlock = result[0].content[0] as ContentBlock
+			if ("toolResult" in resultBlock && resultBlock.toolResult) {
+				const expectedContent: ToolResultContentBlock[] = [{ text: "File contents here" }]
+				expect(resultBlock.toolResult).toEqual({
+					toolUseId: "test-id",
+					content: expectedContent,
+					status: "success",
+				})
+			} else {
+				fail("Expected tool result block not found")
+			}
+		})
+
+		test("handles text content correctly", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: [
+						{
+							type: "text",
+							text: "Hello world",
+						},
+					],
+				},
+			]
+
+			const result = convertToBedrockConverseMessages(messages)
+
+			if (!result[0] || !result[0].content) {
+				fail("Expected result to have content")
+				return
+			}
+
+			expect(result[0].role).toBe("user")
+			expect(result[0].content).toHaveLength(1)
+			const textBlock = result[0].content[0] as ContentBlock
+			expect(textBlock).toEqual({ text: "Hello world" })
+		})
+	})
+
+	describe("convertToAnthropicMessage", () => {
+		test("converts metadata events correctly", () => {
+			const event: StreamEvent = {
+				metadata: {
+					usage: {
+						inputTokens: 10,
+						outputTokens: 20,
+					},
+				},
+			}
+
+			const result = convertToAnthropicMessage(event, "test-model")
+
+			expect(result).toEqual({
+				id: "",
+				type: "message",
+				role: "assistant",
+				model: "test-model",
+				usage: {
+					input_tokens: 10,
+					output_tokens: 20,
+				},
+			})
+		})
+
+		test("converts content block start events correctly", () => {
+			const event: StreamEvent = {
+				contentBlockStart: {
+					start: {
+						text: "Hello",
+					},
+				},
+			}
+
+			const result = convertToAnthropicMessage(event, "test-model")
+
+			expect(result).toEqual({
+				type: "message",
+				role: "assistant",
+				content: [{ type: "text", text: "Hello" }],
+				model: "test-model",
+			})
+		})
+
+		test("converts content block delta events correctly", () => {
+			const event: StreamEvent = {
+				contentBlockDelta: {
+					delta: {
+						text: " world",
+					},
+				},
+			}
+
+			const result = convertToAnthropicMessage(event, "test-model")
+
+			expect(result).toEqual({
+				type: "message",
+				role: "assistant",
+				content: [{ type: "text", text: " world" }],
+				model: "test-model",
+			})
+		})
+
+		test("converts message stop events correctly", () => {
+			const event: StreamEvent = {
+				messageStop: {
+					stopReason: "end_turn" as const,
+				},
+			}
+
+			const result = convertToAnthropicMessage(event, "test-model")
+
+			expect(result).toEqual({
+				type: "message",
+				role: "assistant",
+				stop_reason: "end_turn",
+				stop_sequence: null,
+				model: "test-model",
+			})
+		})
+	})
 })

+ 260 - 242
src/api/transform/__tests__/openai-format.test.ts

@@ -1,257 +1,275 @@
-import { convertToOpenAiMessages, convertToAnthropicMessage } from '../openai-format';
-import { Anthropic } from '@anthropic-ai/sdk';
-import OpenAI from 'openai';
+import { convertToOpenAiMessages, convertToAnthropicMessage } from "../openai-format"
+import { Anthropic } from "@anthropic-ai/sdk"
+import OpenAI from "openai"
 
-type PartialChatCompletion = Omit<OpenAI.Chat.Completions.ChatCompletion, 'choices'> & {
-    choices: Array<Partial<OpenAI.Chat.Completions.ChatCompletion.Choice> & {
-        message: OpenAI.Chat.Completions.ChatCompletion.Choice['message'];
-        finish_reason: string;
-        index: number;
-    }>;
-};
+type PartialChatCompletion = Omit<OpenAI.Chat.Completions.ChatCompletion, "choices"> & {
+	choices: Array<
+		Partial<OpenAI.Chat.Completions.ChatCompletion.Choice> & {
+			message: OpenAI.Chat.Completions.ChatCompletion.Choice["message"]
+			finish_reason: string
+			index: number
+		}
+	>
+}
 
-describe('OpenAI Format Transformations', () => {
-    describe('convertToOpenAiMessages', () => {
-        it('should convert simple text messages', () => {
-            const anthropicMessages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'user',
-                    content: 'Hello'
-                },
-                {
-                    role: 'assistant',
-                    content: 'Hi there!'
-                }
-            ];
+describe("OpenAI Format Transformations", () => {
+	describe("convertToOpenAiMessages", () => {
+		it("should convert simple text messages", () => {
+			const anthropicMessages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: "Hello",
+				},
+				{
+					role: "assistant",
+					content: "Hi there!",
+				},
+			]
 
-            const openAiMessages = convertToOpenAiMessages(anthropicMessages);
-            expect(openAiMessages).toHaveLength(2);
-            expect(openAiMessages[0]).toEqual({
-                role: 'user',
-                content: 'Hello'
-            });
-            expect(openAiMessages[1]).toEqual({
-                role: 'assistant',
-                content: 'Hi there!'
-            });
-        });
+			const openAiMessages = convertToOpenAiMessages(anthropicMessages)
+			expect(openAiMessages).toHaveLength(2)
+			expect(openAiMessages[0]).toEqual({
+				role: "user",
+				content: "Hello",
+			})
+			expect(openAiMessages[1]).toEqual({
+				role: "assistant",
+				content: "Hi there!",
+			})
+		})
 
-        it('should handle messages with image content', () => {
-            const anthropicMessages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'user',
-                    content: [
-                        {
-                            type: 'text',
-                            text: 'What is in this image?'
-                        },
-                        {
-                            type: 'image',
-                            source: {
-                                type: 'base64',
-                                media_type: 'image/jpeg',
-                                data: 'base64data'
-                            }
-                        }
-                    ]
-                }
-            ];
+		it("should handle messages with image content", () => {
+			const anthropicMessages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: [
+						{
+							type: "text",
+							text: "What is in this image?",
+						},
+						{
+							type: "image",
+							source: {
+								type: "base64",
+								media_type: "image/jpeg",
+								data: "base64data",
+							},
+						},
+					],
+				},
+			]
 
-            const openAiMessages = convertToOpenAiMessages(anthropicMessages);
-            expect(openAiMessages).toHaveLength(1);
-            expect(openAiMessages[0].role).toBe('user');
-            
-            const content = openAiMessages[0].content as Array<{
-                type: string;
-                text?: string;
-                image_url?: { url: string };
-            }>;
-            
-            expect(Array.isArray(content)).toBe(true);
-            expect(content).toHaveLength(2);
-            expect(content[0]).toEqual({ type: 'text', text: 'What is in this image?' });
-            expect(content[1]).toEqual({
-                type: 'image_url',
-                image_url: { url: 'data:image/jpeg;base64,base64data' }
-            });
-        });
+			const openAiMessages = convertToOpenAiMessages(anthropicMessages)
+			expect(openAiMessages).toHaveLength(1)
+			expect(openAiMessages[0].role).toBe("user")
 
-        it('should handle assistant messages with tool use', () => {
-            const anthropicMessages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'assistant',
-                    content: [
-                        {
-                            type: 'text',
-                            text: 'Let me check the weather.'
-                        },
-                        {
-                            type: 'tool_use',
-                            id: 'weather-123',
-                            name: 'get_weather',
-                            input: { city: 'London' }
-                        }
-                    ]
-                }
-            ];
+			const content = openAiMessages[0].content as Array<{
+				type: string
+				text?: string
+				image_url?: { url: string }
+			}>
 
-            const openAiMessages = convertToOpenAiMessages(anthropicMessages);
-            expect(openAiMessages).toHaveLength(1);
-            
-            const assistantMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam;
-            expect(assistantMessage.role).toBe('assistant');
-            expect(assistantMessage.content).toBe('Let me check the weather.');
-            expect(assistantMessage.tool_calls).toHaveLength(1);
-            expect(assistantMessage.tool_calls![0]).toEqual({
-                id: 'weather-123',
-                type: 'function',
-                function: {
-                    name: 'get_weather',
-                    arguments: JSON.stringify({ city: 'London' })
-                }
-            });
-        });
+			expect(Array.isArray(content)).toBe(true)
+			expect(content).toHaveLength(2)
+			expect(content[0]).toEqual({ type: "text", text: "What is in this image?" })
+			expect(content[1]).toEqual({
+				type: "image_url",
+				image_url: { url: "data:image/jpeg;base64,base64data" },
+			})
+		})
 
-        it('should handle user messages with tool results', () => {
-            const anthropicMessages: Anthropic.Messages.MessageParam[] = [
-                {
-                    role: 'user',
-                    content: [
-                        {
-                            type: 'tool_result',
-                            tool_use_id: 'weather-123',
-                            content: 'Current temperature in London: 20°C'
-                        }
-                    ]
-                }
-            ];
+		it("should handle assistant messages with tool use", () => {
+			const anthropicMessages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "assistant",
+					content: [
+						{
+							type: "text",
+							text: "Let me check the weather.",
+						},
+						{
+							type: "tool_use",
+							id: "weather-123",
+							name: "get_weather",
+							input: { city: "London" },
+						},
+					],
+				},
+			]
 
-            const openAiMessages = convertToOpenAiMessages(anthropicMessages);
-            expect(openAiMessages).toHaveLength(1);
-            
-            const toolMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionToolMessageParam;
-            expect(toolMessage.role).toBe('tool');
-            expect(toolMessage.tool_call_id).toBe('weather-123');
-            expect(toolMessage.content).toBe('Current temperature in London: 20°C');
-        });
-    });
+			const openAiMessages = convertToOpenAiMessages(anthropicMessages)
+			expect(openAiMessages).toHaveLength(1)
 
-    describe('convertToAnthropicMessage', () => {
-        it('should convert simple completion', () => {
-            const openAiCompletion: PartialChatCompletion = {
-                id: 'completion-123',
-                model: 'gpt-4',
-                choices: [{
-                    message: {
-                        role: 'assistant',
-                        content: 'Hello there!',
-                        refusal: null
-                    },
-                    finish_reason: 'stop',
-                    index: 0
-                }],
-                usage: {
-                    prompt_tokens: 10,
-                    completion_tokens: 5,
-                    total_tokens: 15
-                },
-                created: 123456789,
-                object: 'chat.completion'
-            };
+			const assistantMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam
+			expect(assistantMessage.role).toBe("assistant")
+			expect(assistantMessage.content).toBe("Let me check the weather.")
+			expect(assistantMessage.tool_calls).toHaveLength(1)
+			expect(assistantMessage.tool_calls![0]).toEqual({
+				id: "weather-123",
+				type: "function",
+				function: {
+					name: "get_weather",
+					arguments: JSON.stringify({ city: "London" }),
+				},
+			})
+		})
 
-            const anthropicMessage = convertToAnthropicMessage(openAiCompletion as OpenAI.Chat.Completions.ChatCompletion);
-            expect(anthropicMessage.id).toBe('completion-123');
-            expect(anthropicMessage.role).toBe('assistant');
-            expect(anthropicMessage.content).toHaveLength(1);
-            expect(anthropicMessage.content[0]).toEqual({
-                type: 'text',
-                text: 'Hello there!'
-            });
-            expect(anthropicMessage.stop_reason).toBe('end_turn');
-            expect(anthropicMessage.usage).toEqual({
-                input_tokens: 10,
-                output_tokens: 5
-            });
-        });
+		it("should handle user messages with tool results", () => {
+			const anthropicMessages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: [
+						{
+							type: "tool_result",
+							tool_use_id: "weather-123",
+							content: "Current temperature in London: 20°C",
+						},
+					],
+				},
+			]
 
-        it('should handle tool calls in completion', () => {
-            const openAiCompletion: PartialChatCompletion = {
-                id: 'completion-123',
-                model: 'gpt-4',
-                choices: [{
-                    message: {
-                        role: 'assistant',
-                        content: 'Let me check the weather.',
-                        tool_calls: [{
-                            id: 'weather-123',
-                            type: 'function',
-                            function: {
-                                name: 'get_weather',
-                                arguments: '{"city":"London"}'
-                            }
-                        }],
-                        refusal: null
-                    },
-                    finish_reason: 'tool_calls',
-                    index: 0
-                }],
-                usage: {
-                    prompt_tokens: 15,
-                    completion_tokens: 8,
-                    total_tokens: 23
-                },
-                created: 123456789,
-                object: 'chat.completion'
-            };
+			const openAiMessages = convertToOpenAiMessages(anthropicMessages)
+			expect(openAiMessages).toHaveLength(1)
 
-            const anthropicMessage = convertToAnthropicMessage(openAiCompletion as OpenAI.Chat.Completions.ChatCompletion);
-            expect(anthropicMessage.content).toHaveLength(2);
-            expect(anthropicMessage.content[0]).toEqual({
-                type: 'text',
-                text: 'Let me check the weather.'
-            });
-            expect(anthropicMessage.content[1]).toEqual({
-                type: 'tool_use',
-                id: 'weather-123',
-                name: 'get_weather',
-                input: { city: 'London' }
-            });
-            expect(anthropicMessage.stop_reason).toBe('tool_use');
-        });
+			const toolMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionToolMessageParam
+			expect(toolMessage.role).toBe("tool")
+			expect(toolMessage.tool_call_id).toBe("weather-123")
+			expect(toolMessage.content).toBe("Current temperature in London: 20°C")
+		})
+	})
 
-        it('should handle invalid tool call arguments', () => {
-            const openAiCompletion: PartialChatCompletion = {
-                id: 'completion-123',
-                model: 'gpt-4',
-                choices: [{
-                    message: {
-                        role: 'assistant',
-                        content: 'Testing invalid arguments',
-                        tool_calls: [{
-                            id: 'test-123',
-                            type: 'function',
-                            function: {
-                                name: 'test_function',
-                                arguments: 'invalid json'
-                            }
-                        }],
-                        refusal: null
-                    },
-                    finish_reason: 'tool_calls',
-                    index: 0
-                }],
-                created: 123456789,
-                object: 'chat.completion'
-            };
+	describe("convertToAnthropicMessage", () => {
+		it("should convert simple completion", () => {
+			const openAiCompletion: PartialChatCompletion = {
+				id: "completion-123",
+				model: "gpt-4",
+				choices: [
+					{
+						message: {
+							role: "assistant",
+							content: "Hello there!",
+							refusal: null,
+						},
+						finish_reason: "stop",
+						index: 0,
+					},
+				],
+				usage: {
+					prompt_tokens: 10,
+					completion_tokens: 5,
+					total_tokens: 15,
+				},
+				created: 123456789,
+				object: "chat.completion",
+			}
 
-            const anthropicMessage = convertToAnthropicMessage(openAiCompletion as OpenAI.Chat.Completions.ChatCompletion);
-            expect(anthropicMessage.content).toHaveLength(2);
-            expect(anthropicMessage.content[1]).toEqual({
-                type: 'tool_use',
-                id: 'test-123',
-                name: 'test_function',
-                input: {}  // Should default to empty object for invalid JSON
-            });
-        });
-    });
-});
+			const anthropicMessage = convertToAnthropicMessage(
+				openAiCompletion as OpenAI.Chat.Completions.ChatCompletion,
+			)
+			expect(anthropicMessage.id).toBe("completion-123")
+			expect(anthropicMessage.role).toBe("assistant")
+			expect(anthropicMessage.content).toHaveLength(1)
+			expect(anthropicMessage.content[0]).toEqual({
+				type: "text",
+				text: "Hello there!",
+			})
+			expect(anthropicMessage.stop_reason).toBe("end_turn")
+			expect(anthropicMessage.usage).toEqual({
+				input_tokens: 10,
+				output_tokens: 5,
+			})
+		})
+
+		it("should handle tool calls in completion", () => {
+			const openAiCompletion: PartialChatCompletion = {
+				id: "completion-123",
+				model: "gpt-4",
+				choices: [
+					{
+						message: {
+							role: "assistant",
+							content: "Let me check the weather.",
+							tool_calls: [
+								{
+									id: "weather-123",
+									type: "function",
+									function: {
+										name: "get_weather",
+										arguments: '{"city":"London"}',
+									},
+								},
+							],
+							refusal: null,
+						},
+						finish_reason: "tool_calls",
+						index: 0,
+					},
+				],
+				usage: {
+					prompt_tokens: 15,
+					completion_tokens: 8,
+					total_tokens: 23,
+				},
+				created: 123456789,
+				object: "chat.completion",
+			}
+
+			const anthropicMessage = convertToAnthropicMessage(
+				openAiCompletion as OpenAI.Chat.Completions.ChatCompletion,
+			)
+			expect(anthropicMessage.content).toHaveLength(2)
+			expect(anthropicMessage.content[0]).toEqual({
+				type: "text",
+				text: "Let me check the weather.",
+			})
+			expect(anthropicMessage.content[1]).toEqual({
+				type: "tool_use",
+				id: "weather-123",
+				name: "get_weather",
+				input: { city: "London" },
+			})
+			expect(anthropicMessage.stop_reason).toBe("tool_use")
+		})
+
+		it("should handle invalid tool call arguments", () => {
+			const openAiCompletion: PartialChatCompletion = {
+				id: "completion-123",
+				model: "gpt-4",
+				choices: [
+					{
+						message: {
+							role: "assistant",
+							content: "Testing invalid arguments",
+							tool_calls: [
+								{
+									id: "test-123",
+									type: "function",
+									function: {
+										name: "test_function",
+										arguments: "invalid json",
+									},
+								},
+							],
+							refusal: null,
+						},
+						finish_reason: "tool_calls",
+						index: 0,
+					},
+				],
+				created: 123456789,
+				object: "chat.completion",
+			}
+
+			const anthropicMessage = convertToAnthropicMessage(
+				openAiCompletion as OpenAI.Chat.Completions.ChatCompletion,
+			)
+			expect(anthropicMessage.content).toHaveLength(2)
+			expect(anthropicMessage.content[1]).toEqual({
+				type: "tool_use",
+				id: "test-123",
+				name: "test_function",
+				input: {}, // Should default to empty object for invalid JSON
+			})
+		})
+	})
+})

+ 114 - 114
src/api/transform/__tests__/stream.test.ts

@@ -1,114 +1,114 @@
-import { ApiStreamChunk } from '../stream';
-
-describe('API Stream Types', () => {
-    describe('ApiStreamChunk', () => {
-        it('should correctly handle text chunks', () => {
-            const textChunk: ApiStreamChunk = {
-                type: 'text',
-                text: 'Hello world'
-            };
-
-            expect(textChunk.type).toBe('text');
-            expect(textChunk.text).toBe('Hello world');
-        });
-
-        it('should correctly handle usage chunks with cache information', () => {
-            const usageChunk: ApiStreamChunk = {
-                type: 'usage',
-                inputTokens: 100,
-                outputTokens: 50,
-                cacheWriteTokens: 20,
-                cacheReadTokens: 10
-            };
-
-            expect(usageChunk.type).toBe('usage');
-            expect(usageChunk.inputTokens).toBe(100);
-            expect(usageChunk.outputTokens).toBe(50);
-            expect(usageChunk.cacheWriteTokens).toBe(20);
-            expect(usageChunk.cacheReadTokens).toBe(10);
-        });
-
-        it('should handle usage chunks without cache tokens', () => {
-            const usageChunk: ApiStreamChunk = {
-                type: 'usage',
-                inputTokens: 100,
-                outputTokens: 50
-            };
-
-            expect(usageChunk.type).toBe('usage');
-            expect(usageChunk.inputTokens).toBe(100);
-            expect(usageChunk.outputTokens).toBe(50);
-            expect(usageChunk.cacheWriteTokens).toBeUndefined();
-            expect(usageChunk.cacheReadTokens).toBeUndefined();
-        });
-
-        it('should handle text chunks with empty strings', () => {
-            const emptyTextChunk: ApiStreamChunk = {
-                type: 'text',
-                text: ''
-            };
-
-            expect(emptyTextChunk.type).toBe('text');
-            expect(emptyTextChunk.text).toBe('');
-        });
-
-        it('should handle usage chunks with zero tokens', () => {
-            const zeroUsageChunk: ApiStreamChunk = {
-                type: 'usage',
-                inputTokens: 0,
-                outputTokens: 0
-            };
-
-            expect(zeroUsageChunk.type).toBe('usage');
-            expect(zeroUsageChunk.inputTokens).toBe(0);
-            expect(zeroUsageChunk.outputTokens).toBe(0);
-        });
-
-        it('should handle usage chunks with large token counts', () => {
-            const largeUsageChunk: ApiStreamChunk = {
-                type: 'usage',
-                inputTokens: 1000000,
-                outputTokens: 500000,
-                cacheWriteTokens: 200000,
-                cacheReadTokens: 100000
-            };
-
-            expect(largeUsageChunk.type).toBe('usage');
-            expect(largeUsageChunk.inputTokens).toBe(1000000);
-            expect(largeUsageChunk.outputTokens).toBe(500000);
-            expect(largeUsageChunk.cacheWriteTokens).toBe(200000);
-            expect(largeUsageChunk.cacheReadTokens).toBe(100000);
-        });
-
-        it('should handle text chunks with special characters', () => {
-            const specialCharsChunk: ApiStreamChunk = {
-                type: 'text',
-                text: '!@#$%^&*()_+-=[]{}|;:,.<>?`~'
-            };
-
-            expect(specialCharsChunk.type).toBe('text');
-            expect(specialCharsChunk.text).toBe('!@#$%^&*()_+-=[]{}|;:,.<>?`~');
-        });
-
-        it('should handle text chunks with unicode characters', () => {
-            const unicodeChunk: ApiStreamChunk = {
-                type: 'text',
-                text: '你好世界👋🌍'
-            };
-
-            expect(unicodeChunk.type).toBe('text');
-            expect(unicodeChunk.text).toBe('你好世界👋🌍');
-        });
-
-        it('should handle text chunks with multiline content', () => {
-            const multilineChunk: ApiStreamChunk = {
-                type: 'text',
-                text: 'Line 1\nLine 2\nLine 3'
-            };
-
-            expect(multilineChunk.type).toBe('text');
-            expect(multilineChunk.text).toBe('Line 1\nLine 2\nLine 3');
-            expect(multilineChunk.text.split('\n')).toHaveLength(3);
-        });
-    });
-});
+import { ApiStreamChunk } from "../stream"
+
+describe("API Stream Types", () => {
+	describe("ApiStreamChunk", () => {
+		it("should correctly handle text chunks", () => {
+			const textChunk: ApiStreamChunk = {
+				type: "text",
+				text: "Hello world",
+			}
+
+			expect(textChunk.type).toBe("text")
+			expect(textChunk.text).toBe("Hello world")
+		})
+
+		it("should correctly handle usage chunks with cache information", () => {
+			const usageChunk: ApiStreamChunk = {
+				type: "usage",
+				inputTokens: 100,
+				outputTokens: 50,
+				cacheWriteTokens: 20,
+				cacheReadTokens: 10,
+			}
+
+			expect(usageChunk.type).toBe("usage")
+			expect(usageChunk.inputTokens).toBe(100)
+			expect(usageChunk.outputTokens).toBe(50)
+			expect(usageChunk.cacheWriteTokens).toBe(20)
+			expect(usageChunk.cacheReadTokens).toBe(10)
+		})
+
+		it("should handle usage chunks without cache tokens", () => {
+			const usageChunk: ApiStreamChunk = {
+				type: "usage",
+				inputTokens: 100,
+				outputTokens: 50,
+			}
+
+			expect(usageChunk.type).toBe("usage")
+			expect(usageChunk.inputTokens).toBe(100)
+			expect(usageChunk.outputTokens).toBe(50)
+			expect(usageChunk.cacheWriteTokens).toBeUndefined()
+			expect(usageChunk.cacheReadTokens).toBeUndefined()
+		})
+
+		it("should handle text chunks with empty strings", () => {
+			const emptyTextChunk: ApiStreamChunk = {
+				type: "text",
+				text: "",
+			}
+
+			expect(emptyTextChunk.type).toBe("text")
+			expect(emptyTextChunk.text).toBe("")
+		})
+
+		it("should handle usage chunks with zero tokens", () => {
+			const zeroUsageChunk: ApiStreamChunk = {
+				type: "usage",
+				inputTokens: 0,
+				outputTokens: 0,
+			}
+
+			expect(zeroUsageChunk.type).toBe("usage")
+			expect(zeroUsageChunk.inputTokens).toBe(0)
+			expect(zeroUsageChunk.outputTokens).toBe(0)
+		})
+
+		it("should handle usage chunks with large token counts", () => {
+			const largeUsageChunk: ApiStreamChunk = {
+				type: "usage",
+				inputTokens: 1000000,
+				outputTokens: 500000,
+				cacheWriteTokens: 200000,
+				cacheReadTokens: 100000,
+			}
+
+			expect(largeUsageChunk.type).toBe("usage")
+			expect(largeUsageChunk.inputTokens).toBe(1000000)
+			expect(largeUsageChunk.outputTokens).toBe(500000)
+			expect(largeUsageChunk.cacheWriteTokens).toBe(200000)
+			expect(largeUsageChunk.cacheReadTokens).toBe(100000)
+		})
+
+		it("should handle text chunks with special characters", () => {
+			const specialCharsChunk: ApiStreamChunk = {
+				type: "text",
+				text: "!@#$%^&*()_+-=[]{}|;:,.<>?`~",
+			}
+
+			expect(specialCharsChunk.type).toBe("text")
+			expect(specialCharsChunk.text).toBe("!@#$%^&*()_+-=[]{}|;:,.<>?`~")
+		})
+
+		it("should handle text chunks with unicode characters", () => {
+			const unicodeChunk: ApiStreamChunk = {
+				type: "text",
+				text: "你好世界👋🌍",
+			}
+
+			expect(unicodeChunk.type).toBe("text")
+			expect(unicodeChunk.text).toBe("你好世界👋🌍")
+		})
+
+		it("should handle text chunks with multiline content", () => {
+			const multilineChunk: ApiStreamChunk = {
+				type: "text",
+				text: "Line 1\nLine 2\nLine 3",
+			}
+
+			expect(multilineChunk.type).toBe("text")
+			expect(multilineChunk.text).toBe("Line 1\nLine 2\nLine 3")
+			expect(multilineChunk.text.split("\n")).toHaveLength(3)
+		})
+	})
+})

+ 199 - 189
src/api/transform/__tests__/vscode-lm-format.test.ts

@@ -1,66 +1,66 @@
-import { Anthropic } from "@anthropic-ai/sdk";
-import * as vscode from 'vscode';
-import { convertToVsCodeLmMessages, convertToAnthropicRole, convertToAnthropicMessage } from '../vscode-lm-format';
+import { Anthropic } from "@anthropic-ai/sdk"
+import * as vscode from "vscode"
+import { convertToVsCodeLmMessages, convertToAnthropicRole, convertToAnthropicMessage } from "../vscode-lm-format"
 
 // Mock crypto
 const mockCrypto = {
-	randomUUID: () => 'test-uuid'
-};
-global.crypto = mockCrypto as any;
+	randomUUID: () => "test-uuid",
+}
+global.crypto = mockCrypto as any
 
 // Define types for our mocked classes
 interface MockLanguageModelTextPart {
-	type: 'text';
-	value: string;
+	type: "text"
+	value: string
 }
 
 interface MockLanguageModelToolCallPart {
-	type: 'tool_call';
-	callId: string;
-	name: string;
-	input: any;
+	type: "tool_call"
+	callId: string
+	name: string
+	input: any
 }
 
 interface MockLanguageModelToolResultPart {
-	type: 'tool_result';
-	toolUseId: string;
-	parts: MockLanguageModelTextPart[];
+	type: "tool_result"
+	toolUseId: string
+	parts: MockLanguageModelTextPart[]
 }
 
-type MockMessageContent = MockLanguageModelTextPart | MockLanguageModelToolCallPart | MockLanguageModelToolResultPart;
+type MockMessageContent = MockLanguageModelTextPart | MockLanguageModelToolCallPart | MockLanguageModelToolResultPart
 
 interface MockLanguageModelChatMessage {
-	role: string;
-	name?: string;
-	content: MockMessageContent[];
+	role: string
+	name?: string
+	content: MockMessageContent[]
 }
 
 // Mock vscode namespace
-jest.mock('vscode', () => {
+jest.mock("vscode", () => {
 	const LanguageModelChatMessageRole = {
-		Assistant: 'assistant',
-		User: 'user'
-	};
+		Assistant: "assistant",
+		User: "user",
+	}
 
 	class MockLanguageModelTextPart {
-		type = 'text';
+		type = "text"
 		constructor(public value: string) {}
 	}
 
 	class MockLanguageModelToolCallPart {
-		type = 'tool_call';
+		type = "tool_call"
 		constructor(
 			public callId: string,
 			public name: string,
-			public input: any
+			public input: any,
 		) {}
 	}
 
 	class MockLanguageModelToolResultPart {
-		type = 'tool_result';
+		type = "tool_result"
 		constructor(
 			public toolUseId: string,
-			public parts: MockLanguageModelTextPart[]
+			public parts: MockLanguageModelTextPart[],
 		) {}
 	}
 
@@ -68,179 +68,189 @@ jest.mock('vscode', () => {
 		LanguageModelChatMessage: {
 			Assistant: jest.fn((content) => ({
 				role: LanguageModelChatMessageRole.Assistant,
-				name: 'assistant',
-				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)]
+				name: "assistant",
+				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)],
 			})),
 			User: jest.fn((content) => ({
 				role: LanguageModelChatMessageRole.User,
-				name: 'user',
-				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)]
-			}))
+				name: "user",
+				content: Array.isArray(content) ? content : [new MockLanguageModelTextPart(content)],
+			})),
 		},
 		LanguageModelChatMessageRole,
 		LanguageModelTextPart: MockLanguageModelTextPart,
 		LanguageModelToolCallPart: MockLanguageModelToolCallPart,
-		LanguageModelToolResultPart: MockLanguageModelToolResultPart
-	};
-});
+		LanguageModelToolResultPart: MockLanguageModelToolResultPart,
+	}
+})
 
-describe('vscode-lm-format', () => {
-	describe('convertToVsCodeLmMessages', () => {
-		it('should convert simple string messages', () => {
+describe("vscode-lm-format", () => {
+	describe("convertToVsCodeLmMessages", () => {
+		it("should convert simple string messages", () => {
 			const messages: Anthropic.Messages.MessageParam[] = [
-				{ role: 'user', content: 'Hello' },
-				{ role: 'assistant', content: 'Hi there' }
-			];
-
-			const result = convertToVsCodeLmMessages(messages);
-			
-			expect(result).toHaveLength(2);
-			expect(result[0].role).toBe('user');
-			expect((result[0].content[0] as MockLanguageModelTextPart).value).toBe('Hello');
-			expect(result[1].role).toBe('assistant');
-			expect((result[1].content[0] as MockLanguageModelTextPart).value).toBe('Hi there');
-		});
-
-		it('should handle complex user messages with tool results', () => {
-			const messages: Anthropic.Messages.MessageParam[] = [{
-				role: 'user',
-				content: [
-					{ type: 'text', text: 'Here is the result:' },
-					{
-						type: 'tool_result',
-						tool_use_id: 'tool-1',
-						content: 'Tool output'
-					}
-				]
-			}];
-
-			const result = convertToVsCodeLmMessages(messages);
-			
-			expect(result).toHaveLength(1);
-			expect(result[0].role).toBe('user');
-			expect(result[0].content).toHaveLength(2);
-			const [toolResult, textContent] = result[0].content as [MockLanguageModelToolResultPart, MockLanguageModelTextPart];
-			expect(toolResult.type).toBe('tool_result');
-			expect(textContent.type).toBe('text');
-		});
-
-		it('should handle complex assistant messages with tool calls', () => {
-			const messages: Anthropic.Messages.MessageParam[] = [{
-				role: 'assistant',
-				content: [
-					{ type: 'text', text: 'Let me help you with that.' },
-					{
-						type: 'tool_use',
-						id: 'tool-1',
-						name: 'calculator',
-						input: { operation: 'add', numbers: [2, 2] }
-					}
-				]
-			}];
-
-			const result = convertToVsCodeLmMessages(messages);
-			
-			expect(result).toHaveLength(1);
-			expect(result[0].role).toBe('assistant');
-			expect(result[0].content).toHaveLength(2);
-			const [toolCall, textContent] = result[0].content as [MockLanguageModelToolCallPart, MockLanguageModelTextPart];
-			expect(toolCall.type).toBe('tool_call');
-			expect(textContent.type).toBe('text');
-		});
-
-		it('should handle image blocks with appropriate placeholders', () => {
-			const messages: Anthropic.Messages.MessageParam[] = [{
-				role: 'user',
-				content: [
-					{ type: 'text', text: 'Look at this:' },
-					{
-						type: 'image',
-						source: {
-							type: 'base64',
-							media_type: 'image/png',
-							data: 'base64data'
-						}
-					}
-				]
-			}];
-
-			const result = convertToVsCodeLmMessages(messages);
-			
-			expect(result).toHaveLength(1);
-			const imagePlaceholder = result[0].content[1] as MockLanguageModelTextPart;
-			expect(imagePlaceholder.value).toContain('[Image (base64): image/png not supported by VSCode LM API]');
-		});
-	});
-
-	describe('convertToAnthropicRole', () => {
-		it('should convert assistant role correctly', () => {
-			const result = convertToAnthropicRole('assistant' as any);
-			expect(result).toBe('assistant');
-		});
-
-		it('should convert user role correctly', () => {
-			const result = convertToAnthropicRole('user' as any);
-			expect(result).toBe('user');
-		});
-
-		it('should return null for unknown roles', () => {
-			const result = convertToAnthropicRole('unknown' as any);
-			expect(result).toBeNull();
-		});
-	});
-
-	describe('convertToAnthropicMessage', () => {
-		it('should convert assistant message with text content', async () => {
+				{ role: "user", content: "Hello" },
+				{ role: "assistant", content: "Hi there" },
+			]
+
+			const result = convertToVsCodeLmMessages(messages)
+
+			expect(result).toHaveLength(2)
+			expect(result[0].role).toBe("user")
+			expect((result[0].content[0] as MockLanguageModelTextPart).value).toBe("Hello")
+			expect(result[1].role).toBe("assistant")
+			expect((result[1].content[0] as MockLanguageModelTextPart).value).toBe("Hi there")
+		})
+
+		it("should handle complex user messages with tool results", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: [
+						{ type: "text", text: "Here is the result:" },
+						{
+							type: "tool_result",
+							tool_use_id: "tool-1",
+							content: "Tool output",
+						},
+					],
+				},
+			]
+
+			const result = convertToVsCodeLmMessages(messages)
+
+			expect(result).toHaveLength(1)
+			expect(result[0].role).toBe("user")
+			expect(result[0].content).toHaveLength(2)
+			const [toolResult, textContent] = result[0].content as [
+				MockLanguageModelToolResultPart,
+				MockLanguageModelTextPart,
+			]
+			expect(toolResult.type).toBe("tool_result")
+			expect(textContent.type).toBe("text")
+		})
+
+		it("should handle complex assistant messages with tool calls", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "assistant",
+					content: [
+						{ type: "text", text: "Let me help you with that." },
+						{
+							type: "tool_use",
+							id: "tool-1",
+							name: "calculator",
+							input: { operation: "add", numbers: [2, 2] },
+						},
+					],
+				},
+			]
+
+			const result = convertToVsCodeLmMessages(messages)
+
+			expect(result).toHaveLength(1)
+			expect(result[0].role).toBe("assistant")
+			expect(result[0].content).toHaveLength(2)
+			const [toolCall, textContent] = result[0].content as [
+				MockLanguageModelToolCallPart,
+				MockLanguageModelTextPart,
+			]
+			expect(toolCall.type).toBe("tool_call")
+			expect(textContent.type).toBe("text")
+		})
+
+		it("should handle image blocks with appropriate placeholders", () => {
+			const messages: Anthropic.Messages.MessageParam[] = [
+				{
+					role: "user",
+					content: [
+						{ type: "text", text: "Look at this:" },
+						{
+							type: "image",
+							source: {
+								type: "base64",
+								media_type: "image/png",
+								data: "base64data",
+							},
+						},
+					],
+				},
+			]
+
+			const result = convertToVsCodeLmMessages(messages)
+
+			expect(result).toHaveLength(1)
+			const imagePlaceholder = result[0].content[1] as MockLanguageModelTextPart
+			expect(imagePlaceholder.value).toContain("[Image (base64): image/png not supported by VSCode LM API]")
+		})
+	})
+
+	describe("convertToAnthropicRole", () => {
+		it("should convert assistant role correctly", () => {
+			const result = convertToAnthropicRole("assistant" as any)
+			expect(result).toBe("assistant")
+		})
+
+		it("should convert user role correctly", () => {
+			const result = convertToAnthropicRole("user" as any)
+			expect(result).toBe("user")
+		})
+
+		it("should return null for unknown roles", () => {
+			const result = convertToAnthropicRole("unknown" as any)
+			expect(result).toBeNull()
+		})
+	})
+
+	describe("convertToAnthropicMessage", () => {
+		it("should convert assistant message with text content", async () => {
 			const vsCodeMessage = {
-				role: 'assistant',
-				name: 'assistant',
-				content: [new vscode.LanguageModelTextPart('Hello')]
-			};
-
-			const result = await convertToAnthropicMessage(vsCodeMessage as any);
-			
-			expect(result.role).toBe('assistant');
-			expect(result.content).toHaveLength(1);
+				role: "assistant",
+				name: "assistant",
+				content: [new vscode.LanguageModelTextPart("Hello")],
+			}
+
+			const result = await convertToAnthropicMessage(vsCodeMessage as any)
+
+			expect(result.role).toBe("assistant")
+			expect(result.content).toHaveLength(1)
 			expect(result.content[0]).toEqual({
-				type: 'text',
-				text: 'Hello'
-			});
-			expect(result.id).toBe('test-uuid');
-		});
+				type: "text",
+				text: "Hello",
+			})
+			expect(result.id).toBe("test-uuid")
+		})
 
-		it('should convert assistant message with tool calls', async () => {
+		it("should convert assistant message with tool calls", async () => {
 			const vsCodeMessage = {
-				role: 'assistant',
-				name: 'assistant',
-				content: [new vscode.LanguageModelToolCallPart(
-					'call-1',
-					'calculator',
-					{ operation: 'add', numbers: [2, 2] }
-				)]
-			};
-
-			const result = await convertToAnthropicMessage(vsCodeMessage as any);
-			
-			expect(result.content).toHaveLength(1);
+				role: "assistant",
+				name: "assistant",
+				content: [
+					new vscode.LanguageModelToolCallPart("call-1", "calculator", { operation: "add", numbers: [2, 2] }),
+				],
+			}
+
+			const result = await convertToAnthropicMessage(vsCodeMessage as any)
+
+			expect(result.content).toHaveLength(1)
 			expect(result.content[0]).toEqual({
-				type: 'tool_use',
-				id: 'call-1',
-				name: 'calculator',
-				input: { operation: 'add', numbers: [2, 2] }
-			});
-			expect(result.id).toBe('test-uuid');
-		});
-
-		it('should throw error for non-assistant messages', async () => {
+				type: "tool_use",
+				id: "call-1",
+				name: "calculator",
+				input: { operation: "add", numbers: [2, 2] },
+			})
+			expect(result.id).toBe("test-uuid")
+		})
+
+		it("should throw error for non-assistant messages", async () => {
 			const vsCodeMessage = {
-				role: 'user',
-				name: 'user',
-				content: [new vscode.LanguageModelTextPart('Hello')]
-			};
-
-			await expect(convertToAnthropicMessage(vsCodeMessage as any))
-				.rejects
-				.toThrow('Cline <Language Model API>: Only assistant messages are supported.');
-		});
-	});
-});
+				role: "user",
+				name: "user",
+				content: [new vscode.LanguageModelTextPart("Hello")],
+			}
+
+			await expect(convertToAnthropicMessage(vsCodeMessage as any)).rejects.toThrow(
+				"Cline <Language Model API>: Only assistant messages are supported.",
+			)
+		})
+	})
+})

+ 205 - 199
src/api/transform/bedrock-converse-format.ts

@@ -8,210 +8,216 @@ import { StreamEvent } from "../providers/bedrock"
 /**
  * Convert Anthropic messages to Bedrock Converse format
  */
-export function convertToBedrockConverseMessages(
-    anthropicMessages: Anthropic.Messages.MessageParam[]
-): Message[] {
-    return anthropicMessages.map(anthropicMessage => {
-        // Map Anthropic roles to Bedrock roles
-        const role: ConversationRole = anthropicMessage.role === "assistant" ? "assistant" : "user"
-
-        if (typeof anthropicMessage.content === "string") {
-            return {
-                role,
-                content: [{
-                    text: anthropicMessage.content
-                }] as ContentBlock[]
-            }
-        }
-
-        // Process complex content types
-        const content = anthropicMessage.content.map(block => {
-            const messageBlock = block as MessageContent & { 
-                id?: string, 
-                tool_use_id?: string,
-                content?: Array<{ type: string, text: string }>,
-                output?: string | Array<{ type: string, text: string }>
-            }
-
-            if (messageBlock.type === "text") {
-                return {
-                    text: messageBlock.text || ''
-                } as ContentBlock
-            }
-            
-            if (messageBlock.type === "image" && messageBlock.source) {
-                // Convert base64 string to byte array if needed
-                let byteArray: Uint8Array
-                if (typeof messageBlock.source.data === 'string') {
-                    const binaryString = atob(messageBlock.source.data)
-                    byteArray = new Uint8Array(binaryString.length)
-                    for (let i = 0; i < binaryString.length; i++) {
-                        byteArray[i] = binaryString.charCodeAt(i)
-                    }
-                } else {
-                    byteArray = messageBlock.source.data
-                }
-
-                // Extract format from media_type (e.g., "image/jpeg" -> "jpeg")
-                const format = messageBlock.source.media_type.split('/')[1]
-                if (!['png', 'jpeg', 'gif', 'webp'].includes(format)) {
-                    throw new Error(`Unsupported image format: ${format}`)
-                }
-
-                return {
-                    image: {
-                        format: format as "png" | "jpeg" | "gif" | "webp",
-                        source: {
-                            bytes: byteArray
-                        }
-                    }
-                } as ContentBlock
-            }
-
-            if (messageBlock.type === "tool_use") {
-                // Convert tool use to XML format
-                const toolParams = Object.entries(messageBlock.input || {})
-                    .map(([key, value]) => `<${key}>\n${value}\n</${key}>`)
-                    .join('\n')
-
-                return {
-                    toolUse: {
-                        toolUseId: messageBlock.id || '',
-                        name: messageBlock.name || '',
-                        input: `<${messageBlock.name}>\n${toolParams}\n</${messageBlock.name}>`
-                    }
-                } as ContentBlock
-            }
-
-            if (messageBlock.type === "tool_result") {
-                // First try to use content if available
-                if (messageBlock.content && Array.isArray(messageBlock.content)) {
-                    return {
-                        toolResult: {
-                            toolUseId: messageBlock.tool_use_id || '',
-                            content: messageBlock.content.map(item => ({
-                                text: item.text
-                            })),
-                            status: "success"
-                        }
-                    } as ContentBlock
-                }
-
-                // Fall back to output handling if content is not available
-                if (messageBlock.output && typeof messageBlock.output === "string") {
-                    return {
-                        toolResult: {
-                            toolUseId: messageBlock.tool_use_id || '',
-                            content: [{
-                                text: messageBlock.output
-                            }],
-                            status: "success"
-                        }
-                    } as ContentBlock
-                }
-                // Handle array of content blocks if output is an array
-                if (Array.isArray(messageBlock.output)) {
-                    return {
-                        toolResult: {
-                            toolUseId: messageBlock.tool_use_id || '',
-                            content: messageBlock.output.map(part => {
-                                if (typeof part === "object" && "text" in part) {
-                                    return { text: part.text }
-                                }
-                                // Skip images in tool results as they're handled separately
-                                if (typeof part === "object" && "type" in part && part.type === "image") {
-                                    return { text: "(see following message for image)" }
-                                }
-                                return { text: String(part) }
-                            }),
-                            status: "success"
-                        }
-                    } as ContentBlock
-                }
-
-                // Default case
-                return {
-                    toolResult: {
-                        toolUseId: messageBlock.tool_use_id || '',
-                        content: [{
-                            text: String(messageBlock.output || '')
-                        }],
-                        status: "success"
-                    }
-                } as ContentBlock
-            }
-
-            if (messageBlock.type === "video") {
-                const videoContent = messageBlock.s3Location ? {
-                    s3Location: {
-                        uri: messageBlock.s3Location.uri,
-                        bucketOwner: messageBlock.s3Location.bucketOwner
-                    }
-                } : messageBlock.source
-
-                return {
-                    video: {
-                        format: "mp4", // Default to mp4, adjust based on actual format if needed
-                        source: videoContent
-                    }
-                } as ContentBlock
-            }
-
-            // Default case for unknown block types
-            return {
-                text: '[Unknown Block Type]'
-            } as ContentBlock
-        })
-
-        return {
-            role,
-            content
-        }
-    })
+export function convertToBedrockConverseMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): Message[] {
+	return anthropicMessages.map((anthropicMessage) => {
+		// Map Anthropic roles to Bedrock roles
+		const role: ConversationRole = anthropicMessage.role === "assistant" ? "assistant" : "user"
+
+		if (typeof anthropicMessage.content === "string") {
+			return {
+				role,
+				content: [
+					{
+						text: anthropicMessage.content,
+					},
+				] as ContentBlock[],
+			}
+		}
+
+		// Process complex content types
+		const content = anthropicMessage.content.map((block) => {
+			const messageBlock = block as MessageContent & {
+				id?: string
+				tool_use_id?: string
+				content?: Array<{ type: string; text: string }>
+				output?: string | Array<{ type: string; text: string }>
+			}
+
+			if (messageBlock.type === "text") {
+				return {
+					text: messageBlock.text || "",
+				} as ContentBlock
+			}
+
+			if (messageBlock.type === "image" && messageBlock.source) {
+				// Convert base64 string to byte array if needed
+				let byteArray: Uint8Array
+				if (typeof messageBlock.source.data === "string") {
+					const binaryString = atob(messageBlock.source.data)
+					byteArray = new Uint8Array(binaryString.length)
+					for (let i = 0; i < binaryString.length; i++) {
+						byteArray[i] = binaryString.charCodeAt(i)
+					}
+				} else {
+					byteArray = messageBlock.source.data
+				}
+
+				// Extract format from media_type (e.g., "image/jpeg" -> "jpeg")
+				const format = messageBlock.source.media_type.split("/")[1]
+				if (!["png", "jpeg", "gif", "webp"].includes(format)) {
+					throw new Error(`Unsupported image format: ${format}`)
+				}
+
+				return {
+					image: {
+						format: format as "png" | "jpeg" | "gif" | "webp",
+						source: {
+							bytes: byteArray,
+						},
+					},
+				} as ContentBlock
+			}
+
+			if (messageBlock.type === "tool_use") {
+				// Convert tool use to XML format
+				const toolParams = Object.entries(messageBlock.input || {})
+					.map(([key, value]) => `<${key}>\n${value}\n</${key}>`)
+					.join("\n")
+
+				return {
+					toolUse: {
+						toolUseId: messageBlock.id || "",
+						name: messageBlock.name || "",
+						input: `<${messageBlock.name}>\n${toolParams}\n</${messageBlock.name}>`,
+					},
+				} as ContentBlock
+			}
+
+			if (messageBlock.type === "tool_result") {
+				// First try to use content if available
+				if (messageBlock.content && Array.isArray(messageBlock.content)) {
+					return {
+						toolResult: {
+							toolUseId: messageBlock.tool_use_id || "",
+							content: messageBlock.content.map((item) => ({
+								text: item.text,
+							})),
+							status: "success",
+						},
+					} as ContentBlock
+				}
+
+				// Fall back to output handling if content is not available
+				if (messageBlock.output && typeof messageBlock.output === "string") {
+					return {
+						toolResult: {
+							toolUseId: messageBlock.tool_use_id || "",
+							content: [
+								{
+									text: messageBlock.output,
+								},
+							],
+							status: "success",
+						},
+					} as ContentBlock
+				}
+				// Handle array of content blocks if output is an array
+				if (Array.isArray(messageBlock.output)) {
+					return {
+						toolResult: {
+							toolUseId: messageBlock.tool_use_id || "",
+							content: messageBlock.output.map((part) => {
+								if (typeof part === "object" && "text" in part) {
+									return { text: part.text }
+								}
+								// Skip images in tool results as they're handled separately
+								if (typeof part === "object" && "type" in part && part.type === "image") {
+									return { text: "(see following message for image)" }
+								}
+								return { text: String(part) }
+							}),
+							status: "success",
+						},
+					} as ContentBlock
+				}
+
+				// Default case
+				return {
+					toolResult: {
+						toolUseId: messageBlock.tool_use_id || "",
+						content: [
+							{
+								text: String(messageBlock.output || ""),
+							},
+						],
+						status: "success",
+					},
+				} as ContentBlock
+			}
+
+			if (messageBlock.type === "video") {
+				const videoContent = messageBlock.s3Location
+					? {
+							s3Location: {
+								uri: messageBlock.s3Location.uri,
+								bucketOwner: messageBlock.s3Location.bucketOwner,
+							},
+						}
+					: messageBlock.source
+
+				return {
+					video: {
+						format: "mp4", // Default to mp4, adjust based on actual format if needed
+						source: videoContent,
+					},
+				} as ContentBlock
+			}
+
+			// Default case for unknown block types
+			return {
+				text: "[Unknown Block Type]",
+			} as ContentBlock
+		})
+
+		return {
+			role,
+			content,
+		}
+	})
 }
 
 /**
  * Convert Bedrock Converse stream events to Anthropic message format
  */
 export function convertToAnthropicMessage(
-    streamEvent: StreamEvent,
-    modelId: string
+	streamEvent: StreamEvent,
+	modelId: string,
 ): Partial<Anthropic.Messages.Message> {
-    // Handle metadata events
-    if (streamEvent.metadata?.usage) {
-        return {
-            id: '', // Bedrock doesn't provide message IDs
-            type: "message",
-            role: "assistant",
-            model: modelId,
-            usage: {
-                input_tokens: streamEvent.metadata.usage.inputTokens || 0,
-                output_tokens: streamEvent.metadata.usage.outputTokens || 0
-            }
-        }
-    }
-
-    // Handle content blocks
-    const text = streamEvent.contentBlockStart?.start?.text || streamEvent.contentBlockDelta?.delta?.text
-    if (text !== undefined) {
-        return {
-            type: "message",
-            role: "assistant",
-            content: [{ type: "text", text: text }],
-            model: modelId
-        }
-    }
-
-    // Handle message stop
-    if (streamEvent.messageStop) {
-        return {
-            type: "message",
-            role: "assistant",
-            stop_reason: streamEvent.messageStop.stopReason || null,
-            stop_sequence: null,
-            model: modelId
-        }
-    }
-
-    return {}
+	// Handle metadata events
+	if (streamEvent.metadata?.usage) {
+		return {
+			id: "", // Bedrock doesn't provide message IDs
+			type: "message",
+			role: "assistant",
+			model: modelId,
+			usage: {
+				input_tokens: streamEvent.metadata.usage.inputTokens || 0,
+				output_tokens: streamEvent.metadata.usage.outputTokens || 0,
+			},
+		}
+	}
+
+	// Handle content blocks
+	const text = streamEvent.contentBlockStart?.start?.text || streamEvent.contentBlockDelta?.delta?.text
+	if (text !== undefined) {
+		return {
+			type: "message",
+			role: "assistant",
+			content: [{ type: "text", text: text }],
+			model: modelId,
+		}
+	}
+
+	// Handle message stop
+	if (streamEvent.messageStop) {
+		return {
+			type: "message",
+			role: "assistant",
+			stop_reason: streamEvent.messageStop.stopReason || null,
+			stop_sequence: null,
+			model: modelId,
+		}
+	}
+
+	return {}
 }

+ 90 - 99
src/api/transform/vscode-lm-format.ts

@@ -1,5 +1,5 @@
-import { Anthropic } from "@anthropic-ai/sdk";
-import * as vscode from 'vscode';
+import { Anthropic } from "@anthropic-ai/sdk"
+import * as vscode from "vscode"
 
 /**
  * Safely converts a value into a plain object.
@@ -7,30 +7,31 @@ import * as vscode from 'vscode';
 function asObjectSafe(value: any): object {
 	// Handle null/undefined
 	if (!value) {
-		return {};
+		return {}
 	}
 
 	try {
 		// Handle strings that might be JSON
-		if (typeof value === 'string') {
-			return JSON.parse(value);
+		if (typeof value === "string") {
+			return JSON.parse(value)
 		}
 
 		// Handle pre-existing objects
-		if (typeof value === 'object') {
-			return Object.assign({}, value);
+		if (typeof value === "object") {
+			return Object.assign({}, value)
 		}
 
-		return {};
-	}
-	catch (error) {
-		console.warn('Cline <Language Model API>: Failed to parse object:', error);
-		return {};
+		return {}
+	} catch (error) {
+		console.warn("Cline <Language Model API>: Failed to parse object:", error)
+		return {}
 	}
 }
 
-export function convertToVsCodeLmMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): vscode.LanguageModelChatMessage[] {
-	const vsCodeLmMessages: vscode.LanguageModelChatMessage[] = [];
+export function convertToVsCodeLmMessages(
+	anthropicMessages: Anthropic.Messages.MessageParam[],
+): vscode.LanguageModelChatMessage[] {
+	const vsCodeLmMessages: vscode.LanguageModelChatMessage[] = []
 
 	for (const anthropicMessage of anthropicMessages) {
 		// Handle simple string messages
@@ -38,135 +39,129 @@ export function convertToVsCodeLmMessages(anthropicMessages: Anthropic.Messages.
 			vsCodeLmMessages.push(
 				anthropicMessage.role === "assistant"
 					? vscode.LanguageModelChatMessage.Assistant(anthropicMessage.content)
-					: vscode.LanguageModelChatMessage.User(anthropicMessage.content)
-			);
-			continue;
+					: vscode.LanguageModelChatMessage.User(anthropicMessage.content),
+			)
+			continue
 		}
 
 		// Handle complex message structures
 		switch (anthropicMessage.role) {
 			case "user": {
 				const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
-					nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[];
-					toolMessages: Anthropic.ToolResultBlockParam[];
+					nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
+					toolMessages: Anthropic.ToolResultBlockParam[]
 				}>(
 					(acc, part) => {
 						if (part.type === "tool_result") {
-							acc.toolMessages.push(part);
-						}
-						else if (part.type === "text" || part.type === "image") {
-							acc.nonToolMessages.push(part);
+							acc.toolMessages.push(part)
+						} else if (part.type === "text" || part.type === "image") {
+							acc.nonToolMessages.push(part)
 						}
-						return acc;
+						return acc
 					},
 					{ nonToolMessages: [], toolMessages: [] },
-				);
+				)
 
 				// Process tool messages first then non-tool messages
 				const contentParts = [
 					// Convert tool messages to ToolResultParts
 					...toolMessages.map((toolMessage) => {
 						// Process tool result content into TextParts
-						const toolContentParts: vscode.LanguageModelTextPart[] = (
+						const toolContentParts: vscode.LanguageModelTextPart[] =
 							typeof toolMessage.content === "string"
 								? [new vscode.LanguageModelTextPart(toolMessage.content)]
-								: (
-									toolMessage.content?.map((part) => {
+								: (toolMessage.content?.map((part) => {
 										if (part.type === "image") {
 											return new vscode.LanguageModelTextPart(
-												`[Image (${part.source?.type || 'Unknown source-type'}): ${part.source?.media_type || 'unknown media-type'} not supported by VSCode LM API]`
-											);
+												`[Image (${part.source?.type || "Unknown source-type"}): ${part.source?.media_type || "unknown media-type"} not supported by VSCode LM API]`,
+											)
 										}
-										return new vscode.LanguageModelTextPart(part.text);
-									})
-									?? [new vscode.LanguageModelTextPart("")]
-								)
-						);
-
-						return new vscode.LanguageModelToolResultPart(
-							toolMessage.tool_use_id,
-							toolContentParts
-						);
+										return new vscode.LanguageModelTextPart(part.text)
+									}) ?? [new vscode.LanguageModelTextPart("")])
+
+						return new vscode.LanguageModelToolResultPart(toolMessage.tool_use_id, toolContentParts)
 					}),
 
 					// Convert non-tool messages to TextParts after tool messages
 					...nonToolMessages.map((part) => {
 						if (part.type === "image") {
 							return new vscode.LanguageModelTextPart(
-								`[Image (${part.source?.type || 'Unknown source-type'}): ${part.source?.media_type || 'unknown media-type'} not supported by VSCode LM API]`
-							);
+								`[Image (${part.source?.type || "Unknown source-type"}): ${part.source?.media_type || "unknown media-type"} not supported by VSCode LM API]`,
+							)
 						}
-						return new vscode.LanguageModelTextPart(part.text);
-					})
-				];
+						return new vscode.LanguageModelTextPart(part.text)
+					}),
+				]
 
 				// Add single user message with all content parts
-				vsCodeLmMessages.push(vscode.LanguageModelChatMessage.User(contentParts));
-				break;
+				vsCodeLmMessages.push(vscode.LanguageModelChatMessage.User(contentParts))
+				break
 			}
 
 			case "assistant": {
 				const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
-					nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[];
-					toolMessages: Anthropic.ToolUseBlockParam[];
+					nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
+					toolMessages: Anthropic.ToolUseBlockParam[]
 				}>(
 					(acc, part) => {
 						if (part.type === "tool_use") {
-							acc.toolMessages.push(part);
-						}
-						else if (part.type === "text" || part.type === "image") {
-							acc.nonToolMessages.push(part);
+							acc.toolMessages.push(part)
+						} else if (part.type === "text" || part.type === "image") {
+							acc.nonToolMessages.push(part)
 						}
-						return acc;
+						return acc
 					},
 					{ nonToolMessages: [], toolMessages: [] },
-				);
+				)
 
-				// Process tool messages first then non-tool messages 
+				// Process tool messages first then non-tool messages
 				const contentParts = [
 					// Convert tool messages to ToolCallParts first
-					...toolMessages.map((toolMessage) =>
-						new vscode.LanguageModelToolCallPart(
-							toolMessage.id,
-							toolMessage.name,
-							asObjectSafe(toolMessage.input)
-						)
+					...toolMessages.map(
+						(toolMessage) =>
+							new vscode.LanguageModelToolCallPart(
+								toolMessage.id,
+								toolMessage.name,
+								asObjectSafe(toolMessage.input),
+							),
 					),
 
 					// Convert non-tool messages to TextParts after tool messages
 					...nonToolMessages.map((part) => {
 						if (part.type === "image") {
-							return new vscode.LanguageModelTextPart("[Image generation not supported by VSCode LM API]");
+							return new vscode.LanguageModelTextPart("[Image generation not supported by VSCode LM API]")
 						}
-						return new vscode.LanguageModelTextPart(part.text);
-					})
-				];
+						return new vscode.LanguageModelTextPart(part.text)
+					}),
+				]
 
 				// Add the assistant message to the list of messages
-				vsCodeLmMessages.push(vscode.LanguageModelChatMessage.Assistant(contentParts));
-				break;
+				vsCodeLmMessages.push(vscode.LanguageModelChatMessage.Assistant(contentParts))
+				break
 			}
 		}
 	}
 
-	return vsCodeLmMessages;
+	return vsCodeLmMessages
 }
 
 export function convertToAnthropicRole(vsCodeLmMessageRole: vscode.LanguageModelChatMessageRole): string | null {
 	switch (vsCodeLmMessageRole) {
 		case vscode.LanguageModelChatMessageRole.Assistant:
-			return "assistant";
+			return "assistant"
 		case vscode.LanguageModelChatMessageRole.User:
-			return "user";
+			return "user"
 		default:
-			return null;
+			return null
 	}
 }
 
-export async function convertToAnthropicMessage(vsCodeLmMessage: vscode.LanguageModelChatMessage): Promise<Anthropic.Messages.Message> {
-	const anthropicRole: string | null = convertToAnthropicRole(vsCodeLmMessage.role);
+export async function convertToAnthropicMessage(
+	vsCodeLmMessage: vscode.LanguageModelChatMessage,
+): Promise<Anthropic.Messages.Message> {
+	const anthropicRole: string | null = convertToAnthropicRole(vsCodeLmMessage.role)
 	if (anthropicRole !== "assistant") {
-		throw new Error("Cline <Language Model API>: Only assistant messages are supported.");
+		throw new Error("Cline <Language Model API>: Only assistant messages are supported.")
 	}
 
 	return {
@@ -174,36 +169,32 @@ export async function convertToAnthropicMessage(vsCodeLmMessage: vscode.Language
 		type: "message",
 		model: "vscode-lm",
 		role: anthropicRole,
-		content: (
-			vsCodeLmMessage.content
-				.map((part): Anthropic.ContentBlock | null => {
-					if (part instanceof vscode.LanguageModelTextPart) {
-						return {
-							type: "text",
-							text: part.value
-						};
+		content: vsCodeLmMessage.content
+			.map((part): Anthropic.ContentBlock | null => {
+				if (part instanceof vscode.LanguageModelTextPart) {
+					return {
+						type: "text",
+						text: part.value,
 					}
-
-					if (part instanceof vscode.LanguageModelToolCallPart) {
-						return {
-							type: "tool_use",
-							id: part.callId || crypto.randomUUID(),
-							name: part.name,
-							input: asObjectSafe(part.input)
-						};
+				}
+
+				if (part instanceof vscode.LanguageModelToolCallPart) {
+					return {
+						type: "tool_use",
+						id: part.callId || crypto.randomUUID(),
+						name: part.name,
+						input: asObjectSafe(part.input),
 					}
+				}
 
-					return null;
-				})
-				.filter(
-					(part): part is Anthropic.ContentBlock => part !== null
-				)
-		),
+				return null
+			})
+			.filter((part): part is Anthropic.ContentBlock => part !== null),
 		stop_reason: null,
 		stop_sequence: null,
 		usage: {
 			input_tokens: 0,
 			output_tokens: 0,
-		}
-	};
+		},
+	}
 }

+ 115 - 75
src/core/Cline.ts

@@ -13,7 +13,13 @@ import { ApiHandler, SingleCompletionHandler, buildApiHandler } from "../api"
 import { ApiStream } from "../api/transform/stream"
 import { DiffViewProvider } from "../integrations/editor/DiffViewProvider"
 import { findToolName, formatContentBlockToMarkdown } from "../integrations/misc/export-markdown"
-import { extractTextFromFile, addLineNumbers, stripLineNumbers, everyLineHasLineNumbers, truncateOutput } from "../integrations/misc/extract-text"
+import {
+	extractTextFromFile,
+	addLineNumbers,
+	stripLineNumbers,
+	everyLineHasLineNumbers,
+	truncateOutput,
+} from "../integrations/misc/extract-text"
 import { TerminalManager } from "../integrations/terminal/TerminalManager"
 import { UrlContentFetcher } from "../services/browser/UrlContentFetcher"
 import { listFiles } from "../services/glob/list-files"
@@ -112,7 +118,7 @@ export class Cline {
 		experimentalDiffStrategy: boolean = false,
 	) {
 		if (!task && !images && !historyItem) {
-			throw new Error('Either historyItem or task/images must be provided');
+			throw new Error("Either historyItem or task/images must be provided")
 		}
 
 		this.taskId = crypto.randomUUID()
@@ -144,7 +150,8 @@ export class Cline {
 	async updateDiffStrategy(experimentalDiffStrategy?: boolean) {
 		// If not provided, get from current state
 		if (experimentalDiffStrategy === undefined) {
-			const { experimentalDiffStrategy: stateExperimentalDiffStrategy } = await this.providerRef.deref()?.getState() ?? {}
+			const { experimentalDiffStrategy: stateExperimentalDiffStrategy } =
+				(await this.providerRef.deref()?.getState()) ?? {}
 			experimentalDiffStrategy = stateExperimentalDiffStrategy ?? false
 		}
 		this.diffStrategy = getDiffStrategy(this.api.getModel().id, this.fuzzyMatchThreshold, experimentalDiffStrategy)
@@ -471,7 +478,7 @@ export class Cline {
 		// need to make sure that the api conversation history can be resumed by the api, even if it goes out of sync with cline messages
 
 		let existingApiConversationHistory: Anthropic.Messages.MessageParam[] =
-		await this.getSavedApiConversationHistory()
+			await this.getSavedApiConversationHistory()
 
 		// Now present the cline messages to the user and ask if they want to resume
 
@@ -582,8 +589,8 @@ export class Cline {
 					: [{ type: "text", text: lastMessage.content }]
 				if (previousAssistantMessage && previousAssistantMessage.role === "assistant") {
 					const assistantContent = Array.isArray(previousAssistantMessage.content)
-							? previousAssistantMessage.content
-							: [{ type: "text", text: previousAssistantMessage.content }]
+						? previousAssistantMessage.content
+						: [{ type: "text", text: previousAssistantMessage.content }]
 
 					const toolUseBlocks = assistantContent.filter(
 						(block) => block.type === "tool_use",
@@ -756,8 +763,8 @@ export class Cline {
 		// grouping command_output messages despite any gaps anyways)
 		await delay(50)
 
-		const { terminalOutputLineLimit } = await this.providerRef.deref()?.getState() ?? {}
-		const output = truncateOutput(lines.join('\n'), terminalOutputLineLimit)
+		const { terminalOutputLineLimit } = (await this.providerRef.deref()?.getState()) ?? {}
+		const output = truncateOutput(lines.join("\n"), terminalOutputLineLimit)
 		const result = output.trim()
 
 		if (userFeedback) {
@@ -788,7 +795,8 @@ export class Cline {
 	async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
 		let mcpHub: McpHub | undefined
 
-		const { mcpEnabled, alwaysApproveResubmit, requestDelaySeconds } = await this.providerRef.deref()?.getState() ?? {}
+		const { mcpEnabled, alwaysApproveResubmit, requestDelaySeconds } =
+			(await this.providerRef.deref()?.getState()) ?? {}
 
 		if (mcpEnabled ?? true) {
 			mcpHub = this.providerRef.deref()?.mcpHub
@@ -801,24 +809,27 @@ export class Cline {
 			})
 		}
 
-		const { browserViewportSize, preferredLanguage, mode, customPrompts } = await this.providerRef.deref()?.getState() ?? {}
-		const systemPrompt = await SYSTEM_PROMPT(
-			cwd,
-			this.api.getModel().info.supportsComputerUse ?? false,
-			mcpHub,
-			this.diffStrategy,
-			browserViewportSize,
-			mode,
-			customPrompts
-		) + await addCustomInstructions(
-			{
-				customInstructions: this.customInstructions,
+		const { browserViewportSize, preferredLanguage, mode, customPrompts } =
+			(await this.providerRef.deref()?.getState()) ?? {}
+		const systemPrompt =
+			(await SYSTEM_PROMPT(
+				cwd,
+				this.api.getModel().info.supportsComputerUse ?? false,
+				mcpHub,
+				this.diffStrategy,
+				browserViewportSize,
+				mode,
 				customPrompts,
-				preferredLanguage
-			},
-			cwd,
-			mode
-		)
+			)) +
+			(await addCustomInstructions(
+				{
+					customInstructions: this.customInstructions,
+					customPrompts,
+					preferredLanguage,
+				},
+				cwd,
+				mode,
+			))
 
 		// If the previous API request's total token usage is close to the context window, truncate the conversation history to free up space for the new request
 		if (previousApiReqIndex >= 0) {
@@ -845,18 +856,18 @@ export class Cline {
 			if (Array.isArray(content)) {
 				if (!this.api.getModel().info.supportsImages) {
 					// Convert image blocks to text descriptions
-					content = content.map(block => {
-						if (block.type === 'image') {
+					content = content.map((block) => {
+						if (block.type === "image") {
 							// Convert image blocks to text descriptions
 							// Note: We can't access the actual image content/url due to API limitations,
 							// but we can indicate that an image was present in the conversation
 							return {
-								type: 'text',
-								text: '[Referenced image in conversation]'
-							};
+								type: "text",
+								text: "[Referenced image in conversation]",
+							}
 						}
-						return block;
-					});
+						return block
+					})
 				}
 			}
 			return { role, content }
@@ -876,7 +887,12 @@ export class Cline {
 				// Automatically retry with delay
 				// Show countdown timer in error color
 				for (let i = requestDelay; i > 0; i--) {
-					await this.say("api_req_retry_delayed", `${errorMsg}\n\nRetrying in ${i} seconds...`, undefined, true)
+					await this.say(
+						"api_req_retry_delayed",
+						`${errorMsg}\n\nRetrying in ${i} seconds...`,
+						undefined,
+						true,
+					)
 					await delay(1000)
 				}
 				await this.say("api_req_retry_delayed", `${errorMsg}\n\nRetrying now...`, undefined, false)
@@ -1125,7 +1141,7 @@ export class Cline {
 				}
 
 				// Validate tool use based on current mode
-				const { mode } = await this.providerRef.deref()?.getState() ?? {}
+				const { mode } = (await this.providerRef.deref()?.getState()) ?? {}
 				try {
 					validateToolUse(block.name, mode ?? defaultModeSlug)
 				} catch (error) {
@@ -1192,7 +1208,10 @@ export class Cline {
 									await this.diffViewProvider.open(relPath)
 								}
 								// editor is open, stream content in
-								await this.diffViewProvider.update(everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent, false)
+								await this.diffViewProvider.update(
+									everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
+									false,
+								)
 								break
 							} else {
 								if (!relPath) {
@@ -1209,7 +1228,9 @@ export class Cline {
 								}
 								if (!predictedLineCount) {
 									this.consecutiveMistakeCount++
-									pushToolResult(await this.sayAndCreateMissingParamError("write_to_file", "line_count"))
+									pushToolResult(
+										await this.sayAndCreateMissingParamError("write_to_file", "line_count"),
+									)
 									await this.diffViewProvider.reset()
 									break
 								}
@@ -1224,17 +1245,28 @@ export class Cline {
 									await this.ask("tool", partialMessage, true).catch(() => {}) // sending true for partial even though it's not a partial, this shows the edit row before the content is streamed into the editor
 									await this.diffViewProvider.open(relPath)
 								}
-								await this.diffViewProvider.update(everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent, true)
+								await this.diffViewProvider.update(
+									everyLineHasLineNumbers(newContent) ? stripLineNumbers(newContent) : newContent,
+									true,
+								)
 								await delay(300) // wait for diff view to update
 								this.diffViewProvider.scrollToFirstDiff()
 
 								// Check for code omissions before proceeding
-								if (detectCodeOmission(this.diffViewProvider.originalContent || "", newContent, predictedLineCount)) {
+								if (
+									detectCodeOmission(
+										this.diffViewProvider.originalContent || "",
+										newContent,
+										predictedLineCount,
+									)
+								) {
 									if (this.diffStrategy) {
 										await this.diffViewProvider.revertChanges()
-										pushToolResult(formatResponse.toolError(
-											`Content appears to be truncated (file has ${newContent.split("\n").length} lines but was predicted to have ${predictedLineCount} lines), and found comments indicating omitted code (e.g., '// rest of code unchanged', '/* previous code */'). Please provide the complete file content without any omissions if possible, or otherwise use the 'apply_diff' tool to apply the diff to the original file.`
-										))
+										pushToolResult(
+											formatResponse.toolError(
+												`Content appears to be truncated (file has ${newContent.split("\n").length} lines but was predicted to have ${predictedLineCount} lines), and found comments indicating omitted code (e.g., '// rest of code unchanged', '/* previous code */'). Please provide the complete file content without any omissions if possible, or otherwise use the 'apply_diff' tool to apply the diff to the original file.`,
+											),
+										)
 										break
 									} else {
 										vscode.window
@@ -1285,7 +1317,7 @@ export class Cline {
 									pushToolResult(
 										`The user made the following updates to your content:\n\n${userEdits}\n\n` +
 											`The updated content, which includes both your original modifications and the user's edits, has been successfully saved to ${relPath.toPosix()}. Here is the full, updated content of the file, including line numbers:\n\n` +
-											`<final_file_content path="${relPath.toPosix()}">\n${addLineNumbers(finalContent || '')}\n</final_file_content>\n\n` +
+											`<final_file_content path="${relPath.toPosix()}">\n${addLineNumbers(finalContent || "")}\n</final_file_content>\n\n` +
 											`Please note:\n` +
 											`1. You do not need to re-write the file with these changes, as they have already been applied.\n` +
 											`2. Proceed with the task using this updated file content as the new baseline.\n` +
@@ -1347,21 +1379,24 @@ export class Cline {
 								const originalContent = await fs.readFile(absolutePath, "utf-8")
 
 								// Apply the diff to the original content
-								const diffResult = await this.diffStrategy?.applyDiff(
-									originalContent, 
-									diffContent, 
-									parseInt(block.params.start_line ?? ''), 
-									parseInt(block.params.end_line ?? '')
-								) ?? {
+								const diffResult = (await this.diffStrategy?.applyDiff(
+									originalContent,
+									diffContent,
+									parseInt(block.params.start_line ?? ""),
+									parseInt(block.params.end_line ?? ""),
+								)) ?? {
 									success: false,
-									error: "No diff strategy available"
+									error: "No diff strategy available",
 								}
 								if (!diffResult.success) {
 									this.consecutiveMistakeCount++
-									const currentCount = (this.consecutiveMistakeCountForApplyDiff.get(relPath) || 0) + 1
+									const currentCount =
+										(this.consecutiveMistakeCountForApplyDiff.get(relPath) || 0) + 1
 									this.consecutiveMistakeCountForApplyDiff.set(relPath, currentCount)
-									const errorDetails = diffResult.details ? JSON.stringify(diffResult.details, null, 2) : ''
-									const formattedError = `Unable to apply diff to file: ${absolutePath}\n\n<error_details>\n${diffResult.error}${errorDetails ? `\n\nDetails:\n${errorDetails}` : ''}\n</error_details>`
+									const errorDetails = diffResult.details
+										? JSON.stringify(diffResult.details, null, 2)
+										: ""
+									const formattedError = `Unable to apply diff to file: ${absolutePath}\n\n<error_details>\n${diffResult.error}${errorDetails ? `\n\nDetails:\n${errorDetails}` : ""}\n</error_details>`
 									if (currentCount >= 2) {
 										await this.say("error", formattedError)
 									}
@@ -1373,9 +1408,9 @@ export class Cline {
 								this.consecutiveMistakeCountForApplyDiff.delete(relPath)
 								// Show diff view before asking for approval
 								this.diffViewProvider.editType = "modify"
-								await this.diffViewProvider.open(relPath);
-								await this.diffViewProvider.update(diffResult.content, true);
-								await this.diffViewProvider.scrollToFirstDiff();
+								await this.diffViewProvider.open(relPath)
+								await this.diffViewProvider.update(diffResult.content, true)
+								await this.diffViewProvider.scrollToFirstDiff()
 
 								const completeMessage = JSON.stringify({
 									...sharedMessageProps,
@@ -1403,7 +1438,7 @@ export class Cline {
 									pushToolResult(
 										`The user made the following updates to your content:\n\n${userEdits}\n\n` +
 											`The updated content, which includes both your original modifications and the user's edits, has been successfully saved to ${relPath.toPosix()}. Here is the full, updated content of the file, including line numbers:\n\n` +
-											`<final_file_content path="${relPath.toPosix()}">\n${addLineNumbers(finalContent || '')}\n</final_file_content>\n\n` +
+											`<final_file_content path="${relPath.toPosix()}">\n${addLineNumbers(finalContent || "")}\n</final_file_content>\n\n` +
 											`Please note:\n` +
 											`1. You do not need to re-write the file with these changes, as they have already been applied.\n` +
 											`2. Proceed with the task using this updated file content as the new baseline.\n` +
@@ -1411,7 +1446,9 @@ export class Cline {
 											`${newProblemsMessage}`,
 									)
 								} else {
-									pushToolResult(`Changes successfully applied to ${relPath.toPosix()}:\n\n${newProblemsMessage}`)
+									pushToolResult(
+										`Changes successfully applied to ${relPath.toPosix()}:\n\n${newProblemsMessage}`,
+									)
 								}
 								await this.diffViewProvider.reset()
 								break
@@ -1615,7 +1652,7 @@ export class Cline {
 									await this.ask(
 										"browser_action_launch",
 										removeClosingTag("url", url),
-										block.partial
+										block.partial,
 									).catch(() => {})
 								} else {
 									await this.say(
@@ -1744,7 +1781,7 @@ export class Cline {
 						try {
 							if (block.partial) {
 								await this.ask("command", removeClosingTag("command", command), block.partial).catch(
-									() => {}
+									() => {},
 								)
 								break
 							} else {
@@ -2409,7 +2446,7 @@ export class Cline {
 			Promise.all(
 				userContent.map(async (block) => {
 					const shouldProcessMentions = (text: string) =>
-						text.includes("<task>") || text.includes("<feedback>");
+						text.includes("<task>") || text.includes("<feedback>")
 
 					if (block.type === "text") {
 						if (shouldProcessMentions(block.text)) {
@@ -2418,7 +2455,7 @@ export class Cline {
 								text: await parseMentions(block.text, cwd, this.urlContentFetcher),
 							}
 						}
-						return block;
+						return block
 					} else if (block.type === "tool_result") {
 						if (typeof block.content === "string") {
 							if (shouldProcessMentions(block.content)) {
@@ -2427,7 +2464,7 @@ export class Cline {
 									content: await parseMentions(block.content, cwd, this.urlContentFetcher),
 								}
 							}
-							return block;
+							return block
 						} else if (Array.isArray(block.content)) {
 							const parsedContent = await Promise.all(
 								block.content.map(async (contentBlock) => {
@@ -2445,7 +2482,7 @@ export class Cline {
 								content: parsedContent,
 							}
 						}
-						return block;
+						return block
 					}
 					return block
 				}),
@@ -2571,26 +2608,29 @@ export class Cline {
 		// Add current time information with timezone
 		const now = new Date()
 		const formatter = new Intl.DateTimeFormat(undefined, {
-			year: 'numeric',
-			month: 'numeric',
-			day: 'numeric',
-			hour: 'numeric',
-			minute: 'numeric',
-			second: 'numeric',
-			hour12: true
+			year: "numeric",
+			month: "numeric",
+			day: "numeric",
+			hour: "numeric",
+			minute: "numeric",
+			second: "numeric",
+			hour12: true,
 		})
 		const timeZone = formatter.resolvedOptions().timeZone
 		const timeZoneOffset = -now.getTimezoneOffset() / 60 // Convert to hours and invert sign to match conventional notation
-		const timeZoneOffsetStr = `${timeZoneOffset >= 0 ? '+' : ''}${timeZoneOffset}:00`
+		const timeZoneOffsetStr = `${timeZoneOffset >= 0 ? "+" : ""}${timeZoneOffset}:00`
 		details += `\n\n# Current Time\n${formatter.format(now)} (${timeZone}, UTC${timeZoneOffsetStr})`
 
 		// Add current mode and any mode-specific warnings
-		const { mode } = await this.providerRef.deref()?.getState() ?? {}
+		const { mode } = (await this.providerRef.deref()?.getState()) ?? {}
 		const currentMode = mode ?? defaultModeSlug
 		details += `\n\n# Current Mode\n${currentMode}`
 
 		// Add warning if not in code mode
-		if (!isToolAllowedForMode('write_to_file', currentMode) || !isToolAllowedForMode('execute_command', currentMode)) {
+		if (
+			!isToolAllowedForMode("write_to_file", currentMode) ||
+			!isToolAllowedForMode("execute_command", currentMode)
+		) {
 			details += `\n\nNOTE: You are currently in '${currentMode}' mode which only allows read-only operations. To write files or execute commands, the user will need to switch to '${defaultModeSlug}' mode. Note that only the user can switch modes.`
 		}
 
@@ -2609,4 +2649,4 @@ export class Cline {
 
 		return `<environment_details>\n${details.trim()}\n</environment_details>`
 	}
-}
+}

+ 797 - 825
src/core/__tests__/Cline.test.ts

@@ -1,835 +1,807 @@
-import { Cline } from '../Cline';
-import { ClineProvider } from '../webview/ClineProvider';
-import { ApiConfiguration, ModelInfo } from '../../shared/api';
-import { ApiStreamChunk } from '../../api/transform/stream';
-import { Anthropic } from '@anthropic-ai/sdk';
-import * as vscode from 'vscode';
+import { Cline } from "../Cline"
+import { ClineProvider } from "../webview/ClineProvider"
+import { ApiConfiguration, ModelInfo } from "../../shared/api"
+import { ApiStreamChunk } from "../../api/transform/stream"
+import { Anthropic } from "@anthropic-ai/sdk"
+import * as vscode from "vscode"
 
 // Mock all MCP-related modules
-jest.mock('@modelcontextprotocol/sdk/types.js', () => ({
-    CallToolResultSchema: {},
-    ListResourcesResultSchema: {},
-    ListResourceTemplatesResultSchema: {},
-    ListToolsResultSchema: {},
-    ReadResourceResultSchema: {},
-    ErrorCode: {
-        InvalidRequest: 'InvalidRequest',
-        MethodNotFound: 'MethodNotFound',
-        InternalError: 'InternalError'
-    },
-    McpError: class McpError extends Error {
-        code: string;
-        constructor(code: string, message: string) {
-            super(message);
-            this.code = code;
-            this.name = 'McpError';
-        }
-    }
-}), { virtual: true });
-
-jest.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
-    Client: jest.fn().mockImplementation(() => ({
-        connect: jest.fn().mockResolvedValue(undefined),
-        close: jest.fn().mockResolvedValue(undefined),
-        listTools: jest.fn().mockResolvedValue({ tools: [] }),
-        callTool: jest.fn().mockResolvedValue({ content: [] })
-    }))
-}), { virtual: true });
-
-jest.mock('@modelcontextprotocol/sdk/client/stdio.js', () => ({
-    StdioClientTransport: jest.fn().mockImplementation(() => ({
-        connect: jest.fn().mockResolvedValue(undefined),
-        close: jest.fn().mockResolvedValue(undefined)
-    }))
-}), { virtual: true });
+jest.mock(
+	"@modelcontextprotocol/sdk/types.js",
+	() => ({
+		CallToolResultSchema: {},
+		ListResourcesResultSchema: {},
+		ListResourceTemplatesResultSchema: {},
+		ListToolsResultSchema: {},
+		ReadResourceResultSchema: {},
+		ErrorCode: {
+			InvalidRequest: "InvalidRequest",
+			MethodNotFound: "MethodNotFound",
+			InternalError: "InternalError",
+		},
+		McpError: class McpError extends Error {
+			code: string
+			constructor(code: string, message: string) {
+				super(message)
+				this.code = code
+				this.name = "McpError"
+			}
+		},
+	}),
+	{ virtual: true },
+)
+
+jest.mock(
+	"@modelcontextprotocol/sdk/client/index.js",
+	() => ({
+		Client: jest.fn().mockImplementation(() => ({
+			connect: jest.fn().mockResolvedValue(undefined),
+			close: jest.fn().mockResolvedValue(undefined),
+			listTools: jest.fn().mockResolvedValue({ tools: [] }),
+			callTool: jest.fn().mockResolvedValue({ content: [] }),
+		})),
+	}),
+	{ virtual: true },
+)
+
+jest.mock(
+	"@modelcontextprotocol/sdk/client/stdio.js",
+	() => ({
+		StdioClientTransport: jest.fn().mockImplementation(() => ({
+			connect: jest.fn().mockResolvedValue(undefined),
+			close: jest.fn().mockResolvedValue(undefined),
+		})),
+	}),
+	{ virtual: true },
+)
 
 // Mock fileExistsAtPath
-jest.mock('../../utils/fs', () => ({
-    fileExistsAtPath: jest.fn().mockImplementation((filePath) => {
-        return filePath.includes('ui_messages.json') || 
-               filePath.includes('api_conversation_history.json');
-    })
-}));
+jest.mock("../../utils/fs", () => ({
+	fileExistsAtPath: jest.fn().mockImplementation((filePath) => {
+		return filePath.includes("ui_messages.json") || filePath.includes("api_conversation_history.json")
+	}),
+}))
 
 // Mock fs/promises
-const mockMessages = [{
-    ts: Date.now(),
-    type: 'say',
-    say: 'text',
-    text: 'historical task'
-}];
-
-jest.mock('fs/promises', () => ({
-    mkdir: jest.fn().mockResolvedValue(undefined),
-    writeFile: jest.fn().mockResolvedValue(undefined),
-    readFile: jest.fn().mockImplementation((filePath) => {
-        if (filePath.includes('ui_messages.json')) {
-            return Promise.resolve(JSON.stringify(mockMessages));
-        }
-        if (filePath.includes('api_conversation_history.json')) {
-            return Promise.resolve('[]');
-        }
-        return Promise.resolve('[]');
-    }),
-    unlink: jest.fn().mockResolvedValue(undefined),
-    rmdir: jest.fn().mockResolvedValue(undefined)
-}));
+const mockMessages = [
+	{
+		ts: Date.now(),
+		type: "say",
+		say: "text",
+		text: "historical task",
+	},
+]
+
+jest.mock("fs/promises", () => ({
+	mkdir: jest.fn().mockResolvedValue(undefined),
+	writeFile: jest.fn().mockResolvedValue(undefined),
+	readFile: jest.fn().mockImplementation((filePath) => {
+		if (filePath.includes("ui_messages.json")) {
+			return Promise.resolve(JSON.stringify(mockMessages))
+		}
+		if (filePath.includes("api_conversation_history.json")) {
+			return Promise.resolve("[]")
+		}
+		return Promise.resolve("[]")
+	}),
+	unlink: jest.fn().mockResolvedValue(undefined),
+	rmdir: jest.fn().mockResolvedValue(undefined),
+}))
 
 // Mock dependencies
-jest.mock('vscode', () => {
-    const mockDisposable = { dispose: jest.fn() };
-    const mockEventEmitter = {
-        event: jest.fn(),
-        fire: jest.fn()
-    };
-
-    const mockTextDocument = {
-        uri: {
-            fsPath: '/mock/workspace/path/file.ts'
-        }
-    };
-
-    const mockTextEditor = {
-        document: mockTextDocument
-    };
-
-    const mockTab = {
-        input: {
-            uri: {
-                fsPath: '/mock/workspace/path/file.ts'
-            }
-        }
-    };
-
-    const mockTabGroup = {
-        tabs: [mockTab]
-    };
-
-    return {
-        window: {
-            createTextEditorDecorationType: jest.fn().mockReturnValue({
-                dispose: jest.fn()
-            }),
-            visibleTextEditors: [mockTextEditor],
-            tabGroups: {
-                all: [mockTabGroup]
-            }
-        },
-        workspace: {
-            workspaceFolders: [{
-                uri: {
-                    fsPath: '/mock/workspace/path'
-                },
-                name: 'mock-workspace',
-                index: 0
-            }],
-            createFileSystemWatcher: jest.fn(() => ({
-                onDidCreate: jest.fn(() => mockDisposable),
-                onDidDelete: jest.fn(() => mockDisposable),
-                onDidChange: jest.fn(() => mockDisposable),
-                dispose: jest.fn()
-            })),
-            fs: {
-                stat: jest.fn().mockResolvedValue({ type: 1 }) // FileType.File = 1
-            },
-            onDidSaveTextDocument: jest.fn(() => mockDisposable)
-        },
-        env: {
-            uriScheme: 'vscode',
-            language: 'en'
-        },
-        EventEmitter: jest.fn().mockImplementation(() => mockEventEmitter),
-        Disposable: {
-            from: jest.fn()
-        },
-        TabInputText: jest.fn()
-    };
-});
+jest.mock("vscode", () => {
+	const mockDisposable = { dispose: jest.fn() }
+	const mockEventEmitter = {
+		event: jest.fn(),
+		fire: jest.fn(),
+	}
+
+	const mockTextDocument = {
+		uri: {
+			fsPath: "/mock/workspace/path/file.ts",
+		},
+	}
+
+	const mockTextEditor = {
+		document: mockTextDocument,
+	}
+
+	const mockTab = {
+		input: {
+			uri: {
+				fsPath: "/mock/workspace/path/file.ts",
+			},
+		},
+	}
+
+	const mockTabGroup = {
+		tabs: [mockTab],
+	}
+
+	return {
+		window: {
+			createTextEditorDecorationType: jest.fn().mockReturnValue({
+				dispose: jest.fn(),
+			}),
+			visibleTextEditors: [mockTextEditor],
+			tabGroups: {
+				all: [mockTabGroup],
+			},
+		},
+		workspace: {
+			workspaceFolders: [
+				{
+					uri: {
+						fsPath: "/mock/workspace/path",
+					},
+					name: "mock-workspace",
+					index: 0,
+				},
+			],
+			createFileSystemWatcher: jest.fn(() => ({
+				onDidCreate: jest.fn(() => mockDisposable),
+				onDidDelete: jest.fn(() => mockDisposable),
+				onDidChange: jest.fn(() => mockDisposable),
+				dispose: jest.fn(),
+			})),
+			fs: {
+				stat: jest.fn().mockResolvedValue({ type: 1 }), // FileType.File = 1
+			},
+			onDidSaveTextDocument: jest.fn(() => mockDisposable),
+		},
+		env: {
+			uriScheme: "vscode",
+			language: "en",
+		},
+		EventEmitter: jest.fn().mockImplementation(() => mockEventEmitter),
+		Disposable: {
+			from: jest.fn(),
+		},
+		TabInputText: jest.fn(),
+	}
+})
 
 // Mock p-wait-for to resolve immediately
-jest.mock('p-wait-for', () => ({
-    __esModule: true,
-    default: jest.fn().mockImplementation(async () => Promise.resolve())
-}));
-
-jest.mock('delay', () => ({
-    __esModule: true,
-    default: jest.fn().mockImplementation(async () => Promise.resolve())
-}));
-
-jest.mock('serialize-error', () => ({
-    __esModule: true,
-    serializeError: jest.fn().mockImplementation((error) => ({
-        name: error.name,
-        message: error.message,
-        stack: error.stack
-    }))
-}));
-
-jest.mock('strip-ansi', () => ({
-    __esModule: true,
-    default: jest.fn().mockImplementation((str) => str.replace(/\u001B\[\d+m/g, ''))
-}));
-
-jest.mock('globby', () => ({
-    __esModule: true,
-    globby: jest.fn().mockImplementation(async () => [])
-}));
-
-jest.mock('os-name', () => ({
-    __esModule: true,
-    default: jest.fn().mockReturnValue('Mock OS Name')
-}));
-
-jest.mock('default-shell', () => ({
-    __esModule: true,
-    default: '/bin/bash'  // Mock default shell path
-}));
-
-describe('Cline', () => {
-    let mockProvider: jest.Mocked<ClineProvider>;
-    let mockApiConfig: ApiConfiguration;
-    let mockOutputChannel: any;
-    let mockExtensionContext: vscode.ExtensionContext;
-    
-    beforeEach(() => {
-        // Setup mock extension context
-        mockExtensionContext = {
-            globalState: {
-                get: jest.fn().mockImplementation((key) => {
-                    if (key === 'taskHistory') {
-                        return [{
-                            id: '123',
-                            ts: Date.now(),
-                            task: 'historical task',
-                            tokensIn: 100,
-                            tokensOut: 200,
-                            cacheWrites: 0,
-                            cacheReads: 0,
-                            totalCost: 0.001
-                        }];
-                    }
-                    return undefined;
-                }),
-                update: jest.fn().mockImplementation((key, value) => Promise.resolve()),
-                keys: jest.fn().mockReturnValue([])
-            },
-            workspaceState: {
-                get: jest.fn().mockImplementation((key) => undefined),
-                update: jest.fn().mockImplementation((key, value) => Promise.resolve()),
-                keys: jest.fn().mockReturnValue([])
-            },
-            secrets: {
-                get: jest.fn().mockImplementation((key) => Promise.resolve(undefined)),
-                store: jest.fn().mockImplementation((key, value) => Promise.resolve()),
-                delete: jest.fn().mockImplementation((key) => Promise.resolve())
-            },
-            extensionUri: {
-                fsPath: '/mock/extension/path'
-            },
-            globalStorageUri: {
-                fsPath: '/mock/storage/path'
-            },
-            extension: {
-                packageJSON: {
-                    version: '1.0.0'
-                }
-            }
-        } as unknown as vscode.ExtensionContext;
-
-        // Setup mock output channel
-        mockOutputChannel = {
-            appendLine: jest.fn(),
-            append: jest.fn(),
-            clear: jest.fn(),
-            show: jest.fn(),
-            hide: jest.fn(),
-            dispose: jest.fn()
-        };
-
-        // Setup mock provider with output channel
-        mockProvider = new ClineProvider(mockExtensionContext, mockOutputChannel) as jest.Mocked<ClineProvider>;
-        
-        // Setup mock API configuration
-        mockApiConfig = {
-            apiProvider: 'anthropic',
-            apiModelId: 'claude-3-5-sonnet-20241022',
-            apiKey: 'test-api-key'  // Add API key to mock config
-        };
-
-        // Mock provider methods
-        mockProvider.postMessageToWebview = jest.fn().mockResolvedValue(undefined);
-        mockProvider.postStateToWebview = jest.fn().mockResolvedValue(undefined);
-        mockProvider.getTaskWithId = jest.fn().mockImplementation(async (id) => ({
-            historyItem: {
-                id,
-                ts: Date.now(),
-                task: 'historical task',
-                tokensIn: 100,
-                tokensOut: 200,
-                cacheWrites: 0,
-                cacheReads: 0,
-                totalCost: 0.001
-            },
-            taskDirPath: '/mock/storage/path/tasks/123',
-            apiConversationHistoryFilePath: '/mock/storage/path/tasks/123/api_conversation_history.json',
-            uiMessagesFilePath: '/mock/storage/path/tasks/123/ui_messages.json',
-            apiConversationHistory: []
-        }));
-    });
-
-    describe('constructor', () => {
-        it('should respect provided settings', () => {
-            const cline = new Cline(
-                mockProvider,
-                mockApiConfig,
-                'custom instructions',
-                false,
-                0.95, // 95% threshold
-                'test task'
-            );
-
-            expect(cline.customInstructions).toBe('custom instructions');
-            expect(cline.diffEnabled).toBe(false);
-        });
-
-        it('should use default fuzzy match threshold when not provided', () => {
-            const cline = new Cline(
-                mockProvider,
-                mockApiConfig,
-                'custom instructions',
-                true,
-                undefined,
-                'test task'
-            );
-
-            expect(cline.diffEnabled).toBe(true);
-            // The diff strategy should be created with default threshold (1.0)
-            expect(cline.diffStrategy).toBeDefined();
-        });
-
-        it('should use provided fuzzy match threshold', () => {
-            const getDiffStrategySpy = jest.spyOn(require('../diff/DiffStrategy'), 'getDiffStrategy');
-            
-            const cline = new Cline(
-                mockProvider,
-                mockApiConfig,
-                'custom instructions',
-                true,
-                0.9, // 90% threshold
-                'test task'
-            );
-
-            expect(cline.diffEnabled).toBe(true);
-            expect(cline.diffStrategy).toBeDefined();
-            expect(getDiffStrategySpy).toHaveBeenCalledWith('claude-3-5-sonnet-20241022', 0.9, false);
-            
-            getDiffStrategySpy.mockRestore();
-        });
-
-        it('should pass default threshold to diff strategy when not provided', () => {
-            const getDiffStrategySpy = jest.spyOn(require('../diff/DiffStrategy'), 'getDiffStrategy');
-            
-            const cline = new Cline(
-                mockProvider,
-                mockApiConfig,
-                'custom instructions',
-                true,
-                undefined,
-                'test task'
-            );
-
-            expect(cline.diffEnabled).toBe(true);
-            expect(cline.diffStrategy).toBeDefined();
-            expect(getDiffStrategySpy).toHaveBeenCalledWith('claude-3-5-sonnet-20241022', 1.0, false);
-            
-            getDiffStrategySpy.mockRestore();
-        });
-
-        it('should require either task or historyItem', () => {
-            expect(() => {
-                new Cline(
-                    mockProvider,
-                    mockApiConfig,
-                    undefined, // customInstructions
-                    false, // diffEnabled
-                    undefined, // fuzzyMatchThreshold
-                    undefined // task
-                );
-            }).toThrow('Either historyItem or task/images must be provided');
-        });
-    });
-
-    describe('getEnvironmentDetails', () => {
-        let originalDate: DateConstructor;
-        let mockDate: Date;
-
-        beforeEach(() => {
-            originalDate = global.Date;
-            const fixedTime = new Date('2024-01-01T12:00:00Z');
-            mockDate = new Date(fixedTime);
-            mockDate.getTimezoneOffset = jest.fn().mockReturnValue(420); // UTC-7
-
-            class MockDate extends Date {
-                constructor() {
-                    super();
-                    return mockDate;
-                }
-                static override now() {
-                    return mockDate.getTime();
-                }
-            }
-            
-            global.Date = MockDate as DateConstructor;
-
-            // Create a proper mock of Intl.DateTimeFormat
-            const mockDateTimeFormat = {
-                resolvedOptions: () => ({
-                    timeZone: 'America/Los_Angeles'
-                }),
-                format: () => '1/1/2024, 5:00:00 AM'
-            };
-
-            const MockDateTimeFormat = function(this: any) {
-                return mockDateTimeFormat;
-            } as any;
-
-            MockDateTimeFormat.prototype = mockDateTimeFormat;
-            MockDateTimeFormat.supportedLocalesOf = jest.fn().mockReturnValue(['en-US']);
-
-            global.Intl.DateTimeFormat = MockDateTimeFormat;
-        });
-
-        afterEach(() => {
-            global.Date = originalDate;
-        });
-
-        it('should include timezone information in environment details', async () => {
-            const cline = new Cline(
-                mockProvider,
-                mockApiConfig,
-                undefined,
-                false,
-                undefined,
-                'test task'
-            );
-
-            const details = await cline['getEnvironmentDetails'](false);
-            
-            // Verify timezone information is present and formatted correctly
-            expect(details).toContain('America/Los_Angeles');
-            expect(details).toMatch(/UTC-7:00/); // Fixed offset for America/Los_Angeles
-            expect(details).toContain('# Current Time');
-            expect(details).toMatch(/1\/1\/2024.*5:00:00 AM.*\(America\/Los_Angeles, UTC-7:00\)/); // Full time string format
-        });
-    
-        describe('API conversation handling', () => {
-            it('should clean conversation history before sending to API', async () => {
-                const cline = new Cline(
-                    mockProvider,
-                    mockApiConfig,
-                    undefined,
-                    false,
-                    undefined,
-                    'test task'
-                );
-    
-                // Mock the API's createMessage method to capture the conversation history
-                const createMessageSpy = jest.fn();
-                const mockStream = {
-                    async *[Symbol.asyncIterator]() {
-                        yield { type: 'text', text: '' };
-                    },
-                    async next() {
-                        return { done: true, value: undefined };
-                    },
-                    async return() {
-                        return { done: true, value: undefined };
-                    },
-                    async throw(e: any) {
-                        throw e;
-                    },
-                    async [Symbol.asyncDispose]() {
-                        // Cleanup
-                    }
-                } as AsyncGenerator<ApiStreamChunk>;
-                
-                jest.spyOn(cline.api, 'createMessage').mockImplementation((...args) => {
-                    createMessageSpy(...args);
-                    return mockStream;
-                });
-
-                // Add a message with extra properties to the conversation history
-                const messageWithExtra = {
-                    role: 'user' as const,
-                    content: [{ type: 'text' as const, text: 'test message' }],
-                    ts: Date.now(),
-                    extraProp: 'should be removed'
-                };
-                cline.apiConversationHistory = [messageWithExtra];
-
-                // Trigger an API request
-                await cline.recursivelyMakeClineRequests([
-                    { type: 'text', text: 'test request' }
-                ]);
-
-                // Get all calls to createMessage
-                const calls = createMessageSpy.mock.calls;
-                
-                // Find the call that includes our test message
-                const relevantCall = calls.find(call =>
-                    call[1]?.some((msg: any) =>
-                        msg.content?.[0]?.text === 'test message'
-                    )
-                );
-
-                // Verify the conversation history was cleaned in the relevant call
-                expect(relevantCall?.[1]).toEqual(
-                    expect.arrayContaining([
-                        {
-                            role: 'user',
-                            content: [{ type: 'text', text: 'test message' }]
-                        }
-                    ])
-                );
-
-                // Verify extra properties were removed
-                const passedMessage = relevantCall?.[1].find((msg: any) =>
-                    msg.content?.[0]?.text === 'test message'
-                );
-                expect(passedMessage).not.toHaveProperty('ts');
-                expect(passedMessage).not.toHaveProperty('extraProp');
-            });
-
-            it('should handle image blocks based on model capabilities', async () => {
-                // Create two configurations - one with image support, one without
-                const configWithImages = {
-                    ...mockApiConfig,
-                    apiModelId: 'claude-3-sonnet'
-                };
-                const configWithoutImages = {
-                    ...mockApiConfig,
-                    apiModelId: 'gpt-3.5-turbo'
-                };
-
-                // Create test conversation history with mixed content
-                const conversationHistory: (Anthropic.MessageParam & { ts?: number })[] = [
-                    {
-                        role: 'user' as const,
-                        content: [
-                            {
-                                type: 'text' as const,
-                                text: 'Here is an image'
-                            } satisfies Anthropic.TextBlockParam,
-                            {
-                                type: 'image' as const,
-                                source: {
-                                    type: 'base64' as const,
-                                    media_type: 'image/jpeg',
-                                    data: 'base64data'
-                                }
-                            } satisfies Anthropic.ImageBlockParam
-                        ]
-                    },
-                    {
-                        role: 'assistant' as const,
-                        content: [{
-                            type: 'text' as const,
-                            text: 'I see the image'
-                        } satisfies Anthropic.TextBlockParam]
-                    }
-                ];
-
-                // Test with model that supports images
-                const clineWithImages = new Cline(
-                    mockProvider,
-                    configWithImages,
-                    undefined,
-                    false,
-                    undefined,
-                    'test task'
-                );
-                // Mock the model info to indicate image support
-                jest.spyOn(clineWithImages.api, 'getModel').mockReturnValue({
-                    id: 'claude-3-sonnet',
-                    info: {
-                        supportsImages: true,
-                        supportsPromptCache: true,
-                        supportsComputerUse: true,
-                        contextWindow: 200000,
-                        maxTokens: 4096,
-                        inputPrice: 0.25,
-                        outputPrice: 0.75
-                    } as ModelInfo
-                });
-                clineWithImages.apiConversationHistory = conversationHistory;
-
-                // Test with model that doesn't support images
-                const clineWithoutImages = new Cline(
-                    mockProvider,
-                    configWithoutImages,
-                    undefined,
-                    false,
-                    undefined,
-                    'test task'
-                );
-                // Mock the model info to indicate no image support
-                jest.spyOn(clineWithoutImages.api, 'getModel').mockReturnValue({
-                    id: 'gpt-3.5-turbo',
-                    info: {
-                        supportsImages: false,
-                        supportsPromptCache: false,
-                        supportsComputerUse: false,
-                        contextWindow: 16000,
-                        maxTokens: 2048,
-                        inputPrice: 0.1,
-                        outputPrice: 0.2
-                    } as ModelInfo
-                });
-                clineWithoutImages.apiConversationHistory = conversationHistory;
-
-                // Create message spy for both instances
-                const createMessageSpyWithImages = jest.fn();
-                const createMessageSpyWithoutImages = jest.fn();
-                const mockStream = {
-                    async *[Symbol.asyncIterator]() {
-                        yield { type: 'text', text: '' };
-                    }
-                } as AsyncGenerator<ApiStreamChunk>;
-
-                jest.spyOn(clineWithImages.api, 'createMessage').mockImplementation((...args) => {
-                    createMessageSpyWithImages(...args);
-                    return mockStream;
-                });
-                jest.spyOn(clineWithoutImages.api, 'createMessage').mockImplementation((...args) => {
-                    createMessageSpyWithoutImages(...args);
-                    return mockStream;
-                });
-
-                // Trigger API requests for both instances
-                await clineWithImages.recursivelyMakeClineRequests([{ type: 'text', text: 'test' }]);
-                await clineWithoutImages.recursivelyMakeClineRequests([{ type: 'text', text: 'test' }]);
-
-                // Verify model with image support preserves image blocks
-                const callsWithImages = createMessageSpyWithImages.mock.calls;
-                const historyWithImages = callsWithImages[0][1][0];
-                expect(historyWithImages.content).toHaveLength(2);
-                expect(historyWithImages.content[0]).toEqual({ type: 'text', text: 'Here is an image' });
-                expect(historyWithImages.content[1]).toHaveProperty('type', 'image');
-
-                // Verify model without image support converts image blocks to text
-                const callsWithoutImages = createMessageSpyWithoutImages.mock.calls;
-                const historyWithoutImages = callsWithoutImages[0][1][0];
-                expect(historyWithoutImages.content).toHaveLength(2);
-                expect(historyWithoutImages.content[0]).toEqual({ type: 'text', text: 'Here is an image' });
-                expect(historyWithoutImages.content[1]).toEqual({
-                    type: 'text',
-                    text: '[Referenced image in conversation]'
-                });
-            });
-        
-            it('should handle API retry with countdown', async () => {
-                const cline = new Cline(
-                    mockProvider,
-                    mockApiConfig,
-                    undefined,
-                    false,
-                    undefined,
-                    'test task'
-                );
-
-                // Mock delay to track countdown timing
-                const mockDelay = jest.fn().mockResolvedValue(undefined);
-                jest.spyOn(require('delay'), 'default').mockImplementation(mockDelay);
-
-                // Mock say to track messages
-                const saySpy = jest.spyOn(cline, 'say');
-
-                // Create a stream that fails on first chunk
-                const mockError = new Error('API Error');
-                const mockFailedStream = {
-                    async *[Symbol.asyncIterator]() {
-                        throw mockError;
-                    },
-                    async next() {
-                        throw mockError;
-                    },
-                    async return() {
-                        return { done: true, value: undefined };
-                    },
-                    async throw(e: any) {
-                        throw e;
-                    },
-                    async [Symbol.asyncDispose]() {
-                        // Cleanup
-                    }
-                } as AsyncGenerator<ApiStreamChunk>;
-
-                // Create a successful stream for retry
-                const mockSuccessStream = {
-                    async *[Symbol.asyncIterator]() {
-                        yield { type: 'text', text: 'Success' };
-                    },
-                    async next() {
-                        return { done: true, value: { type: 'text', text: 'Success' } };
-                    },
-                    async return() {
-                        return { done: true, value: undefined };
-                    },
-                    async throw(e: any) {
-                        throw e;
-                    },
-                    async [Symbol.asyncDispose]() {
-                        // Cleanup
-                    }
-                } as AsyncGenerator<ApiStreamChunk>;
-
-                // Mock createMessage to fail first then succeed
-                let firstAttempt = true;
-                jest.spyOn(cline.api, 'createMessage').mockImplementation(() => {
-                    if (firstAttempt) {
-                        firstAttempt = false;
-                        return mockFailedStream;
-                    }
-                    return mockSuccessStream;
-                });
-
-                // Set alwaysApproveResubmit and requestDelaySeconds
-                mockProvider.getState = jest.fn().mockResolvedValue({
-                    alwaysApproveResubmit: true,
-                    requestDelaySeconds: 3
-                });
-
-                // Mock previous API request message
-                cline.clineMessages = [{
-                    ts: Date.now(),
-                    type: 'say',
-                    say: 'api_req_started',
-                    text: JSON.stringify({
-                        tokensIn: 100,
-                        tokensOut: 50,
-                        cacheWrites: 0,
-                        cacheReads: 0,
-                        request: 'test request'
-                    })
-                }];
-
-                // Trigger API request
-                const iterator = cline.attemptApiRequest(0);
-                await iterator.next();
-
-                // Verify countdown messages
-                expect(saySpy).toHaveBeenCalledWith(
-                    'api_req_retry_delayed',
-                    expect.stringContaining('Retrying in 3 seconds'),
-                    undefined,
-                    true
-                );
-                expect(saySpy).toHaveBeenCalledWith(
-                    'api_req_retry_delayed',
-                    expect.stringContaining('Retrying in 2 seconds'),
-                    undefined,
-                    true
-                );
-                expect(saySpy).toHaveBeenCalledWith(
-                    'api_req_retry_delayed',
-                    expect.stringContaining('Retrying in 1 seconds'),
-                    undefined,
-                    true
-                );
-                expect(saySpy).toHaveBeenCalledWith(
-                    'api_req_retry_delayed',
-                    expect.stringContaining('Retrying now'),
-                    undefined,
-                    false
-                );
-
-                // Verify delay was called correctly
-                expect(mockDelay).toHaveBeenCalledTimes(3);
-                expect(mockDelay).toHaveBeenCalledWith(1000);
-
-                // Verify error message content
-                const errorMessage = saySpy.mock.calls.find(
-                    call => call[1]?.includes(mockError.message)
-                )?.[1];
-                expect(errorMessage).toBe(`${mockError.message}\n\nRetrying in 3 seconds...`);
-            });
-
-            describe('loadContext', () => {
-                it('should process mentions in task and feedback tags', async () => {
-                    const cline = new Cline(
-                        mockProvider,
-                        mockApiConfig,
-                        undefined,
-                        false,
-                        undefined,
-                        'test task'
-                    );
-        
-                    // Mock parseMentions to track calls
-                    const mockParseMentions = jest.fn().mockImplementation(text => `processed: ${text}`);
-                    jest.spyOn(require('../../core/mentions'), 'parseMentions').mockImplementation(mockParseMentions);
-        
-                    const userContent = [
-                        {
-                            type: 'text',
-                            text: 'Regular text with @/some/path'
-                        } as const,
-                        {
-                            type: 'text',
-                            text: '<task>Text with @/some/path in task tags</task>'
-                        } as const,
-                        {
-                            type: 'tool_result',
-                            tool_use_id: 'test-id',
-                            content: [{
-                                type: 'text',
-                                text: '<feedback>Check @/some/path</feedback>'
-                            }]
-                        } as Anthropic.ToolResultBlockParam,
-                        {
-                            type: 'tool_result',
-                            tool_use_id: 'test-id-2',
-                            content: [{
-                                type: 'text',
-                                text: 'Regular tool result with @/path'
-                            }]
-                        } as Anthropic.ToolResultBlockParam
-                    ];
-        
-                    // Process the content
-                    const [processedContent] = await cline['loadContext'](userContent);
-        
-                    // Regular text should not be processed
-                    expect((processedContent[0] as Anthropic.TextBlockParam).text)
-                        .toBe('Regular text with @/some/path');
-        
-                    // Text within task tags should be processed
-                    expect((processedContent[1] as Anthropic.TextBlockParam).text)
-                        .toContain('processed:');
-                    expect(mockParseMentions).toHaveBeenCalledWith(
-                        '<task>Text with @/some/path in task tags</task>',
-                        expect.any(String),
-                        expect.any(Object)
-                    );
-        
-                    // Feedback tag content should be processed
-                    const toolResult1 = processedContent[2] as Anthropic.ToolResultBlockParam;
-                    const content1 = Array.isArray(toolResult1.content) ? toolResult1.content[0] : toolResult1.content;
-                    expect((content1 as Anthropic.TextBlockParam).text).toContain('processed:');
-                    expect(mockParseMentions).toHaveBeenCalledWith(
-                        '<feedback>Check @/some/path</feedback>',
-                        expect.any(String),
-                        expect.any(Object)
-                    );
-        
-                    // Regular tool result should not be processed
-                    const toolResult2 = processedContent[3] as Anthropic.ToolResultBlockParam;
-                    const content2 = Array.isArray(toolResult2.content) ? toolResult2.content[0] : toolResult2.content;
-                    expect((content2 as Anthropic.TextBlockParam).text)
-                        .toBe('Regular tool result with @/path');
-                });
-            });
-        });
-    });
-});
+jest.mock("p-wait-for", () => ({
+	__esModule: true,
+	default: jest.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+jest.mock("delay", () => ({
+	__esModule: true,
+	default: jest.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+jest.mock("serialize-error", () => ({
+	__esModule: true,
+	serializeError: jest.fn().mockImplementation((error) => ({
+		name: error.name,
+		message: error.message,
+		stack: error.stack,
+	})),
+}))
+
+jest.mock("strip-ansi", () => ({
+	__esModule: true,
+	default: jest.fn().mockImplementation((str) => str.replace(/\u001B\[\d+m/g, "")),
+}))
+
+jest.mock("globby", () => ({
+	__esModule: true,
+	globby: jest.fn().mockImplementation(async () => []),
+}))
+
+jest.mock("os-name", () => ({
+	__esModule: true,
+	default: jest.fn().mockReturnValue("Mock OS Name"),
+}))
+
+jest.mock("default-shell", () => ({
+	__esModule: true,
+	default: "/bin/bash", // Mock default shell path
+}))
+
+describe("Cline", () => {
+	let mockProvider: jest.Mocked<ClineProvider>
+	let mockApiConfig: ApiConfiguration
+	let mockOutputChannel: any
+	let mockExtensionContext: vscode.ExtensionContext
+
+	beforeEach(() => {
+		// Setup mock extension context
+		mockExtensionContext = {
+			globalState: {
+				get: jest.fn().mockImplementation((key) => {
+					if (key === "taskHistory") {
+						return [
+							{
+								id: "123",
+								ts: Date.now(),
+								task: "historical task",
+								tokensIn: 100,
+								tokensOut: 200,
+								cacheWrites: 0,
+								cacheReads: 0,
+								totalCost: 0.001,
+							},
+						]
+					}
+					return undefined
+				}),
+				update: jest.fn().mockImplementation((key, value) => Promise.resolve()),
+				keys: jest.fn().mockReturnValue([]),
+			},
+			workspaceState: {
+				get: jest.fn().mockImplementation((key) => undefined),
+				update: jest.fn().mockImplementation((key, value) => Promise.resolve()),
+				keys: jest.fn().mockReturnValue([]),
+			},
+			secrets: {
+				get: jest.fn().mockImplementation((key) => Promise.resolve(undefined)),
+				store: jest.fn().mockImplementation((key, value) => Promise.resolve()),
+				delete: jest.fn().mockImplementation((key) => Promise.resolve()),
+			},
+			extensionUri: {
+				fsPath: "/mock/extension/path",
+			},
+			globalStorageUri: {
+				fsPath: "/mock/storage/path",
+			},
+			extension: {
+				packageJSON: {
+					version: "1.0.0",
+				},
+			},
+		} as unknown as vscode.ExtensionContext
+
+		// Setup mock output channel
+		mockOutputChannel = {
+			appendLine: jest.fn(),
+			append: jest.fn(),
+			clear: jest.fn(),
+			show: jest.fn(),
+			hide: jest.fn(),
+			dispose: jest.fn(),
+		}
+
+		// Setup mock provider with output channel
+		mockProvider = new ClineProvider(mockExtensionContext, mockOutputChannel) as jest.Mocked<ClineProvider>
+
+		// Setup mock API configuration
+		mockApiConfig = {
+			apiProvider: "anthropic",
+			apiModelId: "claude-3-5-sonnet-20241022",
+			apiKey: "test-api-key", // Add API key to mock config
+		}
+
+		// Mock provider methods
+		mockProvider.postMessageToWebview = jest.fn().mockResolvedValue(undefined)
+		mockProvider.postStateToWebview = jest.fn().mockResolvedValue(undefined)
+		mockProvider.getTaskWithId = jest.fn().mockImplementation(async (id) => ({
+			historyItem: {
+				id,
+				ts: Date.now(),
+				task: "historical task",
+				tokensIn: 100,
+				tokensOut: 200,
+				cacheWrites: 0,
+				cacheReads: 0,
+				totalCost: 0.001,
+			},
+			taskDirPath: "/mock/storage/path/tasks/123",
+			apiConversationHistoryFilePath: "/mock/storage/path/tasks/123/api_conversation_history.json",
+			uiMessagesFilePath: "/mock/storage/path/tasks/123/ui_messages.json",
+			apiConversationHistory: [],
+		}))
+	})
+
+	describe("constructor", () => {
+		it("should respect provided settings", () => {
+			const cline = new Cline(
+				mockProvider,
+				mockApiConfig,
+				"custom instructions",
+				false,
+				0.95, // 95% threshold
+				"test task",
+			)
+
+			expect(cline.customInstructions).toBe("custom instructions")
+			expect(cline.diffEnabled).toBe(false)
+		})
+
+		it("should use default fuzzy match threshold when not provided", () => {
+			const cline = new Cline(mockProvider, mockApiConfig, "custom instructions", true, undefined, "test task")
+
+			expect(cline.diffEnabled).toBe(true)
+			// The diff strategy should be created with default threshold (1.0)
+			expect(cline.diffStrategy).toBeDefined()
+		})
+
+		it("should use provided fuzzy match threshold", () => {
+			const getDiffStrategySpy = jest.spyOn(require("../diff/DiffStrategy"), "getDiffStrategy")
+
+			const cline = new Cline(
+				mockProvider,
+				mockApiConfig,
+				"custom instructions",
+				true,
+				0.9, // 90% threshold
+				"test task",
+			)
+
+			expect(cline.diffEnabled).toBe(true)
+			expect(cline.diffStrategy).toBeDefined()
+			expect(getDiffStrategySpy).toHaveBeenCalledWith("claude-3-5-sonnet-20241022", 0.9, false)
+
+			getDiffStrategySpy.mockRestore()
+		})
+
+		it("should pass default threshold to diff strategy when not provided", () => {
+			const getDiffStrategySpy = jest.spyOn(require("../diff/DiffStrategy"), "getDiffStrategy")
+
+			const cline = new Cline(mockProvider, mockApiConfig, "custom instructions", true, undefined, "test task")
+
+			expect(cline.diffEnabled).toBe(true)
+			expect(cline.diffStrategy).toBeDefined()
+			expect(getDiffStrategySpy).toHaveBeenCalledWith("claude-3-5-sonnet-20241022", 1.0, false)
+
+			getDiffStrategySpy.mockRestore()
+		})
+
+		it("should require either task or historyItem", () => {
+			expect(() => {
+				new Cline(
+					mockProvider,
+					mockApiConfig,
+					undefined, // customInstructions
+					false, // diffEnabled
+					undefined, // fuzzyMatchThreshold
+					undefined, // task
+				)
+			}).toThrow("Either historyItem or task/images must be provided")
+		})
+	})
+
+	describe("getEnvironmentDetails", () => {
+		let originalDate: DateConstructor
+		let mockDate: Date
+
+		beforeEach(() => {
+			originalDate = global.Date
+			const fixedTime = new Date("2024-01-01T12:00:00Z")
+			mockDate = new Date(fixedTime)
+			mockDate.getTimezoneOffset = jest.fn().mockReturnValue(420) // UTC-7
+
+			class MockDate extends Date {
+				constructor() {
+					super()
+					return mockDate
+				}
+				static override now() {
+					return mockDate.getTime()
+				}
+			}
+
+			global.Date = MockDate as DateConstructor
+
+			// Create a proper mock of Intl.DateTimeFormat
+			const mockDateTimeFormat = {
+				resolvedOptions: () => ({
+					timeZone: "America/Los_Angeles",
+				}),
+				format: () => "1/1/2024, 5:00:00 AM",
+			}
+
+			const MockDateTimeFormat = function (this: any) {
+				return mockDateTimeFormat
+			} as any
+
+			MockDateTimeFormat.prototype = mockDateTimeFormat
+			MockDateTimeFormat.supportedLocalesOf = jest.fn().mockReturnValue(["en-US"])
+
+			global.Intl.DateTimeFormat = MockDateTimeFormat
+		})
+
+		afterEach(() => {
+			global.Date = originalDate
+		})
+
+		it("should include timezone information in environment details", async () => {
+			const cline = new Cline(mockProvider, mockApiConfig, undefined, false, undefined, "test task")
+
+			const details = await cline["getEnvironmentDetails"](false)
+
+			// Verify timezone information is present and formatted correctly
+			expect(details).toContain("America/Los_Angeles")
+			expect(details).toMatch(/UTC-7:00/) // Fixed offset for America/Los_Angeles
+			expect(details).toContain("# Current Time")
+			expect(details).toMatch(/1\/1\/2024.*5:00:00 AM.*\(America\/Los_Angeles, UTC-7:00\)/) // Full time string format
+		})
+
+		describe("API conversation handling", () => {
+			it("should clean conversation history before sending to API", async () => {
+				const cline = new Cline(mockProvider, mockApiConfig, undefined, false, undefined, "test task")
+
+				// Mock the API's createMessage method to capture the conversation history
+				const createMessageSpy = jest.fn()
+				const mockStream = {
+					async *[Symbol.asyncIterator]() {
+						yield { type: "text", text: "" }
+					},
+					async next() {
+						return { done: true, value: undefined }
+					},
+					async return() {
+						return { done: true, value: undefined }
+					},
+					async throw(e: any) {
+						throw e
+					},
+					async [Symbol.asyncDispose]() {
+						// Cleanup
+					},
+				} as AsyncGenerator<ApiStreamChunk>
+
+				jest.spyOn(cline.api, "createMessage").mockImplementation((...args) => {
+					createMessageSpy(...args)
+					return mockStream
+				})
+
+				// Add a message with extra properties to the conversation history
+				const messageWithExtra = {
+					role: "user" as const,
+					content: [{ type: "text" as const, text: "test message" }],
+					ts: Date.now(),
+					extraProp: "should be removed",
+				}
+				cline.apiConversationHistory = [messageWithExtra]
+
+				// Trigger an API request
+				await cline.recursivelyMakeClineRequests([{ type: "text", text: "test request" }])
+
+				// Get all calls to createMessage
+				const calls = createMessageSpy.mock.calls
+
+				// Find the call that includes our test message
+				const relevantCall = calls.find((call) =>
+					call[1]?.some((msg: any) => msg.content?.[0]?.text === "test message"),
+				)
+
+				// Verify the conversation history was cleaned in the relevant call
+				expect(relevantCall?.[1]).toEqual(
+					expect.arrayContaining([
+						{
+							role: "user",
+							content: [{ type: "text", text: "test message" }],
+						},
+					]),
+				)
+
+				// Verify extra properties were removed
+				const passedMessage = relevantCall?.[1].find((msg: any) => msg.content?.[0]?.text === "test message")
+				expect(passedMessage).not.toHaveProperty("ts")
+				expect(passedMessage).not.toHaveProperty("extraProp")
+			})
+
+			it("should handle image blocks based on model capabilities", async () => {
+				// Create two configurations - one with image support, one without
+				const configWithImages = {
+					...mockApiConfig,
+					apiModelId: "claude-3-sonnet",
+				}
+				const configWithoutImages = {
+					...mockApiConfig,
+					apiModelId: "gpt-3.5-turbo",
+				}
+
+				// Create test conversation history with mixed content
+				const conversationHistory: (Anthropic.MessageParam & { ts?: number })[] = [
+					{
+						role: "user" as const,
+						content: [
+							{
+								type: "text" as const,
+								text: "Here is an image",
+							} satisfies Anthropic.TextBlockParam,
+							{
+								type: "image" as const,
+								source: {
+									type: "base64" as const,
+									media_type: "image/jpeg",
+									data: "base64data",
+								},
+							} satisfies Anthropic.ImageBlockParam,
+						],
+					},
+					{
+						role: "assistant" as const,
+						content: [
+							{
+								type: "text" as const,
+								text: "I see the image",
+							} satisfies Anthropic.TextBlockParam,
+						],
+					},
+				]
+
+				// Test with model that supports images
+				const clineWithImages = new Cline(
+					mockProvider,
+					configWithImages,
+					undefined,
+					false,
+					undefined,
+					"test task",
+				)
+				// Mock the model info to indicate image support
+				jest.spyOn(clineWithImages.api, "getModel").mockReturnValue({
+					id: "claude-3-sonnet",
+					info: {
+						supportsImages: true,
+						supportsPromptCache: true,
+						supportsComputerUse: true,
+						contextWindow: 200000,
+						maxTokens: 4096,
+						inputPrice: 0.25,
+						outputPrice: 0.75,
+					} as ModelInfo,
+				})
+				clineWithImages.apiConversationHistory = conversationHistory
+
+				// Test with model that doesn't support images
+				const clineWithoutImages = new Cline(
+					mockProvider,
+					configWithoutImages,
+					undefined,
+					false,
+					undefined,
+					"test task",
+				)
+				// Mock the model info to indicate no image support
+				jest.spyOn(clineWithoutImages.api, "getModel").mockReturnValue({
+					id: "gpt-3.5-turbo",
+					info: {
+						supportsImages: false,
+						supportsPromptCache: false,
+						supportsComputerUse: false,
+						contextWindow: 16000,
+						maxTokens: 2048,
+						inputPrice: 0.1,
+						outputPrice: 0.2,
+					} as ModelInfo,
+				})
+				clineWithoutImages.apiConversationHistory = conversationHistory
+
+				// Create message spy for both instances
+				const createMessageSpyWithImages = jest.fn()
+				const createMessageSpyWithoutImages = jest.fn()
+				const mockStream = {
+					async *[Symbol.asyncIterator]() {
+						yield { type: "text", text: "" }
+					},
+				} as AsyncGenerator<ApiStreamChunk>
+
+				jest.spyOn(clineWithImages.api, "createMessage").mockImplementation((...args) => {
+					createMessageSpyWithImages(...args)
+					return mockStream
+				})
+				jest.spyOn(clineWithoutImages.api, "createMessage").mockImplementation((...args) => {
+					createMessageSpyWithoutImages(...args)
+					return mockStream
+				})
+
+				// Trigger API requests for both instances
+				await clineWithImages.recursivelyMakeClineRequests([{ type: "text", text: "test" }])
+				await clineWithoutImages.recursivelyMakeClineRequests([{ type: "text", text: "test" }])
+
+				// Verify model with image support preserves image blocks
+				const callsWithImages = createMessageSpyWithImages.mock.calls
+				const historyWithImages = callsWithImages[0][1][0]
+				expect(historyWithImages.content).toHaveLength(2)
+				expect(historyWithImages.content[0]).toEqual({ type: "text", text: "Here is an image" })
+				expect(historyWithImages.content[1]).toHaveProperty("type", "image")
+
+				// Verify model without image support converts image blocks to text
+				const callsWithoutImages = createMessageSpyWithoutImages.mock.calls
+				const historyWithoutImages = callsWithoutImages[0][1][0]
+				expect(historyWithoutImages.content).toHaveLength(2)
+				expect(historyWithoutImages.content[0]).toEqual({ type: "text", text: "Here is an image" })
+				expect(historyWithoutImages.content[1]).toEqual({
+					type: "text",
+					text: "[Referenced image in conversation]",
+				})
+			})
+
+			it("should handle API retry with countdown", async () => {
+				const cline = new Cline(mockProvider, mockApiConfig, undefined, false, undefined, "test task")
+
+				// Mock delay to track countdown timing
+				const mockDelay = jest.fn().mockResolvedValue(undefined)
+				jest.spyOn(require("delay"), "default").mockImplementation(mockDelay)
+
+				// Mock say to track messages
+				const saySpy = jest.spyOn(cline, "say")
+
+				// Create a stream that fails on first chunk
+				const mockError = new Error("API Error")
+				const mockFailedStream = {
+					async *[Symbol.asyncIterator]() {
+						throw mockError
+					},
+					async next() {
+						throw mockError
+					},
+					async return() {
+						return { done: true, value: undefined }
+					},
+					async throw(e: any) {
+						throw e
+					},
+					async [Symbol.asyncDispose]() {
+						// Cleanup
+					},
+				} as AsyncGenerator<ApiStreamChunk>
+
+				// Create a successful stream for retry
+				const mockSuccessStream = {
+					async *[Symbol.asyncIterator]() {
+						yield { type: "text", text: "Success" }
+					},
+					async next() {
+						return { done: true, value: { type: "text", text: "Success" } }
+					},
+					async return() {
+						return { done: true, value: undefined }
+					},
+					async throw(e: any) {
+						throw e
+					},
+					async [Symbol.asyncDispose]() {
+						// Cleanup
+					},
+				} as AsyncGenerator<ApiStreamChunk>
+
+				// Mock createMessage to fail first then succeed
+				let firstAttempt = true
+				jest.spyOn(cline.api, "createMessage").mockImplementation(() => {
+					if (firstAttempt) {
+						firstAttempt = false
+						return mockFailedStream
+					}
+					return mockSuccessStream
+				})
+
+				// Set alwaysApproveResubmit and requestDelaySeconds
+				mockProvider.getState = jest.fn().mockResolvedValue({
+					alwaysApproveResubmit: true,
+					requestDelaySeconds: 3,
+				})
+
+				// Mock previous API request message
+				cline.clineMessages = [
+					{
+						ts: Date.now(),
+						type: "say",
+						say: "api_req_started",
+						text: JSON.stringify({
+							tokensIn: 100,
+							tokensOut: 50,
+							cacheWrites: 0,
+							cacheReads: 0,
+							request: "test request",
+						}),
+					},
+				]
+
+				// Trigger API request
+				const iterator = cline.attemptApiRequest(0)
+				await iterator.next()
+
+				// Verify countdown messages
+				expect(saySpy).toHaveBeenCalledWith(
+					"api_req_retry_delayed",
+					expect.stringContaining("Retrying in 3 seconds"),
+					undefined,
+					true,
+				)
+				expect(saySpy).toHaveBeenCalledWith(
+					"api_req_retry_delayed",
+					expect.stringContaining("Retrying in 2 seconds"),
+					undefined,
+					true,
+				)
+				expect(saySpy).toHaveBeenCalledWith(
+					"api_req_retry_delayed",
+					expect.stringContaining("Retrying in 1 seconds"),
+					undefined,
+					true,
+				)
+				expect(saySpy).toHaveBeenCalledWith(
+					"api_req_retry_delayed",
+					expect.stringContaining("Retrying now"),
+					undefined,
+					false,
+				)
+
+				// Verify delay was called correctly
+				expect(mockDelay).toHaveBeenCalledTimes(3)
+				expect(mockDelay).toHaveBeenCalledWith(1000)
+
+				// Verify error message content
+				const errorMessage = saySpy.mock.calls.find((call) => call[1]?.includes(mockError.message))?.[1]
+				expect(errorMessage).toBe(`${mockError.message}\n\nRetrying in 3 seconds...`)
+			})
+
+			describe("loadContext", () => {
+				it("should process mentions in task and feedback tags", async () => {
+					const cline = new Cline(mockProvider, mockApiConfig, undefined, false, undefined, "test task")
+
+					// Mock parseMentions to track calls
+					const mockParseMentions = jest.fn().mockImplementation((text) => `processed: ${text}`)
+					jest.spyOn(require("../../core/mentions"), "parseMentions").mockImplementation(mockParseMentions)
+
+					const userContent = [
+						{
+							type: "text",
+							text: "Regular text with @/some/path",
+						} as const,
+						{
+							type: "text",
+							text: "<task>Text with @/some/path in task tags</task>",
+						} as const,
+						{
+							type: "tool_result",
+							tool_use_id: "test-id",
+							content: [
+								{
+									type: "text",
+									text: "<feedback>Check @/some/path</feedback>",
+								},
+							],
+						} as Anthropic.ToolResultBlockParam,
+						{
+							type: "tool_result",
+							tool_use_id: "test-id-2",
+							content: [
+								{
+									type: "text",
+									text: "Regular tool result with @/path",
+								},
+							],
+						} as Anthropic.ToolResultBlockParam,
+					]
+
+					// Process the content
+					const [processedContent] = await cline["loadContext"](userContent)
+
+					// Regular text should not be processed
+					expect((processedContent[0] as Anthropic.TextBlockParam).text).toBe("Regular text with @/some/path")
+
+					// Text within task tags should be processed
+					expect((processedContent[1] as Anthropic.TextBlockParam).text).toContain("processed:")
+					expect(mockParseMentions).toHaveBeenCalledWith(
+						"<task>Text with @/some/path in task tags</task>",
+						expect.any(String),
+						expect.any(Object),
+					)
+
+					// Feedback tag content should be processed
+					const toolResult1 = processedContent[2] as Anthropic.ToolResultBlockParam
+					const content1 = Array.isArray(toolResult1.content) ? toolResult1.content[0] : toolResult1.content
+					expect((content1 as Anthropic.TextBlockParam).text).toContain("processed:")
+					expect(mockParseMentions).toHaveBeenCalledWith(
+						"<feedback>Check @/some/path</feedback>",
+						expect.any(String),
+						expect.any(Object),
+					)
+
+					// Regular tool result should not be processed
+					const toolResult2 = processedContent[3] as Anthropic.ToolResultBlockParam
+					const content2 = Array.isArray(toolResult2.content) ? toolResult2.content[0] : toolResult2.content
+					expect((content2 as Anthropic.TextBlockParam).text).toBe("Regular tool result with @/path")
+				})
+			})
+		})
+	})
+})

+ 45 - 45
src/core/__tests__/mode-validator.test.ts

@@ -1,52 +1,52 @@
-import { Mode, isToolAllowedForMode, TestToolName, getModeConfig, modes } from '../../shared/modes';
-import { validateToolUse } from '../mode-validator';
+import { Mode, isToolAllowedForMode, TestToolName, getModeConfig, modes } from "../../shared/modes"
+import { validateToolUse } from "../mode-validator"
 
-const asTestTool = (tool: string): TestToolName => tool as TestToolName;
-const [codeMode, architectMode, askMode] = modes.map(mode => mode.slug);
+const asTestTool = (tool: string): TestToolName => tool as TestToolName
+const [codeMode, architectMode, askMode] = modes.map((mode) => mode.slug)
 
-describe('mode-validator', () => {
-    describe('isToolAllowedForMode', () => {
-        describe('code mode', () => {
-            it('allows all code mode tools', () => {
-                const mode = getModeConfig(codeMode);
-                mode.tools.forEach(([tool]) => {
-                    expect(isToolAllowedForMode(tool, codeMode)).toBe(true)
-                })
-            })
+describe("mode-validator", () => {
+	describe("isToolAllowedForMode", () => {
+		describe("code mode", () => {
+			it("allows all code mode tools", () => {
+				const mode = getModeConfig(codeMode)
+				mode.tools.forEach(([tool]) => {
+					expect(isToolAllowedForMode(tool, codeMode)).toBe(true)
+				})
+			})
 
-            it('disallows unknown tools', () => {
-                expect(isToolAllowedForMode(asTestTool('unknown_tool'), codeMode)).toBe(false)
-            })
-        })
+			it("disallows unknown tools", () => {
+				expect(isToolAllowedForMode(asTestTool("unknown_tool"), codeMode)).toBe(false)
+			})
+		})
 
-        describe('architect mode', () => {
-            it('allows configured tools', () => {
-                const mode = getModeConfig(architectMode);
-                mode.tools.forEach(([tool]) => {
-                    expect(isToolAllowedForMode(tool, architectMode)).toBe(true)
-                })
-            })
-        })
+		describe("architect mode", () => {
+			it("allows configured tools", () => {
+				const mode = getModeConfig(architectMode)
+				mode.tools.forEach(([tool]) => {
+					expect(isToolAllowedForMode(tool, architectMode)).toBe(true)
+				})
+			})
+		})
 
-        describe('ask mode', () => {
-            it('allows configured tools', () => {
-                const mode = getModeConfig(askMode);
-                mode.tools.forEach(([tool]) => {
-                    expect(isToolAllowedForMode(tool, askMode)).toBe(true)
-                })
-            })
-        })
-    })
+		describe("ask mode", () => {
+			it("allows configured tools", () => {
+				const mode = getModeConfig(askMode)
+				mode.tools.forEach(([tool]) => {
+					expect(isToolAllowedForMode(tool, askMode)).toBe(true)
+				})
+			})
+		})
+	})
 
-    describe('validateToolUse', () => {
-        it('throws error for disallowed tools in architect mode', () => {
-            expect(() => validateToolUse('unknown_tool', 'architect')).toThrow(
-                'Tool "unknown_tool" is not allowed in architect mode.'
-            )
-        })
+	describe("validateToolUse", () => {
+		it("throws error for disallowed tools in architect mode", () => {
+			expect(() => validateToolUse("unknown_tool", "architect")).toThrow(
+				'Tool "unknown_tool" is not allowed in architect mode.',
+			)
+		})
 
-        it('does not throw for allowed tools in architect mode', () => {
-            expect(() => validateToolUse('read_file', 'architect')).not.toThrow()
-        })
-    })
-})
+		it("does not throw for allowed tools in architect mode", () => {
+			expect(() => validateToolUse("read_file", "architect")).not.toThrow()
+		})
+	})
+})

+ 216 - 216
src/core/config/ConfigManager.ts

@@ -1,221 +1,221 @@
-import { ExtensionContext } from 'vscode'
-import { ApiConfiguration } from '../../shared/api'
-import { Mode } from '../prompts/types'
-import { ApiConfigMeta } from '../../shared/ExtensionMessage'
+import { ExtensionContext } from "vscode"
+import { ApiConfiguration } from "../../shared/api"
+import { Mode } from "../prompts/types"
+import { ApiConfigMeta } from "../../shared/ExtensionMessage"
 
 export interface ApiConfigData {
-  currentApiConfigName: string
-  apiConfigs: {
-    [key: string]: ApiConfiguration
-  }
-  modeApiConfigs?: Partial<Record<Mode, string>>
+	currentApiConfigName: string
+	apiConfigs: {
+		[key: string]: ApiConfiguration
+	}
+	modeApiConfigs?: Partial<Record<Mode, string>>
 }
 
 export class ConfigManager {
-  private readonly defaultConfig: ApiConfigData = {
-    currentApiConfigName: 'default',
-    apiConfigs: {
-      default: {
-        id: this.generateId()
-      }
-    }
-  }
-
-  private readonly SCOPE_PREFIX = "roo_cline_config_"
-  private readonly context: ExtensionContext
-
-  constructor(context: ExtensionContext) {
-    this.context = context
-    this.initConfig().catch(console.error)
-  }
-
-  private generateId(): string {
-    return Math.random().toString(36).substring(2, 15)
-  }
-
-  /**
-   * Initialize config if it doesn't exist
-   */
-  async initConfig(): Promise<void> {
-    try {
-      const config = await this.readConfig()
-      if (!config) {
-        await this.writeConfig(this.defaultConfig)
-        return
-      }
-
-      // Migrate: ensure all configs have IDs
-      let needsMigration = false
-      for (const [name, apiConfig] of Object.entries(config.apiConfigs)) {
-        if (!apiConfig.id) {
-          apiConfig.id = this.generateId()
-          needsMigration = true
-        }
-      }
-
-      if (needsMigration) {
-        await this.writeConfig(config)
-      }
-    } catch (error) {
-      throw new Error(`Failed to initialize config: ${error}`)
-    }
-  }
-
-  /**
-   * List all available configs with metadata
-   */
-  async ListConfig(): Promise<ApiConfigMeta[]> {
-    try {
-      const config = await this.readConfig()
-      return Object.entries(config.apiConfigs).map(([name, apiConfig]) => ({
-        name,
-        id: apiConfig.id || '',
-        apiProvider: apiConfig.apiProvider,
-      }))
-    } catch (error) {
-      throw new Error(`Failed to list configs: ${error}`)
-    }
-  }
-
-  /**
-   * Save a config with the given name
-   */
-  async SaveConfig(name: string, config: ApiConfiguration): Promise<void> {
-    try {
-      const currentConfig = await this.readConfig()
-      const existingConfig = currentConfig.apiConfigs[name]
-      currentConfig.apiConfigs[name] = {
-        ...config,
-        id: existingConfig?.id || this.generateId()
-      }
-      await this.writeConfig(currentConfig)
-    } catch (error) {
-      throw new Error(`Failed to save config: ${error}`)
-    }
-  }
-
-  /**
-   * Load a config by name
-   */
-  async LoadConfig(name: string): Promise<ApiConfiguration> {
-    try {
-      const config = await this.readConfig()
-      const apiConfig = config.apiConfigs[name]
-      
-      if (!apiConfig) {
-        throw new Error(`Config '${name}' not found`)
-      }
-      
-      config.currentApiConfigName = name;
-      await this.writeConfig(config)
-      
-      return apiConfig
-    } catch (error) {
-      throw new Error(`Failed to load config: ${error}`)
-    }
-  }
-
-  /**
-   * Delete a config by name
-   */
-  async DeleteConfig(name: string): Promise<void> {
-    try {
-      const currentConfig = await this.readConfig()
-      if (!currentConfig.apiConfigs[name]) {
-        throw new Error(`Config '${name}' not found`)
-      }
-
-      // Don't allow deleting the default config
-      if (Object.keys(currentConfig.apiConfigs).length === 1) {
-        throw new Error(`Cannot delete the last remaining configuration.`)
-      }
-
-      delete currentConfig.apiConfigs[name]
-      await this.writeConfig(currentConfig)
-    } catch (error) {
-      throw new Error(`Failed to delete config: ${error}`)
-    }
-  }
-
-  /**
-   * Set the current active API configuration
-   */
-  async SetCurrentConfig(name: string): Promise<void> {
-    try {
-      const currentConfig = await this.readConfig()
-      if (!currentConfig.apiConfigs[name]) {
-        throw new Error(`Config '${name}' not found`)
-      }
-
-      currentConfig.currentApiConfigName = name
-      await this.writeConfig(currentConfig)
-    } catch (error) {
-      throw new Error(`Failed to set current config: ${error}`)
-    }
-  }
-
-  /**
-   * Check if a config exists by name
-   */
-  async HasConfig(name: string): Promise<boolean> {
-    try {
-      const config = await this.readConfig()
-      return name in config.apiConfigs
-    } catch (error) {
-      throw new Error(`Failed to check config existence: ${error}`)
-    }
-  }
-
-  /**
-   * Set the API config for a specific mode
-   */
-  async SetModeConfig(mode: Mode, configId: string): Promise<void> {
-    try {
-      const currentConfig = await this.readConfig()
-      if (!currentConfig.modeApiConfigs) {
-        currentConfig.modeApiConfigs = {}
-      }
-      currentConfig.modeApiConfigs[mode] = configId
-      await this.writeConfig(currentConfig)
-    } catch (error) {
-      throw new Error(`Failed to set mode config: ${error}`)
-    }
-  }
-
-  /**
-   * Get the API config ID for a specific mode
-   */
-  async GetModeConfigId(mode: Mode): Promise<string | undefined> {
-    try {
-      const config = await this.readConfig()
-      return config.modeApiConfigs?.[mode]
-    } catch (error) {
-      throw new Error(`Failed to get mode config: ${error}`)
-    }
-  }
-
-  private async readConfig(): Promise<ApiConfigData> {
-    try {
-      const configKey = `${this.SCOPE_PREFIX}api_config`
-      const content = await this.context.secrets.get(configKey)
-      
-      if (!content) {
-        return this.defaultConfig
-      }
-
-      return JSON.parse(content)
-    } catch (error) {
-      throw new Error(`Failed to read config from secrets: ${error}`)
-    }
-  }
-
-  private async writeConfig(config: ApiConfigData): Promise<void> {
-    try {
-      const configKey = `${this.SCOPE_PREFIX}api_config`
-      const content = JSON.stringify(config, null, 2)
-      await this.context.secrets.store(configKey, content)
-    } catch (error) {
-      throw new Error(`Failed to write config to secrets: ${error}`)
-    }
-  }
-}
+	private readonly defaultConfig: ApiConfigData = {
+		currentApiConfigName: "default",
+		apiConfigs: {
+			default: {
+				id: this.generateId(),
+			},
+		},
+	}
+
+	private readonly SCOPE_PREFIX = "roo_cline_config_"
+	private readonly context: ExtensionContext
+
+	constructor(context: ExtensionContext) {
+		this.context = context
+		this.initConfig().catch(console.error)
+	}
+
+	private generateId(): string {
+		return Math.random().toString(36).substring(2, 15)
+	}
+
+	/**
+	 * Initialize config if it doesn't exist
+	 */
+	async initConfig(): Promise<void> {
+		try {
+			const config = await this.readConfig()
+			if (!config) {
+				await this.writeConfig(this.defaultConfig)
+				return
+			}
+
+			// Migrate: ensure all configs have IDs
+			let needsMigration = false
+			for (const [name, apiConfig] of Object.entries(config.apiConfigs)) {
+				if (!apiConfig.id) {
+					apiConfig.id = this.generateId()
+					needsMigration = true
+				}
+			}
+
+			if (needsMigration) {
+				await this.writeConfig(config)
+			}
+		} catch (error) {
+			throw new Error(`Failed to initialize config: ${error}`)
+		}
+	}
+
+	/**
+	 * List all available configs with metadata
+	 */
+	async ListConfig(): Promise<ApiConfigMeta[]> {
+		try {
+			const config = await this.readConfig()
+			return Object.entries(config.apiConfigs).map(([name, apiConfig]) => ({
+				name,
+				id: apiConfig.id || "",
+				apiProvider: apiConfig.apiProvider,
+			}))
+		} catch (error) {
+			throw new Error(`Failed to list configs: ${error}`)
+		}
+	}
+
+	/**
+	 * Save a config with the given name
+	 */
+	async SaveConfig(name: string, config: ApiConfiguration): Promise<void> {
+		try {
+			const currentConfig = await this.readConfig()
+			const existingConfig = currentConfig.apiConfigs[name]
+			currentConfig.apiConfigs[name] = {
+				...config,
+				id: existingConfig?.id || this.generateId(),
+			}
+			await this.writeConfig(currentConfig)
+		} catch (error) {
+			throw new Error(`Failed to save config: ${error}`)
+		}
+	}
+
+	/**
+	 * Load a config by name
+	 */
+	async LoadConfig(name: string): Promise<ApiConfiguration> {
+		try {
+			const config = await this.readConfig()
+			const apiConfig = config.apiConfigs[name]
+
+			if (!apiConfig) {
+				throw new Error(`Config '${name}' not found`)
+			}
+
+			config.currentApiConfigName = name
+			await this.writeConfig(config)
+
+			return apiConfig
+		} catch (error) {
+			throw new Error(`Failed to load config: ${error}`)
+		}
+	}
+
+	/**
+	 * Delete a config by name
+	 */
+	async DeleteConfig(name: string): Promise<void> {
+		try {
+			const currentConfig = await this.readConfig()
+			if (!currentConfig.apiConfigs[name]) {
+				throw new Error(`Config '${name}' not found`)
+			}
+
+			// Don't allow deleting the default config
+			if (Object.keys(currentConfig.apiConfigs).length === 1) {
+				throw new Error(`Cannot delete the last remaining configuration.`)
+			}
+
+			delete currentConfig.apiConfigs[name]
+			await this.writeConfig(currentConfig)
+		} catch (error) {
+			throw new Error(`Failed to delete config: ${error}`)
+		}
+	}
+
+	/**
+	 * Set the current active API configuration
+	 */
+	async SetCurrentConfig(name: string): Promise<void> {
+		try {
+			const currentConfig = await this.readConfig()
+			if (!currentConfig.apiConfigs[name]) {
+				throw new Error(`Config '${name}' not found`)
+			}
+
+			currentConfig.currentApiConfigName = name
+			await this.writeConfig(currentConfig)
+		} catch (error) {
+			throw new Error(`Failed to set current config: ${error}`)
+		}
+	}
+
+	/**
+	 * Check if a config exists by name
+	 */
+	async HasConfig(name: string): Promise<boolean> {
+		try {
+			const config = await this.readConfig()
+			return name in config.apiConfigs
+		} catch (error) {
+			throw new Error(`Failed to check config existence: ${error}`)
+		}
+	}
+
+	/**
+	 * Set the API config for a specific mode
+	 */
+	async SetModeConfig(mode: Mode, configId: string): Promise<void> {
+		try {
+			const currentConfig = await this.readConfig()
+			if (!currentConfig.modeApiConfigs) {
+				currentConfig.modeApiConfigs = {}
+			}
+			currentConfig.modeApiConfigs[mode] = configId
+			await this.writeConfig(currentConfig)
+		} catch (error) {
+			throw new Error(`Failed to set mode config: ${error}`)
+		}
+	}
+
+	/**
+	 * Get the API config ID for a specific mode
+	 */
+	async GetModeConfigId(mode: Mode): Promise<string | undefined> {
+		try {
+			const config = await this.readConfig()
+			return config.modeApiConfigs?.[mode]
+		} catch (error) {
+			throw new Error(`Failed to get mode config: ${error}`)
+		}
+	}
+
+	private async readConfig(): Promise<ApiConfigData> {
+		try {
+			const configKey = `${this.SCOPE_PREFIX}api_config`
+			const content = await this.context.secrets.get(configKey)
+
+			if (!content) {
+				return this.defaultConfig
+			}
+
+			return JSON.parse(content)
+		} catch (error) {
+			throw new Error(`Failed to read config from secrets: ${error}`)
+		}
+	}
+
+	private async writeConfig(config: ApiConfigData): Promise<void> {
+		try {
+			const configKey = `${this.SCOPE_PREFIX}api_config`
+			const content = JSON.stringify(config, null, 2)
+			await this.context.secrets.store(configKey, content)
+		} catch (error) {
+			throw new Error(`Failed to write config to secrets: ${error}`)
+		}
+	}
+}

+ 462 - 444
src/core/config/__tests__/ConfigManager.test.ts

@@ -1,452 +1,470 @@
-import { ExtensionContext } from 'vscode'
-import { ConfigManager, ApiConfigData } from '../ConfigManager'
-import { ApiConfiguration } from '../../../shared/api'
+import { ExtensionContext } from "vscode"
+import { ConfigManager, ApiConfigData } from "../ConfigManager"
+import { ApiConfiguration } from "../../../shared/api"
 
 // Mock VSCode ExtensionContext
 const mockSecrets = {
-  get: jest.fn(),
-  store: jest.fn(),
-  delete: jest.fn()
+	get: jest.fn(),
+	store: jest.fn(),
+	delete: jest.fn(),
 }
 
 const mockContext = {
-  secrets: mockSecrets
+	secrets: mockSecrets,
 } as unknown as ExtensionContext
 
-describe('ConfigManager', () => {
-  let configManager: ConfigManager
-
-  beforeEach(() => {
-    jest.clearAllMocks()
-    configManager = new ConfigManager(mockContext)
-  })
-
-  describe('initConfig', () => {
-    it('should not write to storage when secrets.get returns null', async () => {
-      // Mock readConfig to return null
-      mockSecrets.get.mockResolvedValueOnce(null)
-
-      await configManager.initConfig()
-
-      // Should not write to storage because readConfig returns defaultConfig
-      expect(mockSecrets.store).not.toHaveBeenCalled()
-    })
-
-    it('should not initialize config if it exists', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            config: {},
-            id: 'default'
-          }
-        }
-      }))
-
-      await configManager.initConfig()
-
-      expect(mockSecrets.store).not.toHaveBeenCalled()
-    })
-
-    it('should generate IDs for configs that lack them', async () => {
-      // Mock a config with missing IDs
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            config: {}
-          },
-          test: {
-            apiProvider: 'anthropic'
-          }
-        }
-      }))
-
-      await configManager.initConfig()
-
-      // Should have written the config with new IDs
-      expect(mockSecrets.store).toHaveBeenCalled()
-      const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
-      expect(storedConfig.apiConfigs.default.id).toBeTruthy()
-      expect(storedConfig.apiConfigs.test.id).toBeTruthy()
-    })
-
-    it('should throw error if secrets storage fails', async () => {
-      mockSecrets.get.mockRejectedValue(new Error('Storage failed'))
-
-      await expect(configManager.initConfig()).rejects.toThrow(
-        'Failed to initialize config: Error: Failed to read config from secrets: Error: Storage failed'
-      )
-    })
-  })
-
-  describe('ListConfig', () => {
-    it('should list all available configs', async () => {
-      const existingConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            id: 'default'
-          },
-          test: {
-            apiProvider: 'anthropic',
-            id: 'test-id'
-          }
-        },
-        modeApiConfigs: {
-          code: 'default',
-          architect: 'default',
-          ask: 'default'
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
-
-      const configs = await configManager.ListConfig()
-      expect(configs).toEqual([
-        { name: 'default', id: 'default', apiProvider: undefined },
-        { name: 'test', id: 'test-id', apiProvider: 'anthropic' }
-      ])
-    })
-
-    it('should handle empty config file', async () => {
-      const emptyConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {},
-        modeApiConfigs: {
-          code: 'default',
-          architect: 'default',
-          ask: 'default'
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(emptyConfig))
-
-      const configs = await configManager.ListConfig()
-      expect(configs).toEqual([])
-    })
-
-    it('should throw error if reading from secrets fails', async () => {
-      mockSecrets.get.mockRejectedValue(new Error('Read failed'))
-
-      await expect(configManager.ListConfig()).rejects.toThrow(
-        'Failed to list configs: Error: Failed to read config from secrets: Error: Read failed'
-      )
-    })
-  })
-
-  describe('SaveConfig', () => {
-    it('should save new config', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {}
-        },
-        modeApiConfigs: {
-          code: 'default',
-          architect: 'default',
-          ask: 'default'
-        }
-      }))
-
-      const newConfig: ApiConfiguration = {
-        apiProvider: 'anthropic',
-        apiKey: 'test-key'
-      }
-
-      await configManager.SaveConfig('test', newConfig)
-
-      // Get the actual stored config to check the generated ID
-      const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
-      const testConfigId = storedConfig.apiConfigs.test.id
-
-      const expectedConfig = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {},
-          test: {
-            ...newConfig,
-            id: testConfigId
-          }
-        },
-        modeApiConfigs: {
-          code: 'default',
-          architect: 'default',
-          ask: 'default'
-        }
-      }
-
-      expect(mockSecrets.store).toHaveBeenCalledWith(
-        'roo_cline_config_api_config',
-        JSON.stringify(expectedConfig, null, 2)
-      )
-    })
-
-    it('should update existing config', async () => {
-      const existingConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          test: {
-            apiProvider: 'anthropic',
-            apiKey: 'old-key',
-            id: 'test-id'
-          }
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
-
-      const updatedConfig: ApiConfiguration = {
-        apiProvider: 'anthropic',
-        apiKey: 'new-key'
-      }
-
-      await configManager.SaveConfig('test', updatedConfig)
-
-      const expectedConfig = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          test: {
-            apiProvider: 'anthropic',
-            apiKey: 'new-key',
-            id: 'test-id'
-          }
-        }
-      }
-
-      expect(mockSecrets.store).toHaveBeenCalledWith(
-        'roo_cline_config_api_config',
-        JSON.stringify(expectedConfig, null, 2)
-      )
-    })
-
-    it('should throw error if secrets storage fails', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: { default: {} }
-      }))
-      mockSecrets.store.mockRejectedValueOnce(new Error('Storage failed'))
-
-      await expect(configManager.SaveConfig('test', {})).rejects.toThrow(
-        'Failed to save config: Error: Failed to write config to secrets: Error: Storage failed'
-      )
-    })
-  })
-
-  describe('DeleteConfig', () => {
-    it('should delete existing config', async () => {
-      const existingConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            id: 'default'
-          },
-          test: {
-            apiProvider: 'anthropic',
-            id: 'test-id'
-          }
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
-
-      await configManager.DeleteConfig('test')
-
-      // Get the stored config to check the ID
-      const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
-      expect(storedConfig.currentApiConfigName).toBe('default')
-      expect(Object.keys(storedConfig.apiConfigs)).toEqual(['default'])
-      expect(storedConfig.apiConfigs.default.id).toBeTruthy()
-    })
-
-    it('should throw error when trying to delete non-existent config', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: { default: {} }
-      }))
-
-      await expect(configManager.DeleteConfig('nonexistent')).rejects.toThrow(
-        "Config 'nonexistent' not found"
-      )
-    })
-
-    it('should throw error when trying to delete last remaining config', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            id: 'default'
-          }
-        }
-      }))
-
-      await expect(configManager.DeleteConfig('default')).rejects.toThrow(
-        'Cannot delete the last remaining configuration.'
-      )
-    })
-  })
-
-  describe('LoadConfig', () => {
-    it('should load config and update current config name', async () => {
-      const existingConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          test: {
-            apiProvider: 'anthropic',
-            apiKey: 'test-key',
-            id: 'test-id'
-          }
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
-
-      const config = await configManager.LoadConfig('test')
-
-      expect(config).toEqual({
-        apiProvider: 'anthropic',
-        apiKey: 'test-key',
-        id: 'test-id'
-      })
-
-      // Get the stored config to check the structure
-      const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
-      expect(storedConfig.currentApiConfigName).toBe('test')
-      expect(storedConfig.apiConfigs.test).toEqual({
-        apiProvider: 'anthropic',
-        apiKey: 'test-key',
-        id: 'test-id'
-      })
-    })
-
-    it('should throw error when config does not exist', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            config: {},
-            id: 'default'
-          }
-        }
-      }))
-
-      await expect(configManager.LoadConfig('nonexistent')).rejects.toThrow(
-        "Config 'nonexistent' not found"
-      )
-    })
-
-    it('should throw error if secrets storage fails', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          test: {
-            config: {
-              apiProvider: 'anthropic'
-            },
-            id: 'test-id'
-          }
-        }
-      }))
-      mockSecrets.store.mockRejectedValueOnce(new Error('Storage failed'))
-
-      await expect(configManager.LoadConfig('test')).rejects.toThrow(
-        'Failed to load config: Error: Failed to write config to secrets: Error: Storage failed'
-      )
-    })
-  })
-
-  describe('SetCurrentConfig', () => {
-    it('should set current config', async () => {
-      const existingConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            id: 'default'
-          },
-          test: {
-            apiProvider: 'anthropic',
-            id: 'test-id'
-          }
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
-
-      await configManager.SetCurrentConfig('test')
-
-      // Get the stored config to check the structure
-      const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
-      expect(storedConfig.currentApiConfigName).toBe('test')
-      expect(storedConfig.apiConfigs.default.id).toBe('default')
-      expect(storedConfig.apiConfigs.test).toEqual({
-        apiProvider: 'anthropic',
-        id: 'test-id'
-      })
-    })
-
-    it('should throw error when config does not exist', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: { default: {} }
-      }))
-
-      await expect(configManager.SetCurrentConfig('nonexistent')).rejects.toThrow(
-        "Config 'nonexistent' not found"
-      )
-    })
-
-    it('should throw error if secrets storage fails', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          test: { apiProvider: 'anthropic' }
-        }
-      }))
-      mockSecrets.store.mockRejectedValueOnce(new Error('Storage failed'))
-
-      await expect(configManager.SetCurrentConfig('test')).rejects.toThrow(
-        'Failed to set current config: Error: Failed to write config to secrets: Error: Storage failed'
-      )
-    })
-  })
-
-  describe('HasConfig', () => {
-    it('should return true for existing config', async () => {
-      const existingConfig: ApiConfigData = {
-        currentApiConfigName: 'default',
-        apiConfigs: {
-          default: {
-            id: 'default'
-          },
-          test: {
-            apiProvider: 'anthropic',
-            id: 'test-id'
-          }
-        }
-      }
-
-      mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
-
-      const hasConfig = await configManager.HasConfig('test')
-      expect(hasConfig).toBe(true)
-    })
-
-    it('should return false for non-existent config', async () => {
-      mockSecrets.get.mockResolvedValue(JSON.stringify({
-        currentApiConfigName: 'default',
-        apiConfigs: { default: {} }
-      }))
-
-      const hasConfig = await configManager.HasConfig('nonexistent')
-      expect(hasConfig).toBe(false)
-    })
-
-    it('should throw error if secrets storage fails', async () => {
-      mockSecrets.get.mockRejectedValue(new Error('Storage failed'))
-
-      await expect(configManager.HasConfig('test')).rejects.toThrow(
-        'Failed to check config existence: Error: Failed to read config from secrets: Error: Storage failed'
-      )
-    })
-  })
-})
+describe("ConfigManager", () => {
+	let configManager: ConfigManager
+
+	beforeEach(() => {
+		jest.clearAllMocks()
+		configManager = new ConfigManager(mockContext)
+	})
+
+	describe("initConfig", () => {
+		it("should not write to storage when secrets.get returns null", async () => {
+			// Mock readConfig to return null
+			mockSecrets.get.mockResolvedValueOnce(null)
+
+			await configManager.initConfig()
+
+			// Should not write to storage because readConfig returns defaultConfig
+			expect(mockSecrets.store).not.toHaveBeenCalled()
+		})
+
+		it("should not initialize config if it exists", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						default: {
+							config: {},
+							id: "default",
+						},
+					},
+				}),
+			)
+
+			await configManager.initConfig()
+
+			expect(mockSecrets.store).not.toHaveBeenCalled()
+		})
+
+		it("should generate IDs for configs that lack them", async () => {
+			// Mock a config with missing IDs
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						default: {
+							config: {},
+						},
+						test: {
+							apiProvider: "anthropic",
+						},
+					},
+				}),
+			)
+
+			await configManager.initConfig()
+
+			// Should have written the config with new IDs
+			expect(mockSecrets.store).toHaveBeenCalled()
+			const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
+			expect(storedConfig.apiConfigs.default.id).toBeTruthy()
+			expect(storedConfig.apiConfigs.test.id).toBeTruthy()
+		})
+
+		it("should throw error if secrets storage fails", async () => {
+			mockSecrets.get.mockRejectedValue(new Error("Storage failed"))
+
+			await expect(configManager.initConfig()).rejects.toThrow(
+				"Failed to initialize config: Error: Failed to read config from secrets: Error: Storage failed",
+			)
+		})
+	})
+
+	describe("ListConfig", () => {
+		it("should list all available configs", async () => {
+			const existingConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					default: {
+						id: "default",
+					},
+					test: {
+						apiProvider: "anthropic",
+						id: "test-id",
+					},
+				},
+				modeApiConfigs: {
+					code: "default",
+					architect: "default",
+					ask: "default",
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
+
+			const configs = await configManager.ListConfig()
+			expect(configs).toEqual([
+				{ name: "default", id: "default", apiProvider: undefined },
+				{ name: "test", id: "test-id", apiProvider: "anthropic" },
+			])
+		})
+
+		it("should handle empty config file", async () => {
+			const emptyConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {},
+				modeApiConfigs: {
+					code: "default",
+					architect: "default",
+					ask: "default",
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(emptyConfig))
+
+			const configs = await configManager.ListConfig()
+			expect(configs).toEqual([])
+		})
+
+		it("should throw error if reading from secrets fails", async () => {
+			mockSecrets.get.mockRejectedValue(new Error("Read failed"))
+
+			await expect(configManager.ListConfig()).rejects.toThrow(
+				"Failed to list configs: Error: Failed to read config from secrets: Error: Read failed",
+			)
+		})
+	})
+
+	describe("SaveConfig", () => {
+		it("should save new config", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						default: {},
+					},
+					modeApiConfigs: {
+						code: "default",
+						architect: "default",
+						ask: "default",
+					},
+				}),
+			)
+
+			const newConfig: ApiConfiguration = {
+				apiProvider: "anthropic",
+				apiKey: "test-key",
+			}
+
+			await configManager.SaveConfig("test", newConfig)
+
+			// Get the actual stored config to check the generated ID
+			const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
+			const testConfigId = storedConfig.apiConfigs.test.id
+
+			const expectedConfig = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					default: {},
+					test: {
+						...newConfig,
+						id: testConfigId,
+					},
+				},
+				modeApiConfigs: {
+					code: "default",
+					architect: "default",
+					ask: "default",
+				},
+			}
+
+			expect(mockSecrets.store).toHaveBeenCalledWith(
+				"roo_cline_config_api_config",
+				JSON.stringify(expectedConfig, null, 2),
+			)
+		})
+
+		it("should update existing config", async () => {
+			const existingConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					test: {
+						apiProvider: "anthropic",
+						apiKey: "old-key",
+						id: "test-id",
+					},
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
+
+			const updatedConfig: ApiConfiguration = {
+				apiProvider: "anthropic",
+				apiKey: "new-key",
+			}
+
+			await configManager.SaveConfig("test", updatedConfig)
+
+			const expectedConfig = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					test: {
+						apiProvider: "anthropic",
+						apiKey: "new-key",
+						id: "test-id",
+					},
+				},
+			}
+
+			expect(mockSecrets.store).toHaveBeenCalledWith(
+				"roo_cline_config_api_config",
+				JSON.stringify(expectedConfig, null, 2),
+			)
+		})
+
+		it("should throw error if secrets storage fails", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: { default: {} },
+				}),
+			)
+			mockSecrets.store.mockRejectedValueOnce(new Error("Storage failed"))
+
+			await expect(configManager.SaveConfig("test", {})).rejects.toThrow(
+				"Failed to save config: Error: Failed to write config to secrets: Error: Storage failed",
+			)
+		})
+	})
+
+	describe("DeleteConfig", () => {
+		it("should delete existing config", async () => {
+			const existingConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					default: {
+						id: "default",
+					},
+					test: {
+						apiProvider: "anthropic",
+						id: "test-id",
+					},
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
+
+			await configManager.DeleteConfig("test")
+
+			// Get the stored config to check the ID
+			const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
+			expect(storedConfig.currentApiConfigName).toBe("default")
+			expect(Object.keys(storedConfig.apiConfigs)).toEqual(["default"])
+			expect(storedConfig.apiConfigs.default.id).toBeTruthy()
+		})
+
+		it("should throw error when trying to delete non-existent config", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: { default: {} },
+				}),
+			)
+
+			await expect(configManager.DeleteConfig("nonexistent")).rejects.toThrow("Config 'nonexistent' not found")
+		})
+
+		it("should throw error when trying to delete last remaining config", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						default: {
+							id: "default",
+						},
+					},
+				}),
+			)
+
+			await expect(configManager.DeleteConfig("default")).rejects.toThrow(
+				"Cannot delete the last remaining configuration.",
+			)
+		})
+	})
+
+	describe("LoadConfig", () => {
+		it("should load config and update current config name", async () => {
+			const existingConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					test: {
+						apiProvider: "anthropic",
+						apiKey: "test-key",
+						id: "test-id",
+					},
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
+
+			const config = await configManager.LoadConfig("test")
+
+			expect(config).toEqual({
+				apiProvider: "anthropic",
+				apiKey: "test-key",
+				id: "test-id",
+			})
+
+			// Get the stored config to check the structure
+			const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
+			expect(storedConfig.currentApiConfigName).toBe("test")
+			expect(storedConfig.apiConfigs.test).toEqual({
+				apiProvider: "anthropic",
+				apiKey: "test-key",
+				id: "test-id",
+			})
+		})
+
+		it("should throw error when config does not exist", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						default: {
+							config: {},
+							id: "default",
+						},
+					},
+				}),
+			)
+
+			await expect(configManager.LoadConfig("nonexistent")).rejects.toThrow("Config 'nonexistent' not found")
+		})
+
+		it("should throw error if secrets storage fails", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						test: {
+							config: {
+								apiProvider: "anthropic",
+							},
+							id: "test-id",
+						},
+					},
+				}),
+			)
+			mockSecrets.store.mockRejectedValueOnce(new Error("Storage failed"))
+
+			await expect(configManager.LoadConfig("test")).rejects.toThrow(
+				"Failed to load config: Error: Failed to write config to secrets: Error: Storage failed",
+			)
+		})
+	})
+
+	describe("SetCurrentConfig", () => {
+		it("should set current config", async () => {
+			const existingConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					default: {
+						id: "default",
+					},
+					test: {
+						apiProvider: "anthropic",
+						id: "test-id",
+					},
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
+
+			await configManager.SetCurrentConfig("test")
+
+			// Get the stored config to check the structure
+			const storedConfig = JSON.parse(mockSecrets.store.mock.calls[0][1])
+			expect(storedConfig.currentApiConfigName).toBe("test")
+			expect(storedConfig.apiConfigs.default.id).toBe("default")
+			expect(storedConfig.apiConfigs.test).toEqual({
+				apiProvider: "anthropic",
+				id: "test-id",
+			})
+		})
+
+		it("should throw error when config does not exist", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: { default: {} },
+				}),
+			)
+
+			await expect(configManager.SetCurrentConfig("nonexistent")).rejects.toThrow(
+				"Config 'nonexistent' not found",
+			)
+		})
+
+		it("should throw error if secrets storage fails", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: {
+						test: { apiProvider: "anthropic" },
+					},
+				}),
+			)
+			mockSecrets.store.mockRejectedValueOnce(new Error("Storage failed"))
+
+			await expect(configManager.SetCurrentConfig("test")).rejects.toThrow(
+				"Failed to set current config: Error: Failed to write config to secrets: Error: Storage failed",
+			)
+		})
+	})
+
+	describe("HasConfig", () => {
+		it("should return true for existing config", async () => {
+			const existingConfig: ApiConfigData = {
+				currentApiConfigName: "default",
+				apiConfigs: {
+					default: {
+						id: "default",
+					},
+					test: {
+						apiProvider: "anthropic",
+						id: "test-id",
+					},
+				},
+			}
+
+			mockSecrets.get.mockResolvedValue(JSON.stringify(existingConfig))
+
+			const hasConfig = await configManager.HasConfig("test")
+			expect(hasConfig).toBe(true)
+		})
+
+		it("should return false for non-existent config", async () => {
+			mockSecrets.get.mockResolvedValue(
+				JSON.stringify({
+					currentApiConfigName: "default",
+					apiConfigs: { default: {} },
+				}),
+			)
+
+			const hasConfig = await configManager.HasConfig("nonexistent")
+			expect(hasConfig).toBe(false)
+		})
+
+		it("should throw error if secrets storage fails", async () => {
+			mockSecrets.get.mockRejectedValue(new Error("Storage failed"))
+
+			await expect(configManager.HasConfig("test")).rejects.toThrow(
+				"Failed to check config existence: Error: Failed to read config from secrets: Error: Storage failed",
+			)
+		})
+	})
+})

+ 13 - 9
src/core/diff/DiffStrategy.ts

@@ -1,17 +1,21 @@
-import type { DiffStrategy } from './types'
-import { UnifiedDiffStrategy } from './strategies/unified'
-import { SearchReplaceDiffStrategy } from './strategies/search-replace'
-import { NewUnifiedDiffStrategy } from './strategies/new-unified'
+import type { DiffStrategy } from "./types"
+import { UnifiedDiffStrategy } from "./strategies/unified"
+import { SearchReplaceDiffStrategy } from "./strategies/search-replace"
+import { NewUnifiedDiffStrategy } from "./strategies/new-unified"
 /**
  * Get the appropriate diff strategy for the given model
  * @param model The name of the model being used (e.g., 'gpt-4', 'claude-3-opus')
  * @returns The appropriate diff strategy for the model
  */
-export function getDiffStrategy(model: string, fuzzyMatchThreshold?: number, experimentalDiffStrategy: boolean = false): DiffStrategy {
-    if (experimentalDiffStrategy) {
-        return new NewUnifiedDiffStrategy(fuzzyMatchThreshold)
-    }
-    return new SearchReplaceDiffStrategy(fuzzyMatchThreshold)
+export function getDiffStrategy(
+	model: string,
+	fuzzyMatchThreshold?: number,
+	experimentalDiffStrategy: boolean = false,
+): DiffStrategy {
+	if (experimentalDiffStrategy) {
+		return new NewUnifiedDiffStrategy(fuzzyMatchThreshold)
+	}
+	return new SearchReplaceDiffStrategy(fuzzyMatchThreshold)
 }
 
 export type { DiffStrategy }

+ 239 - 242
src/core/diff/strategies/__tests__/new-unified.test.ts

@@ -1,74 +1,73 @@
-import { NewUnifiedDiffStrategy } from '../new-unified';
-
-describe('main', () => {
-
-  let strategy: NewUnifiedDiffStrategy
-
-  beforeEach(() => {
-      strategy = new NewUnifiedDiffStrategy(0.97)
-  })
-
-  describe('constructor', () => {
-    it('should use default confidence threshold when not provided', () => {
-      const defaultStrategy = new NewUnifiedDiffStrategy()
-      expect(defaultStrategy['confidenceThreshold']).toBe(1)
-    })
-
-    it('should use provided confidence threshold', () => {
-      const customStrategy = new NewUnifiedDiffStrategy(0.85)
-      expect(customStrategy['confidenceThreshold']).toBe(0.85)
-    })
-
-    it('should enforce minimum confidence threshold', () => {
-      const lowStrategy = new NewUnifiedDiffStrategy(0.7) // Below minimum of 0.8
-      expect(lowStrategy['confidenceThreshold']).toBe(0.8)
-    })
-  })
-
-  describe('getToolDescription', () => {
-      it('should return tool description with correct cwd', () => {
-          const cwd = '/test/path'
-          const description = strategy.getToolDescription({ cwd })
-          
-          expect(description).toContain('apply_diff')
-          expect(description).toContain(cwd)
-          expect(description).toContain('Parameters:')
-          expect(description).toContain('Format Requirements:')
-      })
-  })
-
-  it('should apply simple diff correctly', async () => {
-    const original = `line1
+import { NewUnifiedDiffStrategy } from "../new-unified"
+
+describe("main", () => {
+	let strategy: NewUnifiedDiffStrategy
+
+	beforeEach(() => {
+		strategy = new NewUnifiedDiffStrategy(0.97)
+	})
+
+	describe("constructor", () => {
+		it("should use default confidence threshold when not provided", () => {
+			const defaultStrategy = new NewUnifiedDiffStrategy()
+			expect(defaultStrategy["confidenceThreshold"]).toBe(1)
+		})
+
+		it("should use provided confidence threshold", () => {
+			const customStrategy = new NewUnifiedDiffStrategy(0.85)
+			expect(customStrategy["confidenceThreshold"]).toBe(0.85)
+		})
+
+		it("should enforce minimum confidence threshold", () => {
+			const lowStrategy = new NewUnifiedDiffStrategy(0.7) // Below minimum of 0.8
+			expect(lowStrategy["confidenceThreshold"]).toBe(0.8)
+		})
+	})
+
+	describe("getToolDescription", () => {
+		it("should return tool description with correct cwd", () => {
+			const cwd = "/test/path"
+			const description = strategy.getToolDescription({ cwd })
+
+			expect(description).toContain("apply_diff")
+			expect(description).toContain(cwd)
+			expect(description).toContain("Parameters:")
+			expect(description).toContain("Format Requirements:")
+		})
+	})
+
+	it("should apply simple diff correctly", async () => {
+		const original = `line1
 line2
-line3`;
+line3`
 
-    const diff = `--- a/file.txt
+		const diff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1
 +new line
  line2
 -line3
-+modified line3`;
++modified line3`
 
-    const result = await strategy.applyDiff(original, diff);
-    expect(result.success).toBe(true);
-    if(result.success) {
-      expect(result.content).toBe(`line1
+		const result = await strategy.applyDiff(original, diff)
+		expect(result.success).toBe(true)
+		if (result.success) {
+			expect(result.content).toBe(`line1
 new line
 line2
-modified line3`);
-    }
-  });
+modified line3`)
+		}
+	})
 
-  it('should handle multiple hunks', async () => {
-    const original = `line1
+	it("should handle multiple hunks", async () => {
+		const original = `line1
 line2
 line3
 line4
-line5`;
+line5`
 
-    const diff = `--- a/file.txt
+		const diff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1
@@ -80,23 +79,23 @@ line5`;
  line4
 -line5
 +modified line5
-+new line at end`;
++new line at end`
 
-    const result = await strategy.applyDiff(original, diff);
-    expect(result.success).toBe(true);
-    if (result.success) {
-      expect(result.content).toBe(`line1
+		const result = await strategy.applyDiff(original, diff)
+		expect(result.success).toBe(true)
+		if (result.success) {
+			expect(result.content).toBe(`line1
 new line
 line2
 modified line3
 line4
 modified line5
-new line at end`);
-    }
-  });
+new line at end`)
+		}
+	})
 
-  it('should handle complex large', async () => {
-    const original = `line1
+	it("should handle complex large", async () => {
+		const original = `line1
 line2
 line3
 line4
@@ -105,9 +104,9 @@ line6
 line7
 line8
 line9
-line10`;
+line10`
 
-    const diff = `--- a/file.txt
+		const diff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1
@@ -130,12 +129,12 @@ line10`;
  line9
 -line10
 +final line
-+very last line`;
++very last line`
 
-    const result = await strategy.applyDiff(original, diff);
-    expect(result.success).toBe(true);
-    if (result.success) {
-      expect(result.content).toBe(`line1
+		const result = await strategy.applyDiff(original, diff)
+		expect(result.success).toBe(true)
+		if (result.success) {
+			expect(result.content).toBe(`line1
 header line
 another header
 line2
@@ -150,12 +149,12 @@ changed line8
 bonus line
 line9
 final line
-very last line`);
-    }
-  });
+very last line`)
+		}
+	})
 
-  it('should handle indentation changes', async () => {
-    const original = `first line
+	it("should handle indentation changes", async () => {
+		const original = `first line
   indented line
     double indented line
   back to single indent
@@ -164,9 +163,9 @@ no indent
     double indent again
       triple indent
   back to single
-last line`;
+last line`
 
-    const diff = `--- original
+		const diff = `--- original
 +++ modified
 @@ ... @@
  first line
@@ -181,9 +180,9 @@ last line`;
 -      triple indent
 +      hi there mate
    back to single
- last line`;
+ last line`
 
-    const expected = `first line
+		const expected = `first line
   indented line
 	tab indented line
   new indented line
@@ -194,23 +193,22 @@ no indent
     double indent again
       hi there mate
   back to single
-last line`;
+last line`
 
-    const result = await strategy.applyDiff(original, diff);
-    expect(result.success).toBe(true);
-    if (result.success) {
-      expect(result.content).toBe(expected);
-    }
-  });
+		const result = await strategy.applyDiff(original, diff)
+		expect(result.success).toBe(true)
+		if (result.success) {
+			expect(result.content).toBe(expected)
+		}
+	})
 
-  it('should handle high level edits', async () => {
-
-    const original = `def factorial(n):
+	it("should handle high level edits", async () => {
+		const original = `def factorial(n):
     if n == 0:
         return 1
     else:
         return n * factorial(n-1)`
-    const diff = `@@ ... @@
+		const diff = `@@ ... @@
 -def factorial(n):
 -    if n == 0:
 -        return 1
@@ -222,21 +220,21 @@ last line`;
 +    else:
 +        return number * factorial(number-1)`
 
-const expected = `def factorial(number):
+		const expected = `def factorial(number):
     if number == 0:
         return 1
     else:
         return number * factorial(number-1)`
 
-    const result = await strategy.applyDiff(original, diff);
-    expect(result.success).toBe(true);
-    if (result.success) {
-      expect(result.content).toBe(expected);
-    }
-  });
+		const result = await strategy.applyDiff(original, diff)
+		expect(result.success).toBe(true)
+		if (result.success) {
+			expect(result.content).toBe(expected)
+		}
+	})
 
-  it('it should handle very complex edits', async () => {
-    const original = `//Initialize the array that will hold the primes
+	it("it should handle very complex edits", async () => {
+		const original = `//Initialize the array that will hold the primes
 var primeArray = [];
 /*Write a function that checks for primeness and
  pushes those values to t*he array*/
@@ -269,7 +267,7 @@ for (var i = 2; primeArray.length < numPrimes; i++) {
 console.log(primeArray);
 `
 
-    const diff = `--- test_diff.js
+		const diff = `--- test_diff.js
 +++ test_diff.js
 @@ ... @@
 -//Initialize the array that will hold the primes
@@ -297,7 +295,7 @@ console.log(primeArray);
  }
  console.log(primeArray);`
 
-    const expected = `var primeArray = [];
+		const expected = `var primeArray = [];
 function PrimeCheck(candidate){
   isPrime = true;
   for(var i = 2; i < candidate && isPrime; i++){
@@ -320,58 +318,57 @@ for (var i = 2; primeArray.length < numPrimes; i++) {
 }
 console.log(primeArray);
 `
- 
 
-    const result = await strategy.applyDiff(original, diff);
-    expect(result.success).toBe(true);
-    if (result.success) {
-      expect(result.content).toBe(expected);
-    }
-  });
-
-  describe('error handling and edge cases', () => {
-    it('should reject completely invalid diff format', async () => {
-      const original = 'line1\nline2\nline3';
-      const invalidDiff = 'this is not a diff at all';
-      
-      const result = await strategy.applyDiff(original, invalidDiff);
-      expect(result.success).toBe(false);
-    });
-
-    it('should reject diff with invalid hunk format', async () => {
-      const original = 'line1\nline2\nline3';
-      const invalidHunkDiff = `--- a/file.txt
+		const result = await strategy.applyDiff(original, diff)
+		expect(result.success).toBe(true)
+		if (result.success) {
+			expect(result.content).toBe(expected)
+		}
+	})
+
+	describe("error handling and edge cases", () => {
+		it("should reject completely invalid diff format", async () => {
+			const original = "line1\nline2\nline3"
+			const invalidDiff = "this is not a diff at all"
+
+			const result = await strategy.applyDiff(original, invalidDiff)
+			expect(result.success).toBe(false)
+		})
+
+		it("should reject diff with invalid hunk format", async () => {
+			const original = "line1\nline2\nline3"
+			const invalidHunkDiff = `--- a/file.txt
 +++ b/file.txt
 invalid hunk header
  line1
 -line2
-+new line`;
-      
-      const result = await strategy.applyDiff(original, invalidHunkDiff);
-      expect(result.success).toBe(false);
-    });
-
-    it('should fail when diff tries to modify non-existent content', async () => {
-      const original = 'line1\nline2\nline3';
-      const nonMatchingDiff = `--- a/file.txt
++new line`
+
+			const result = await strategy.applyDiff(original, invalidHunkDiff)
+			expect(result.success).toBe(false)
+		})
+
+		it("should fail when diff tries to modify non-existent content", async () => {
+			const original = "line1\nline2\nline3"
+			const nonMatchingDiff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1
 -nonexistent line
 +new line
- line3`;
-      
-      const result = await strategy.applyDiff(original, nonMatchingDiff);
-      expect(result.success).toBe(false);
-    });
-
-    it('should handle overlapping hunks', async () => {
-      const original = `line1
+ line3`
+
+			const result = await strategy.applyDiff(original, nonMatchingDiff)
+			expect(result.success).toBe(false)
+		})
+
+		it("should handle overlapping hunks", async () => {
+			const original = `line1
 line2
 line3
 line4
-line5`;
-      const overlappingDiff = `--- a/file.txt
+line5`
+			const overlappingDiff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1
@@ -384,19 +381,19 @@ line5`;
 -line3
 -line4
 +modified3and4
- line5`;
-      
-      const result = await strategy.applyDiff(original, overlappingDiff);
-      expect(result.success).toBe(false);
-    });
+ line5`
+
+			const result = await strategy.applyDiff(original, overlappingDiff)
+			expect(result.success).toBe(false)
+		})
 
-    it('should handle empty lines modifications', async () => {
-      const original = `line1
+		it("should handle empty lines modifications", async () => {
+			const original = `line1
 
 line3
 
-line5`;
-      const emptyLinesDiff = `--- a/file.txt
+line5`
+			const emptyLinesDiff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1
@@ -404,73 +401,73 @@ line5`;
 -line3
 +line3modified
 
- line5`;
-      
-      const result = await strategy.applyDiff(original, emptyLinesDiff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe(`line1
+ line5`
+
+			const result = await strategy.applyDiff(original, emptyLinesDiff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(`line1
 
 line3modified
 
-line5`);
-      }
-    });
+line5`)
+			}
+		})
 
-    it('should handle mixed line endings in diff', async () => {
-      const original = 'line1\r\nline2\nline3\r\n';
-      const mixedEndingsDiff = `--- a/file.txt
+		it("should handle mixed line endings in diff", async () => {
+			const original = "line1\r\nline2\nline3\r\n"
+			const mixedEndingsDiff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
  line1\r
 -line2
 +modified2\r
- line3`;
-      
-      const result = await strategy.applyDiff(original, mixedEndingsDiff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe('line1\r\nmodified2\r\nline3\r\n');
-      }
-    });
-
-    it('should handle partial line modifications', async () => {
-      const original = 'const value = oldValue + 123;';
-      const partialDiff = `--- a/file.txt
+ line3`
+
+			const result = await strategy.applyDiff(original, mixedEndingsDiff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe("line1\r\nmodified2\r\nline3\r\n")
+			}
+		})
+
+		it("should handle partial line modifications", async () => {
+			const original = "const value = oldValue + 123;"
+			const partialDiff = `--- a/file.txt
 +++ b/file.txt
 @@ ... @@
 -const value = oldValue + 123;
-+const value = newValue + 123;`;
-      
-      const result = await strategy.applyDiff(original, partialDiff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe('const value = newValue + 123;');
-      }
-    });
-
-    it('should handle slightly malformed but recoverable diff', async () => {
-      const original = 'line1\nline2\nline3';
-      // Missing space after --- and +++
-      const slightlyBadDiff = `---a/file.txt
++const value = newValue + 123;`
+
+			const result = await strategy.applyDiff(original, partialDiff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe("const value = newValue + 123;")
+			}
+		})
+
+		it("should handle slightly malformed but recoverable diff", async () => {
+			const original = "line1\nline2\nline3"
+			// Missing space after --- and +++
+			const slightlyBadDiff = `---a/file.txt
 +++b/file.txt
 @@ ... @@
  line1
 -line2
 +new line
- line3`;
-      
-      const result = await strategy.applyDiff(original, slightlyBadDiff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe('line1\nnew line\nline3');
-      }
-    });
-  });
-
-  describe('similar code sections', () => {
-    it('should correctly modify the right section when similar code exists', async () => {
-      const original = `function add(a, b) {
+ line3`
+
+			const result = await strategy.applyDiff(original, slightlyBadDiff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe("line1\nnew line\nline3")
+			}
+		})
+	})
+
+	describe("similar code sections", () => {
+		it("should correctly modify the right section when similar code exists", async () => {
+			const original = `function add(a, b) {
   return a + b;
 }
 
@@ -480,20 +477,20 @@ function subtract(a, b) {
 
 function multiply(a, b) {
   return a + b;  // Bug here
-}`;
+}`
 
-      const diff = `--- a/math.js
+			const diff = `--- a/math.js
 +++ b/math.js
 @@ ... @@
  function multiply(a, b) {
 -  return a + b;  // Bug here
 +  return a * b;
- }`;
+ }`
 
-      const result = await strategy.applyDiff(original, diff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe(`function add(a, b) {
+			const result = await strategy.applyDiff(original, diff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(`function add(a, b) {
   return a + b;
 }
 
@@ -503,12 +500,12 @@ function subtract(a, b) {
 
 function multiply(a, b) {
   return a * b;
-}`);
-      }
-    });
+}`)
+			}
+		})
 
-    it('should handle multiple similar sections with correct context', async () => {
-      const original = `if (condition) {
+		it("should handle multiple similar sections with correct context", async () => {
+			const original = `if (condition) {
   doSomething();
   doSomething();
   doSomething();
@@ -518,9 +515,9 @@ if (otherCondition) {
   doSomething();
   doSomething();
   doSomething();
-}`;
+}`
 
-      const diff = `--- a/file.js
+			const diff = `--- a/file.js
 +++ b/file.js
 @@ ... @@
  if (otherCondition) {
@@ -528,12 +525,12 @@ if (otherCondition) {
 -  doSomething();
 +  doSomethingElse();
    doSomething();
- }`;
+ }`
 
-      const result = await strategy.applyDiff(original, diff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe(`if (condition) {
+			const result = await strategy.applyDiff(original, diff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(`if (condition) {
   doSomething();
   doSomething();
   doSomething();
@@ -543,14 +540,14 @@ if (otherCondition) {
   doSomething();
   doSomethingElse();
   doSomething();
-}`);
-      }
-    });
-  });
-
-  describe('hunk splitting', () => {
-    it('should handle large diffs with multiple non-contiguous changes', async () => {
-      const original = `import { readFile } from 'fs';
+}`)
+			}
+		})
+	})
+
+	describe("hunk splitting", () => {
+		it("should handle large diffs with multiple non-contiguous changes", async () => {
+			const original = `import { readFile } from 'fs';
 import { join } from 'path';
 import { Logger } from './logger';
 
@@ -595,9 +592,9 @@ export {
   validateInput,
   writeOutput,
   parseConfig
-};`;
+};`
 
-      const diff = `--- a/file.ts
+			const diff = `--- a/file.ts
 +++ b/file.ts
 @@ ... @@
 -import { readFile } from 'fs';
@@ -672,9 +669,9 @@ export {
 -  parseConfig
 +  parseConfig,
 +  type Config
- };`;
+ };`
 
-      const expected = `import { readFile, writeFile } from 'fs';
+			const expected = `import { readFile, writeFile } from 'fs';
 import { join } from 'path';
 import { Logger } from './utils/logger';
 import { Config } from './types';
@@ -727,13 +724,13 @@ export {
   writeOutput,
   parseConfig,
   type Config
-};`;
-
-      const result = await strategy.applyDiff(original, diff);
-      expect(result.success).toBe(true);
-      if (result.success) {
-        expect(result.content).toBe(expected);
-      }
-    });
-  });
-});
+};`
+
+			const result = await strategy.applyDiff(original, diff)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(expected)
+			}
+		})
+	})
+})

Разлика између датотеке није приказан због своје велике величине
+ 375 - 364
src/core/diff/strategies/__tests__/search-replace.test.ts


+ 74 - 75
src/core/diff/strategies/__tests__/unified.test.ts

@@ -1,27 +1,27 @@
-import { UnifiedDiffStrategy } from '../unified'
-
-describe('UnifiedDiffStrategy', () => {
-    let strategy: UnifiedDiffStrategy
-
-    beforeEach(() => {
-        strategy = new UnifiedDiffStrategy()
-    })
-
-    describe('getToolDescription', () => {
-        it('should return tool description with correct cwd', () => {
-            const cwd = '/test/path'
-            const description = strategy.getToolDescription({ cwd })
-            
-            expect(description).toContain('apply_diff')
-            expect(description).toContain(cwd)
-            expect(description).toContain('Parameters:')
-            expect(description).toContain('Format Requirements:')
-        })
-    })
-
-    describe('applyDiff', () => {
-        it('should successfully apply a function modification diff', async () => {
-            const originalContent = `import { Logger } from '../logger';
+import { UnifiedDiffStrategy } from "../unified"
+
+describe("UnifiedDiffStrategy", () => {
+	let strategy: UnifiedDiffStrategy
+
+	beforeEach(() => {
+		strategy = new UnifiedDiffStrategy()
+	})
+
+	describe("getToolDescription", () => {
+		it("should return tool description with correct cwd", () => {
+			const cwd = "/test/path"
+			const description = strategy.getToolDescription({ cwd })
+
+			expect(description).toContain("apply_diff")
+			expect(description).toContain(cwd)
+			expect(description).toContain("Parameters:")
+			expect(description).toContain("Format Requirements:")
+		})
+	})
+
+	describe("applyDiff", () => {
+		it("should successfully apply a function modification diff", async () => {
+			const originalContent = `import { Logger } from '../logger';
 
 function calculateTotal(items: number[]): number {
   return items.reduce((sum, item) => {
@@ -31,7 +31,7 @@ function calculateTotal(items: number[]): number {
 
 export { calculateTotal };`
 
-            const diffContent = `--- src/utils/helper.ts
+			const diffContent = `--- src/utils/helper.ts
 +++ src/utils/helper.ts
 @@ -1,9 +1,10 @@
  import { Logger } from '../logger';
@@ -47,7 +47,7 @@ export { calculateTotal };`
  
  export { calculateTotal };`
 
-            const expected = `import { Logger } from '../logger';
+			const expected = `import { Logger } from '../logger';
 
 function calculateTotal(items: number[]): number {
   const total = items.reduce((sum, item) => {
@@ -58,21 +58,21 @@ function calculateTotal(items: number[]): number {
 
 export { calculateTotal };`
 
-            const result = await strategy.applyDiff(originalContent, diffContent)
-            expect(result.success).toBe(true)
-            if (result.success) {
-                expect(result.content).toBe(expected)
-            }
-        })
+			const result = await strategy.applyDiff(originalContent, diffContent)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(expected)
+			}
+		})
 
-        it('should successfully apply a diff adding a new method', async () => {
-            const originalContent = `class Calculator {
+		it("should successfully apply a diff adding a new method", async () => {
+			const originalContent = `class Calculator {
   add(a: number, b: number): number {
     return a + b;
   }
 }`
 
-            const diffContent = `--- src/Calculator.ts
+			const diffContent = `--- src/Calculator.ts
 +++ src/Calculator.ts
 @@ -1,5 +1,9 @@
  class Calculator {
@@ -85,7 +85,7 @@ export { calculateTotal };`
 +  }
  }`
 
-            const expected = `class Calculator {
+			const expected = `class Calculator {
   add(a: number, b: number): number {
     return a + b;
   }
@@ -95,15 +95,15 @@ export { calculateTotal };`
   }
 }`
 
-            const result = await strategy.applyDiff(originalContent, diffContent)
-            expect(result.success).toBe(true)
-            if (result.success) {
-                expect(result.content).toBe(expected)
-            }
-        })
+			const result = await strategy.applyDiff(originalContent, diffContent)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(expected)
+			}
+		})
 
-        it('should successfully apply a diff modifying imports', async () => {
-            const originalContent = `import { useState } from 'react';
+		it("should successfully apply a diff modifying imports", async () => {
+			const originalContent = `import { useState } from 'react';
 import { Button } from './components';
 
 function App() {
@@ -111,7 +111,7 @@ function App() {
   return <Button onClick={() => setCount(count + 1)}>{count}</Button>;
 }`
 
-            const diffContent = `--- src/App.tsx
+			const diffContent = `--- src/App.tsx
 +++ src/App.tsx
 @@ -1,7 +1,8 @@
 -import { useState } from 'react';
@@ -124,7 +124,7 @@ function App() {
    return <Button onClick={() => setCount(count + 1)}>{count}</Button>;
  }`
 
-            const expected = `import { useState, useEffect } from 'react';
+			const expected = `import { useState, useEffect } from 'react';
 import { Button } from './components';
 
 function App() {
@@ -132,16 +132,16 @@ function App() {
   useEffect(() => { document.title = \`Count: \${count}\` }, [count]);
   return <Button onClick={() => setCount(count + 1)}>{count}</Button>;
 }`
-          
-            const result = await strategy.applyDiff(originalContent, diffContent)
-            expect(result.success).toBe(true)
-            if (result.success) {
-                expect(result.content).toBe(expected)
-            }
-        })
 
-        it('should successfully apply a diff with multiple hunks', async () => {
-            const originalContent = `import { readFile, writeFile } from 'fs';
+			const result = await strategy.applyDiff(originalContent, diffContent)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(expected)
+			}
+		})
+
+		it("should successfully apply a diff with multiple hunks", async () => {
+			const originalContent = `import { readFile, writeFile } from 'fs';
 
 function processFile(path: string) {
   readFile(path, 'utf8', (err, data) => {
@@ -155,7 +155,7 @@ function processFile(path: string) {
 
 export { processFile };`
 
-            const diffContent = `--- src/file-processor.ts
+			const diffContent = `--- src/file-processor.ts
 +++ src/file-processor.ts
 @@ -1,12 +1,14 @@
 -import { readFile, writeFile } from 'fs';
@@ -182,7 +182,7 @@ export { processFile };`
  
  export { processFile };`
 
-            const expected = `import { promises as fs } from 'fs';
+			const expected = `import { promises as fs } from 'fs';
 import { join } from 'path';
 
 async function processFile(path: string) {
@@ -198,32 +198,31 @@ async function processFile(path: string) {
 
 export { processFile };`
 
-            const result = await strategy.applyDiff(originalContent, diffContent)
-            expect(result.success).toBe(true)
-            if (result.success) {
-                expect(result.content).toBe(expected)
-            }
-        })
+			const result = await strategy.applyDiff(originalContent, diffContent)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(expected)
+			}
+		})
 
-        it('should handle empty original content', async () => {
-            const originalContent = ''
-            const diffContent = `--- empty.ts
+		it("should handle empty original content", async () => {
+			const originalContent = ""
+			const diffContent = `--- empty.ts
 +++ empty.ts
 @@ -0,0 +1,3 @@
 +export function greet(name: string): string {
 +  return \`Hello, \${name}!\`;
 +}`
 
-            const expected = `export function greet(name: string): string {
+			const expected = `export function greet(name: string): string {
   return \`Hello, \${name}!\`;
 }\n`
 
-            const result = await strategy.applyDiff(originalContent, diffContent)
-            expect(result.success).toBe(true)
-            if (result.success) {
-                expect(result.content).toBe(expected)
-            }
-        })
-    })
+			const result = await strategy.applyDiff(originalContent, diffContent)
+			expect(result.success).toBe(true)
+			if (result.success) {
+				expect(result.content).toBe(expected)
+			}
+		})
+	})
 })
-

+ 4 - 4
src/core/diff/strategies/new-unified/__tests__/edit-strategies.test.ts

@@ -265,8 +265,8 @@ describe("applyGitFallback", () => {
 				{ type: "context", content: "line1", indent: "" },
 				{ type: "remove", content: "line2", indent: "" },
 				{ type: "add", content: "new line2", indent: "" },
-				{ type: "context", content: "line3", indent: "" }
-			]
+				{ type: "context", content: "line3", indent: "" },
+			],
 		} as Hunk
 
 		const content = ["line1", "line2", "line3"]
@@ -281,8 +281,8 @@ describe("applyGitFallback", () => {
 		const hunk = {
 			changes: [
 				{ type: "context", content: "nonexistent", indent: "" },
-				{ type: "add", content: "new line", indent: "" }
-			]
+				{ type: "add", content: "new line", indent: "" },
+			],
 		} as Hunk
 
 		const content = ["line1", "line2", "line3"]

+ 184 - 184
src/core/diff/strategies/new-unified/__tests__/search-strategies.test.ts

@@ -3,7 +3,7 @@ import { findAnchorMatch, findExactMatch, findSimilarityMatch, findLevenshteinMa
 type SearchStrategy = (
 	searchStr: string,
 	content: string[],
-	startIndex?: number
+	startIndex?: number,
 ) => {
 	index: number
 	confidence: number
@@ -11,141 +11,141 @@ type SearchStrategy = (
 }
 
 const testCases = [
-    {
-        name: "should return no match if the search string is not found",
-        searchStr: "not found",
-        content: ["line1", "line2", "line3"],
-        expected: { index: -1, confidence: 0 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match if the search string is found",
-        searchStr: "line2",
-        content: ["line1", "line2", "line3"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with correct index when startIndex is provided",
-        searchStr: "line3",
-        content: ["line1", "line2", "line3", "line4", "line3"],
-        startIndex: 3,
-        expected: { index: 4, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match even if there are more lines in content",
-        searchStr: "line2",
-        content: ["line1", "line2", "line3", "line4", "line5"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match even if the search string is at the beginning of the content",
-        searchStr: "line1",
-        content: ["line1", "line2", "line3"],
-        expected: { index: 0, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match even if the search string is at the end of the content",
-        searchStr: "line3",
-        content: ["line1", "line2", "line3"],
-        expected: { index: 2, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match for a multi-line search string",
-        searchStr: "line2\nline3",
-        content: ["line1", "line2", "line3", "line4"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return no match if a multi-line search string is not found",
-        searchStr: "line2\nline4",
-        content: ["line1", "line2", "line3", "line4"],
-        expected: { index: -1, confidence: 0 },
-        strategies: ["exact", "similarity"],
-    },
-    {
-        name: "should return a match with indentation",
-        searchStr: "  line2",
-        content: ["line1", "  line2", "line3"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with more complex indentation",
-        searchStr: "    line3",
-        content: ["  line1", "    line2", "    line3", "  line4"],
-        expected: { index: 2, confidence: 1 },
-         strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with mixed indentation",
-        searchStr: "\tline2",
-        content: ["  line1", "\tline2", "    line3"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with mixed indentation and multi-line",
-        searchStr: "  line2\n\tline3",
-        content: ["line1", "  line2", "\tline3", "    line4"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return no match if mixed indentation and multi-line is not found",
-        searchStr: "  line2\n    line4",
-        content: ["line1", "  line2", "\tline3", "    line4"],
-        expected: { index: -1, confidence: 0 },
-        strategies: ["exact", "similarity"],
-    },
-    {
-        name: "should return a match with leading and trailing spaces",
-        searchStr: "  line2  ",
-        content: ["line1", "  line2  ", "line3"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with leading and trailing tabs",
-        searchStr: "\tline2\t",
-        content: ["line1", "\tline2\t", "line3"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with mixed leading and trailing spaces and tabs",
-        searchStr: " \tline2\t ",
-        content: ["line1", " \tline2\t ", "line3"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return a match with mixed leading and trailing spaces and tabs and multi-line",
-        searchStr: " \tline2\t \n  line3  ",
-        content: ["line1", " \tline2\t ", "  line3  ", "line4"],
-        expected: { index: 1, confidence: 1 },
-        strategies: ["exact", "similarity", "levenshtein"],
-    },
-    {
-        name: "should return no match if mixed leading and trailing spaces and tabs and multi-line is not found",
-        searchStr: " \tline2\t \n  line4  ",
-        content: ["line1", " \tline2\t ", "  line3  ", "line4"],
-        expected: { index: -1, confidence: 0 },
-        strategies: ["exact", "similarity"],
-    },
+	{
+		name: "should return no match if the search string is not found",
+		searchStr: "not found",
+		content: ["line1", "line2", "line3"],
+		expected: { index: -1, confidence: 0 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match if the search string is found",
+		searchStr: "line2",
+		content: ["line1", "line2", "line3"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with correct index when startIndex is provided",
+		searchStr: "line3",
+		content: ["line1", "line2", "line3", "line4", "line3"],
+		startIndex: 3,
+		expected: { index: 4, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match even if there are more lines in content",
+		searchStr: "line2",
+		content: ["line1", "line2", "line3", "line4", "line5"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match even if the search string is at the beginning of the content",
+		searchStr: "line1",
+		content: ["line1", "line2", "line3"],
+		expected: { index: 0, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match even if the search string is at the end of the content",
+		searchStr: "line3",
+		content: ["line1", "line2", "line3"],
+		expected: { index: 2, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match for a multi-line search string",
+		searchStr: "line2\nline3",
+		content: ["line1", "line2", "line3", "line4"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return no match if a multi-line search string is not found",
+		searchStr: "line2\nline4",
+		content: ["line1", "line2", "line3", "line4"],
+		expected: { index: -1, confidence: 0 },
+		strategies: ["exact", "similarity"],
+	},
+	{
+		name: "should return a match with indentation",
+		searchStr: "  line2",
+		content: ["line1", "  line2", "line3"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with more complex indentation",
+		searchStr: "    line3",
+		content: ["  line1", "    line2", "    line3", "  line4"],
+		expected: { index: 2, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with mixed indentation",
+		searchStr: "\tline2",
+		content: ["  line1", "\tline2", "    line3"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with mixed indentation and multi-line",
+		searchStr: "  line2\n\tline3",
+		content: ["line1", "  line2", "\tline3", "    line4"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return no match if mixed indentation and multi-line is not found",
+		searchStr: "  line2\n    line4",
+		content: ["line1", "  line2", "\tline3", "    line4"],
+		expected: { index: -1, confidence: 0 },
+		strategies: ["exact", "similarity"],
+	},
+	{
+		name: "should return a match with leading and trailing spaces",
+		searchStr: "  line2  ",
+		content: ["line1", "  line2  ", "line3"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with leading and trailing tabs",
+		searchStr: "\tline2\t",
+		content: ["line1", "\tline2\t", "line3"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with mixed leading and trailing spaces and tabs",
+		searchStr: " \tline2\t ",
+		content: ["line1", " \tline2\t ", "line3"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return a match with mixed leading and trailing spaces and tabs and multi-line",
+		searchStr: " \tline2\t \n  line3  ",
+		content: ["line1", " \tline2\t ", "  line3  ", "line4"],
+		expected: { index: 1, confidence: 1 },
+		strategies: ["exact", "similarity", "levenshtein"],
+	},
+	{
+		name: "should return no match if mixed leading and trailing spaces and tabs and multi-line is not found",
+		searchStr: " \tline2\t \n  line4  ",
+		content: ["line1", " \tline2\t ", "  line3  ", "line4"],
+		expected: { index: -1, confidence: 0 },
+		strategies: ["exact", "similarity"],
+	},
 ]
 
 describe("findExactMatch", () => {
-    testCases.forEach(({ name, searchStr, content, startIndex, expected, strategies }) => {
+	testCases.forEach(({ name, searchStr, content, startIndex, expected, strategies }) => {
 		if (!strategies?.includes("exact")) {
 			return
 		}
-        it(name, () => {
+		it(name, () => {
 			const result = findExactMatch(searchStr, content, startIndex)
 			expect(result.index).toBe(expected.index)
 			expect(result.confidence).toBeGreaterThanOrEqual(expected.confidence)
@@ -155,16 +155,16 @@ describe("findExactMatch", () => {
 })
 
 describe("findAnchorMatch", () => {
-    const anchorTestCases = [
-        {
-            name: "should return no match if no anchors are found",
-            searchStr: "   \n   \n   ",
-            content: ["line1", "line2", "line3"],
-            expected: { index: -1, confidence: 0 },
-        },
-        {
-            name: "should return no match if anchor positions cannot be validated",
-            searchStr: "unique line\ncontext line 1\ncontext line 2",
+	const anchorTestCases = [
+		{
+			name: "should return no match if no anchors are found",
+			searchStr: "   \n   \n   ",
+			content: ["line1", "line2", "line3"],
+			expected: { index: -1, confidence: 0 },
+		},
+		{
+			name: "should return no match if anchor positions cannot be validated",
+			searchStr: "unique line\ncontext line 1\ncontext line 2",
 			content: [
 				"different line 1",
 				"different line 2",
@@ -173,24 +173,24 @@ describe("findAnchorMatch", () => {
 				"context line 1",
 				"context line 2",
 			],
-            expected: { index: -1, confidence: 0 },
-        },
-        {
-            name: "should return a match if anchor positions can be validated",
-            searchStr: "unique line\ncontext line 1\ncontext line 2",
-            content: ["line1", "line2", "unique line", "context line 1", "context line 2", "line 6"],
-            expected: { index: 2, confidence: 1 },
-        },
-        {
-            name: "should return a match with correct index when startIndex is provided",
-            searchStr: "unique line\ncontext line 1\ncontext line 2",
-            content: ["line1", "line2", "line3", "unique line", "context line 1", "context line 2", "line 7"],
-            startIndex: 3,
-            expected: { index: 3, confidence: 1 },
-        },
-        {
-            name: "should return a match even if there are more lines in content",
-            searchStr: "unique line\ncontext line 1\ncontext line 2",
+			expected: { index: -1, confidence: 0 },
+		},
+		{
+			name: "should return a match if anchor positions can be validated",
+			searchStr: "unique line\ncontext line 1\ncontext line 2",
+			content: ["line1", "line2", "unique line", "context line 1", "context line 2", "line 6"],
+			expected: { index: 2, confidence: 1 },
+		},
+		{
+			name: "should return a match with correct index when startIndex is provided",
+			searchStr: "unique line\ncontext line 1\ncontext line 2",
+			content: ["line1", "line2", "line3", "unique line", "context line 1", "context line 2", "line 7"],
+			startIndex: 3,
+			expected: { index: 3, confidence: 1 },
+		},
+		{
+			name: "should return a match even if there are more lines in content",
+			searchStr: "unique line\ncontext line 1\ncontext line 2",
 			content: [
 				"line1",
 				"line2",
@@ -201,30 +201,30 @@ describe("findAnchorMatch", () => {
 				"extra line 1",
 				"extra line 2",
 			],
-            expected: { index: 2, confidence: 1 },
-        },
-        {
-            name: "should return a match even if the anchor is at the beginning of the content",
-            searchStr: "unique line\ncontext line 1\ncontext line 2",
-            content: ["unique line", "context line 1", "context line 2", "line 6"],
-            expected: { index: 0, confidence: 1 },
-        },
-        {
-            name: "should return a match even if the anchor is at the end of the content",
-            searchStr: "unique line\ncontext line 1\ncontext line 2",
-            content: ["line1", "line2", "unique line", "context line 1", "context line 2"],
-            expected: { index: 2, confidence: 1 },
-        },
-        {
-            name: "should return no match if no valid anchor is found",
-            searchStr: "non-unique line\ncontext line 1\ncontext line 2",
-            content: ["line1", "line2", "non-unique line", "context line 1", "context line 2", "non-unique line"],
-            expected: { index: -1, confidence: 0 },
-        },
+			expected: { index: 2, confidence: 1 },
+		},
+		{
+			name: "should return a match even if the anchor is at the beginning of the content",
+			searchStr: "unique line\ncontext line 1\ncontext line 2",
+			content: ["unique line", "context line 1", "context line 2", "line 6"],
+			expected: { index: 0, confidence: 1 },
+		},
+		{
+			name: "should return a match even if the anchor is at the end of the content",
+			searchStr: "unique line\ncontext line 1\ncontext line 2",
+			content: ["line1", "line2", "unique line", "context line 1", "context line 2"],
+			expected: { index: 2, confidence: 1 },
+		},
+		{
+			name: "should return no match if no valid anchor is found",
+			searchStr: "non-unique line\ncontext line 1\ncontext line 2",
+			content: ["line1", "line2", "non-unique line", "context line 1", "context line 2", "non-unique line"],
+			expected: { index: -1, confidence: 0 },
+		},
 	]
 
-    anchorTestCases.forEach(({ name, searchStr, content, startIndex, expected }) => {
-        it(name, () => {
+	anchorTestCases.forEach(({ name, searchStr, content, startIndex, expected }) => {
+		it(name, () => {
 			const result = findAnchorMatch(searchStr, content, startIndex)
 			expect(result.index).toBe(expected.index)
 			expect(result.confidence).toBeGreaterThanOrEqual(expected.confidence)
@@ -234,11 +234,11 @@ describe("findAnchorMatch", () => {
 })
 
 describe("findSimilarityMatch", () => {
-    testCases.forEach(({ name, searchStr, content, startIndex, expected, strategies }) => {
+	testCases.forEach(({ name, searchStr, content, startIndex, expected, strategies }) => {
 		if (!strategies?.includes("similarity")) {
 			return
 		}
-        it(name, () => {
+		it(name, () => {
 			const result = findSimilarityMatch(searchStr, content, startIndex)
 			expect(result.index).toBe(expected.index)
 			expect(result.confidence).toBeGreaterThanOrEqual(expected.confidence)
@@ -248,11 +248,11 @@ describe("findSimilarityMatch", () => {
 })
 
 describe("findLevenshteinMatch", () => {
-    testCases.forEach(({ name, searchStr, content, startIndex, expected, strategies }) => {
+	testCases.forEach(({ name, searchStr, content, startIndex, expected, strategies }) => {
 		if (!strategies?.includes("levenshtein")) {
 			return
 		}
-        it(name, () => {
+		it(name, () => {
 			const result = findLevenshteinMatch(searchStr, content, startIndex)
 			expect(result.index).toBe(expected.index)
 			expect(result.confidence).toBeGreaterThanOrEqual(expected.confidence)

+ 27 - 35
src/core/diff/strategies/new-unified/edit-strategies.ts

@@ -18,7 +18,7 @@ function inferIndentation(line: string, contextLines: string[], previousIndent:
 	const contextLine = contextLines[0]
 	if (contextLine) {
 		const contextMatch = contextLine.match(/^(\s+)/)
-    if (contextMatch) {
+		if (contextMatch) {
 			return contextMatch[1]
 		}
 	}
@@ -28,19 +28,15 @@ function inferIndentation(line: string, contextLines: string[], previousIndent:
 }
 
 // Context matching edit strategy
-export function applyContextMatching(
-	hunk: Hunk,
-	content: string[],
-	matchPosition: number,
-): EditResult {
-  if (matchPosition === -1) {
+export function applyContextMatching(hunk: Hunk, content: string[], matchPosition: number): EditResult {
+	if (matchPosition === -1) {
 		return { confidence: 0, result: content, strategy: "context" }
 	}
 
 	const newResult = [...content.slice(0, matchPosition)]
 	let sourceIndex = matchPosition
 
-  for (const change of hunk.changes) {
+	for (const change of hunk.changes) {
 		if (change.type === "context") {
 			// Use the original line from content if available
 			if (sourceIndex < content.length) {
@@ -82,20 +78,16 @@ export function applyContextMatching(
 
 	const confidence = validateEditResult(hunk, afterText)
 
-	return { 
+	return {
 		confidence,
 		result: newResult,
-		strategy: "context"
+		strategy: "context",
 	}
 }
 
 // DMP edit strategy
-export function applyDMP(
-	hunk: Hunk,
-	content: string[],
-	matchPosition: number,
-): EditResult {
-  if (matchPosition === -1) {
+export function applyDMP(hunk: Hunk, content: string[], matchPosition: number): EditResult {
+	if (matchPosition === -1) {
 		return { confidence: 0, result: content, strategy: "dmp" }
 	}
 
@@ -105,9 +97,9 @@ export function applyDMP(
 	const beforeLineCount = hunk.changes
 		.filter((change) => change.type === "context" || change.type === "remove")
 		.reduce((count, change) => count + change.content.split("\n").length, 0)
-  
-  // Build BEFORE block (context + removals)
-  const beforeLines = hunk.changes
+
+	// Build BEFORE block (context + removals)
+	const beforeLines = hunk.changes
 		.filter((change) => change.type === "context" || change.type === "remove")
 		.map((change) => {
 			if (change.originalLine) {
@@ -115,9 +107,9 @@ export function applyDMP(
 			}
 			return change.indent ? change.indent + change.content : change.content
 		})
-  
-  // Build AFTER block (context + additions)
-  const afterLines = hunk.changes
+
+	// Build AFTER block (context + additions)
+	const afterLines = hunk.changes
 		.filter((change) => change.type === "context" || change.type === "add")
 		.map((change) => {
 			if (change.originalLine) {
@@ -139,17 +131,17 @@ export function applyDMP(
 	const patchedLines = patchedText.split("\n")
 
 	// Construct final result
-  const newResult = [
-    ...content.slice(0, matchPosition),
-    ...patchedLines,
+	const newResult = [
+		...content.slice(0, matchPosition),
+		...patchedLines,
 		...content.slice(matchPosition + beforeLineCount),
 	]
-  
+
 	const confidence = validateEditResult(hunk, patchedText)
-  
-  return {
+
+	return {
 		confidence,
-    result: newResult,
+		result: newResult,
 		strategy: "dmp",
 	}
 }
@@ -171,7 +163,7 @@ export async function applyGitFallback(hunk: Hunk, content: string[]): Promise<E
 		const searchLines = hunk.changes
 			.filter((change) => change.type === "context" || change.type === "remove")
 			.map((change) => change.originalLine || change.indent + change.content)
-		
+
 		const replaceLines = hunk.changes
 			.filter((change) => change.type === "context" || change.type === "add")
 			.map((change) => change.originalLine || change.indent + change.content)
@@ -272,16 +264,16 @@ export async function applyGitFallback(hunk: Hunk, content: string[]): Promise<E
 
 // Main edit function that tries strategies sequentially
 export async function applyEdit(
-	hunk: Hunk, 
-	content: string[], 
-	matchPosition: number, 
+	hunk: Hunk,
+	content: string[],
+	matchPosition: number,
 	confidence: number,
-	confidenceThreshold: number = 0.97
+	confidenceThreshold: number = 0.97,
 ): Promise<EditResult> {
 	// Don't attempt regular edits if confidence is too low
 	if (confidence < confidenceThreshold) {
 		console.log(
-			`Search confidence (${confidence}) below minimum threshold (${confidenceThreshold}), trying git fallback...`
+			`Search confidence (${confidence}) below minimum threshold (${confidenceThreshold}), trying git fallback...`,
 		)
 		return applyGitFallback(hunk, content)
 	}

+ 5 - 5
src/core/diff/strategies/new-unified/index.ts

@@ -242,7 +242,7 @@ Your diff here
 		originalContent: string,
 		diffContent: string,
 		startLine?: number,
-		endLine?: number
+		endLine?: number,
 	): Promise<DiffResult> {
 		const parsedDiff = this.parseUnifiedDiff(diffContent)
 		const originalLines = originalContent.split("\n")
@@ -280,7 +280,7 @@ Your diff here
 							subHunkResult,
 							subSearchResult.index,
 							subSearchResult.confidence,
-							this.confidenceThreshold
+							this.confidenceThreshold,
 						)
 						if (subEditResult.confidence >= this.confidenceThreshold) {
 							subHunkResult = subEditResult.result
@@ -302,12 +302,12 @@ Your diff here
 				const contextRatio = contextLines / totalLines
 
 				let errorMsg = `Failed to find a matching location in the file (${Math.floor(
-					confidence * 100
+					confidence * 100,
 				)}% confidence, needs ${Math.floor(this.confidenceThreshold * 100)}%)\n\n`
 				errorMsg += "Debug Info:\n"
 				errorMsg += `- Search Strategy Used: ${strategy}\n`
 				errorMsg += `- Context Lines: ${contextLines} out of ${totalLines} total lines (${Math.floor(
-					contextRatio * 100
+					contextRatio * 100,
 				)}%)\n`
 				errorMsg += `- Attempted to split into ${subHunks.length} sub-hunks but still failed\n`
 
@@ -339,7 +339,7 @@ Your diff here
 			} else {
 				// Edit failure - likely due to content mismatch
 				let errorMsg = `Failed to apply the edit using ${editResult.strategy} strategy (${Math.floor(
-					editResult.confidence * 100
+					editResult.confidence * 100,
 				)}% confidence)\n\n`
 				errorMsg += "Debug Info:\n"
 				errorMsg += "- The location was found but the content didn't match exactly\n"

+ 20 - 20
src/core/diff/strategies/new-unified/search-strategies.ts

@@ -69,26 +69,26 @@ export function getDMPSimilarity(original: string, modified: string): number {
 export function validateEditResult(hunk: Hunk, result: string): number {
 	// Build the expected text from the hunk
 	const expectedText = hunk.changes
-		.filter(change => change.type === "context" || change.type === "add")
-		.map(change => change.indent ? change.indent + change.content : change.content)
-		.join("\n");
+		.filter((change) => change.type === "context" || change.type === "add")
+		.map((change) => (change.indent ? change.indent + change.content : change.content))
+		.join("\n")
 
 	// Calculate similarity between the result and expected text
-	const similarity = getDMPSimilarity(expectedText, result);
+	const similarity = getDMPSimilarity(expectedText, result)
 
 	// If the result is unchanged from original, return low confidence
 	const originalText = hunk.changes
-		.filter(change => change.type === "context" || change.type === "remove")
-		.map(change => change.indent ? change.indent + change.content : change.content)
-		.join("\n");
+		.filter((change) => change.type === "context" || change.type === "remove")
+		.map((change) => (change.indent ? change.indent + change.content : change.content))
+		.join("\n")
 
-	const originalSimilarity = getDMPSimilarity(originalText, result);
+	const originalSimilarity = getDMPSimilarity(originalText, result)
 	if (originalSimilarity > 0.97 && similarity !== 1) {
-		return 0.8 * similarity;  // Some confidence since we found the right location
+		return 0.8 * similarity // Some confidence since we found the right location
 	}
-  
+
 	// For partial matches, scale the confidence but keep it high if we're close
-	return similarity;
+	return similarity
 }
 
 // Helper function to validate context lines against original content
@@ -114,7 +114,7 @@ function validateContextLines(searchStr: string, content: string, confidenceThre
 function createOverlappingWindows(
 	content: string[],
 	searchSize: number,
-	overlapSize: number = DEFAULT_OVERLAP_SIZE
+	overlapSize: number = DEFAULT_OVERLAP_SIZE,
 ): { window: string[]; startIndex: number }[] {
 	const windows: { window: string[]; startIndex: number }[] = []
 
@@ -140,7 +140,7 @@ function createOverlappingWindows(
 // Helper function to combine overlapping matches
 function combineOverlappingMatches(
 	matches: (SearchResult & { windowIndex: number })[],
-	overlapSize: number = DEFAULT_OVERLAP_SIZE
+	overlapSize: number = DEFAULT_OVERLAP_SIZE,
 ): SearchResult[] {
 	if (matches.length === 0) {
 		return []
@@ -162,7 +162,7 @@ function combineOverlappingMatches(
 			(m) =>
 				Math.abs(m.windowIndex - match.windowIndex) === 1 &&
 				Math.abs(m.index - match.index) <= overlapSize &&
-				!usedIndices.has(m.windowIndex)
+				!usedIndices.has(m.windowIndex),
 		)
 
 		if (overlapping.length > 0) {
@@ -196,7 +196,7 @@ export function findExactMatch(
 	searchStr: string,
 	content: string[],
 	startIndex: number = 0,
-	confidenceThreshold: number = 0.97
+	confidenceThreshold: number = 0.97,
 ): SearchResult {
 	const searchLines = searchStr.split("\n")
 	const windows = createOverlappingWindows(content.slice(startIndex), searchLines.length)
@@ -210,7 +210,7 @@ export function findExactMatch(
 			const matchedContent = windowData.window
 				.slice(
 					windowStr.slice(0, exactMatch).split("\n").length - 1,
-					windowStr.slice(0, exactMatch).split("\n").length - 1 + searchLines.length
+					windowStr.slice(0, exactMatch).split("\n").length - 1 + searchLines.length,
 				)
 				.join("\n")
 
@@ -236,7 +236,7 @@ export function findSimilarityMatch(
 	searchStr: string,
 	content: string[],
 	startIndex: number = 0,
-	confidenceThreshold: number = 0.97
+	confidenceThreshold: number = 0.97,
 ): SearchResult {
 	const searchLines = searchStr.split("\n")
 	let bestScore = 0
@@ -269,7 +269,7 @@ export function findLevenshteinMatch(
 	searchStr: string,
 	content: string[],
 	startIndex: number = 0,
-	confidenceThreshold: number = 0.97
+	confidenceThreshold: number = 0.97,
 ): SearchResult {
 	const searchLines = searchStr.split("\n")
 	const candidates = []
@@ -324,7 +324,7 @@ export function findAnchorMatch(
 	searchStr: string,
 	content: string[],
 	startIndex: number = 0,
-	confidenceThreshold: number = 0.97
+	confidenceThreshold: number = 0.97,
 ): SearchResult {
 	const searchLines = searchStr.split("\n")
 	const { first, last } = identifyAnchors(searchStr)
@@ -391,7 +391,7 @@ export function findBestMatch(
 	searchStr: string,
 	content: string[],
 	startIndex: number = 0,
-	confidenceThreshold: number = 0.97
+	confidenceThreshold: number = 0.97,
 ): SearchResult {
 	const strategies = [findExactMatch, findAnchorMatch, findSimilarityMatch, findLevenshteinMatch]
 

+ 13 - 13
src/core/diff/strategies/new-unified/types.ts

@@ -1,20 +1,20 @@
 export type Change = {
-  type: 'context' | 'add' | 'remove';
-  content: string;
-  indent: string;
-  originalLine?: string;
-};
+	type: "context" | "add" | "remove"
+	content: string
+	indent: string
+	originalLine?: string
+}
 
 export type Hunk = {
-  changes: Change[];
-};
+	changes: Change[]
+}
 
 export type Diff = {
-  hunks: Hunk[];
-}; 
+	hunks: Hunk[]
+}
 
 export type EditResult = {
-  confidence: number;
-  result: string[];
-  strategy: string;
-};
+	confidence: number
+	result: string[]
+	strategy: string
+}

+ 261 - 248
src/core/diff/strategies/search-replace.ts

@@ -1,72 +1,74 @@
 import { DiffStrategy, DiffResult } from "../types"
 import { addLineNumbers, everyLineHasLineNumbers, stripLineNumbers } from "../../../integrations/misc/extract-text"
 
-const BUFFER_LINES = 20; // Number of extra context lines to show before and after matches
+const BUFFER_LINES = 20 // Number of extra context lines to show before and after matches
 
 function levenshteinDistance(a: string, b: string): number {
-    const matrix: number[][] = [];
-
-    // Initialize matrix
-    for (let i = 0; i <= a.length; i++) {
-        matrix[i] = [i];
-    }
-    for (let j = 0; j <= b.length; j++) {
-        matrix[0][j] = j;
-    }
-
-    // Fill matrix
-    for (let i = 1; i <= a.length; i++) {
-        for (let j = 1; j <= b.length; j++) {
-            if (a[i-1] === b[j-1]) {
-                matrix[i][j] = matrix[i-1][j-1];
-            } else {
-                matrix[i][j] = Math.min(
-                    matrix[i-1][j-1] + 1, // substitution
-                    matrix[i][j-1] + 1,   // insertion
-                    matrix[i-1][j] + 1    // deletion
-                );
-            }
-        }
-    }
-
-    return matrix[a.length][b.length];
+	const matrix: number[][] = []
+
+	// Initialize matrix
+	for (let i = 0; i <= a.length; i++) {
+		matrix[i] = [i]
+	}
+	for (let j = 0; j <= b.length; j++) {
+		matrix[0][j] = j
+	}
+
+	// Fill matrix
+	for (let i = 1; i <= a.length; i++) {
+		for (let j = 1; j <= b.length; j++) {
+			if (a[i - 1] === b[j - 1]) {
+				matrix[i][j] = matrix[i - 1][j - 1]
+			} else {
+				matrix[i][j] = Math.min(
+					matrix[i - 1][j - 1] + 1, // substitution
+					matrix[i][j - 1] + 1, // insertion
+					matrix[i - 1][j] + 1, // deletion
+				)
+			}
+		}
+	}
+
+	return matrix[a.length][b.length]
 }
 
 function getSimilarity(original: string, search: string): number {
-    if (search === '') {
-        return 1;
-    }
-
-    // Normalize strings by removing extra whitespace but preserve case
-    const normalizeStr = (str: string) => str.replace(/\s+/g, ' ').trim();
-    
-    const normalizedOriginal = normalizeStr(original);
-    const normalizedSearch = normalizeStr(search);
-    
-    if (normalizedOriginal === normalizedSearch) { return 1; }
-    
-    // Calculate Levenshtein distance
-    const distance = levenshteinDistance(normalizedOriginal, normalizedSearch);
-    
-    // Calculate similarity ratio (0 to 1, where 1 is exact match)
-    const maxLength = Math.max(normalizedOriginal.length, normalizedSearch.length);
-    return 1 - (distance / maxLength);
+	if (search === "") {
+		return 1
+	}
+
+	// Normalize strings by removing extra whitespace but preserve case
+	const normalizeStr = (str: string) => str.replace(/\s+/g, " ").trim()
+
+	const normalizedOriginal = normalizeStr(original)
+	const normalizedSearch = normalizeStr(search)
+
+	if (normalizedOriginal === normalizedSearch) {
+		return 1
+	}
+
+	// Calculate Levenshtein distance
+	const distance = levenshteinDistance(normalizedOriginal, normalizedSearch)
+
+	// Calculate similarity ratio (0 to 1, where 1 is exact match)
+	const maxLength = Math.max(normalizedOriginal.length, normalizedSearch.length)
+	return 1 - distance / maxLength
 }
 
 export class SearchReplaceDiffStrategy implements DiffStrategy {
-    private fuzzyThreshold: number;
-    private bufferLines: number;
-
-    constructor(fuzzyThreshold?: number, bufferLines?: number) {
-        // Use provided threshold or default to exact matching (1.0)
-        // Note: fuzzyThreshold is inverted in UI (0% = 1.0, 10% = 0.9)
-        // so we use it directly here
-        this.fuzzyThreshold = fuzzyThreshold ?? 1.0;
-        this.bufferLines = bufferLines ?? BUFFER_LINES;
-    }
-
-    getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string {
-        return `## apply_diff
+	private fuzzyThreshold: number
+	private bufferLines: number
+
+	constructor(fuzzyThreshold?: number, bufferLines?: number) {
+		// Use provided threshold or default to exact matching (1.0)
+		// Note: fuzzyThreshold is inverted in UI (0% = 1.0, 10% = 0.9)
+		// so we use it directly here
+		this.fuzzyThreshold = fuzzyThreshold ?? 1.0
+		this.bufferLines = bufferLines ?? BUFFER_LINES
+	}
+
+	getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string {
+		return `## apply_diff
 Description: Request to replace existing code using a search and replace block.
 This tool allows for precise, surgical replaces to files by specifying exactly what content to search for and what to replace it with.
 The tool will maintain proper indentation and formatting while making changes.
@@ -125,193 +127,204 @@ Your search/replace content here
 <start_line>1</start_line>
 <end_line>5</end_line>
 </apply_diff>`
-    }
-
-    async applyDiff(originalContent: string, diffContent: string, startLine?: number, endLine?: number): Promise<DiffResult> {
-        // Extract the search and replace blocks
-        const match = diffContent.match(/<<<<<<< SEARCH\n([\s\S]*?)\n?=======\n([\s\S]*?)\n?>>>>>>> REPLACE/);
-        if (!match) {
-            return {
-                success: false,
-                error: `Invalid diff format - missing required SEARCH/REPLACE sections\n\nDebug Info:\n- Expected Format: <<<<<<< SEARCH\\n[search content]\\n=======\\n[replace content]\\n>>>>>>> REPLACE\n- Tip: Make sure to include both SEARCH and REPLACE sections with correct markers`
-            };
-        }
-
-        let [_, searchContent, replaceContent] = match;
-
-        // Detect line ending from original content
-        const lineEnding = originalContent.includes('\r\n') ? '\r\n' : '\n';
-
-        // Strip line numbers from search and replace content if every line starts with a line number
-        if (everyLineHasLineNumbers(searchContent) && everyLineHasLineNumbers(replaceContent)) {
-            searchContent = stripLineNumbers(searchContent);
-            replaceContent = stripLineNumbers(replaceContent);
-        }
-        
-        // Split content into lines, handling both \n and \r\n
-        const searchLines = searchContent === '' ? [] : searchContent.split(/\r?\n/);
-        const replaceLines = replaceContent === '' ? [] : replaceContent.split(/\r?\n/);
-        const originalLines = originalContent.split(/\r?\n/);
-
-        // Validate that empty search requires start line
-        if (searchLines.length === 0 && !startLine) {
-            return {
-                success: false,
-                error: `Empty search content requires start_line to be specified\n\nDebug Info:\n- Empty search content is only valid for insertions at a specific line\n- For insertions, specify the line number where content should be inserted`
-            };
-        }
-
-        // Validate that empty search requires same start and end line
-        if (searchLines.length === 0 && startLine && endLine && startLine !== endLine) {
-            return {
-                success: false,
-                error: `Empty search content requires start_line and end_line to be the same (got ${startLine}-${endLine})\n\nDebug Info:\n- Empty search content is only valid for insertions at a specific line\n- For insertions, use the same line number for both start_line and end_line`
-            };
-        }
-        
-        // Initialize search variables
-        let matchIndex = -1;
-        let bestMatchScore = 0;
-        let bestMatchContent = "";
-        const searchChunk = searchLines.join('\n');
-
-        // Determine search bounds
-        let searchStartIndex = 0;
-        let searchEndIndex = originalLines.length;
-
-        // Validate and handle line range if provided
-        if (startLine && endLine) {
-            // Convert to 0-based index
-            const exactStartIndex = startLine - 1;
-            const exactEndIndex = endLine - 1;
-
-            if (exactStartIndex < 0 || exactEndIndex > originalLines.length || exactStartIndex > exactEndIndex) {
-                return {
-                    success: false,
-                    error: `Line range ${startLine}-${endLine} is invalid (file has ${originalLines.length} lines)\n\nDebug Info:\n- Requested Range: lines ${startLine}-${endLine}\n- File Bounds: lines 1-${originalLines.length}`,
-                };
-            }
-
-            // Try exact match first
-            const originalChunk = originalLines.slice(exactStartIndex, exactEndIndex + 1).join('\n');
-            const similarity = getSimilarity(originalChunk, searchChunk);
-            if (similarity >= this.fuzzyThreshold) {
-                matchIndex = exactStartIndex;
-                bestMatchScore = similarity;
-                bestMatchContent = originalChunk;
-            } else {
-                // Set bounds for buffered search
-                searchStartIndex = Math.max(0, startLine - (this.bufferLines + 1));
-                searchEndIndex = Math.min(originalLines.length, endLine + this.bufferLines);
-            }
-        }
-
-        // If no match found yet, try middle-out search within bounds
-        if (matchIndex === -1) {
-            const midPoint = Math.floor((searchStartIndex + searchEndIndex) / 2);
-            let leftIndex = midPoint;
-            let rightIndex = midPoint + 1;
-
-            // Search outward from the middle within bounds
-            while (leftIndex >= searchStartIndex || rightIndex <= searchEndIndex - searchLines.length) {
-                // Check left side if still in range
-                if (leftIndex >= searchStartIndex) {
-                    const originalChunk = originalLines.slice(leftIndex, leftIndex + searchLines.length).join('\n');
-                    const similarity = getSimilarity(originalChunk, searchChunk);
-                    if (similarity > bestMatchScore) {
-                        bestMatchScore = similarity;
-                        matchIndex = leftIndex;
-                        bestMatchContent = originalChunk;
-                    }
-                    leftIndex--;
-                }
-
-                // Check right side if still in range
-                if (rightIndex <= searchEndIndex - searchLines.length) {
-                    const originalChunk = originalLines.slice(rightIndex, rightIndex + searchLines.length).join('\n');
-                    const similarity = getSimilarity(originalChunk, searchChunk);
-                    if (similarity > bestMatchScore) {
-                        bestMatchScore = similarity;
-                        matchIndex = rightIndex;
-                        bestMatchContent = originalChunk;
-                    }
-                    rightIndex++;
-                }
-            }
-        }
-
-        // Require similarity to meet threshold
-        if (matchIndex === -1 || bestMatchScore < this.fuzzyThreshold) {
-            const searchChunk = searchLines.join('\n');
-            const originalContentSection = startLine !== undefined && endLine !== undefined
-                ? `\n\nOriginal Content:\n${addLineNumbers(
-                    originalLines.slice(
-                        Math.max(0, startLine - 1 - this.bufferLines),
-                        Math.min(originalLines.length, endLine + this.bufferLines)
-                    ).join('\n'),
-                    Math.max(1, startLine - this.bufferLines)
-                )}`
-                : `\n\nOriginal Content:\n${addLineNumbers(originalLines.join('\n'))}`;
-
-            const bestMatchSection = bestMatchContent
-                ? `\n\nBest Match Found:\n${addLineNumbers(bestMatchContent, matchIndex + 1)}`
-                : `\n\nBest Match Found:\n(no match)`;
-
-            const lineRange = startLine || endLine ?
-                ` at ${startLine ? `start: ${startLine}` : 'start'} to ${endLine ? `end: ${endLine}` : 'end'}` : '';
-            return {
-                success: false,
-                error: `No sufficiently similar match found${lineRange} (${Math.floor(bestMatchScore * 100)}% similar, needs ${Math.floor(this.fuzzyThreshold * 100)}%)\n\nDebug Info:\n- Similarity Score: ${Math.floor(bestMatchScore * 100)}%\n- Required Threshold: ${Math.floor(this.fuzzyThreshold * 100)}%\n- Search Range: ${startLine && endLine ? `lines ${startLine}-${endLine}` : 'start to end'}\n\nSearch Content:\n${searchChunk}${bestMatchSection}${originalContentSection}`
-            };
-        }
-
-        // Get the matched lines from the original content
-        const matchedLines = originalLines.slice(matchIndex, matchIndex + searchLines.length);
-        
-        // Get the exact indentation (preserving tabs/spaces) of each line
-        const originalIndents = matchedLines.map(line => {
-            const match = line.match(/^[\t ]*/);
-            return match ? match[0] : '';
-        });
-
-        // Get the exact indentation of each line in the search block
-        const searchIndents = searchLines.map(line => {
-            const match = line.match(/^[\t ]*/);
-            return match ? match[0] : '';
-        });
-
-        // Apply the replacement while preserving exact indentation
-        const indentedReplaceLines = replaceLines.map((line, i) => {
-            // Get the matched line's exact indentation
-            const matchedIndent = originalIndents[0] || '';
-            
-            // Get the current line's indentation relative to the search content
-            const currentIndentMatch = line.match(/^[\t ]*/);
-            const currentIndent = currentIndentMatch ? currentIndentMatch[0] : '';
-            const searchBaseIndent = searchIndents[0] || '';
-            
-            // Calculate the relative indentation level
-            const searchBaseLevel = searchBaseIndent.length;
-            const currentLevel = currentIndent.length;
-            const relativeLevel = currentLevel - searchBaseLevel;
-            
-            // If relative level is negative, remove indentation from matched indent
-            // If positive, add to matched indent
-            const finalIndent = relativeLevel < 0
-                ? matchedIndent.slice(0, Math.max(0, matchedIndent.length + relativeLevel))
-                : matchedIndent + currentIndent.slice(searchBaseLevel);
-            
-            return finalIndent + line.trim();
-        });
-
-        // Construct the final content
-        const beforeMatch = originalLines.slice(0, matchIndex);
-        const afterMatch = originalLines.slice(matchIndex + searchLines.length);
-        
-        const finalContent = [...beforeMatch, ...indentedReplaceLines, ...afterMatch].join(lineEnding);
-        return {
-            success: true,
-            content: finalContent
-        };
-    }
-}
+	}
+
+	async applyDiff(
+		originalContent: string,
+		diffContent: string,
+		startLine?: number,
+		endLine?: number,
+	): Promise<DiffResult> {
+		// Extract the search and replace blocks
+		const match = diffContent.match(/<<<<<<< SEARCH\n([\s\S]*?)\n?=======\n([\s\S]*?)\n?>>>>>>> REPLACE/)
+		if (!match) {
+			return {
+				success: false,
+				error: `Invalid diff format - missing required SEARCH/REPLACE sections\n\nDebug Info:\n- Expected Format: <<<<<<< SEARCH\\n[search content]\\n=======\\n[replace content]\\n>>>>>>> REPLACE\n- Tip: Make sure to include both SEARCH and REPLACE sections with correct markers`,
+			}
+		}
+
+		let [_, searchContent, replaceContent] = match
+
+		// Detect line ending from original content
+		const lineEnding = originalContent.includes("\r\n") ? "\r\n" : "\n"
+
+		// Strip line numbers from search and replace content if every line starts with a line number
+		if (everyLineHasLineNumbers(searchContent) && everyLineHasLineNumbers(replaceContent)) {
+			searchContent = stripLineNumbers(searchContent)
+			replaceContent = stripLineNumbers(replaceContent)
+		}
+
+		// Split content into lines, handling both \n and \r\n
+		const searchLines = searchContent === "" ? [] : searchContent.split(/\r?\n/)
+		const replaceLines = replaceContent === "" ? [] : replaceContent.split(/\r?\n/)
+		const originalLines = originalContent.split(/\r?\n/)
+
+		// Validate that empty search requires start line
+		if (searchLines.length === 0 && !startLine) {
+			return {
+				success: false,
+				error: `Empty search content requires start_line to be specified\n\nDebug Info:\n- Empty search content is only valid for insertions at a specific line\n- For insertions, specify the line number where content should be inserted`,
+			}
+		}
+
+		// Validate that empty search requires same start and end line
+		if (searchLines.length === 0 && startLine && endLine && startLine !== endLine) {
+			return {
+				success: false,
+				error: `Empty search content requires start_line and end_line to be the same (got ${startLine}-${endLine})\n\nDebug Info:\n- Empty search content is only valid for insertions at a specific line\n- For insertions, use the same line number for both start_line and end_line`,
+			}
+		}
+
+		// Initialize search variables
+		let matchIndex = -1
+		let bestMatchScore = 0
+		let bestMatchContent = ""
+		const searchChunk = searchLines.join("\n")
+
+		// Determine search bounds
+		let searchStartIndex = 0
+		let searchEndIndex = originalLines.length
+
+		// Validate and handle line range if provided
+		if (startLine && endLine) {
+			// Convert to 0-based index
+			const exactStartIndex = startLine - 1
+			const exactEndIndex = endLine - 1
+
+			if (exactStartIndex < 0 || exactEndIndex > originalLines.length || exactStartIndex > exactEndIndex) {
+				return {
+					success: false,
+					error: `Line range ${startLine}-${endLine} is invalid (file has ${originalLines.length} lines)\n\nDebug Info:\n- Requested Range: lines ${startLine}-${endLine}\n- File Bounds: lines 1-${originalLines.length}`,
+				}
+			}
+
+			// Try exact match first
+			const originalChunk = originalLines.slice(exactStartIndex, exactEndIndex + 1).join("\n")
+			const similarity = getSimilarity(originalChunk, searchChunk)
+			if (similarity >= this.fuzzyThreshold) {
+				matchIndex = exactStartIndex
+				bestMatchScore = similarity
+				bestMatchContent = originalChunk
+			} else {
+				// Set bounds for buffered search
+				searchStartIndex = Math.max(0, startLine - (this.bufferLines + 1))
+				searchEndIndex = Math.min(originalLines.length, endLine + this.bufferLines)
+			}
+		}
+
+		// If no match found yet, try middle-out search within bounds
+		if (matchIndex === -1) {
+			const midPoint = Math.floor((searchStartIndex + searchEndIndex) / 2)
+			let leftIndex = midPoint
+			let rightIndex = midPoint + 1
+
+			// Search outward from the middle within bounds
+			while (leftIndex >= searchStartIndex || rightIndex <= searchEndIndex - searchLines.length) {
+				// Check left side if still in range
+				if (leftIndex >= searchStartIndex) {
+					const originalChunk = originalLines.slice(leftIndex, leftIndex + searchLines.length).join("\n")
+					const similarity = getSimilarity(originalChunk, searchChunk)
+					if (similarity > bestMatchScore) {
+						bestMatchScore = similarity
+						matchIndex = leftIndex
+						bestMatchContent = originalChunk
+					}
+					leftIndex--
+				}
+
+				// Check right side if still in range
+				if (rightIndex <= searchEndIndex - searchLines.length) {
+					const originalChunk = originalLines.slice(rightIndex, rightIndex + searchLines.length).join("\n")
+					const similarity = getSimilarity(originalChunk, searchChunk)
+					if (similarity > bestMatchScore) {
+						bestMatchScore = similarity
+						matchIndex = rightIndex
+						bestMatchContent = originalChunk
+					}
+					rightIndex++
+				}
+			}
+		}
+
+		// Require similarity to meet threshold
+		if (matchIndex === -1 || bestMatchScore < this.fuzzyThreshold) {
+			const searchChunk = searchLines.join("\n")
+			const originalContentSection =
+				startLine !== undefined && endLine !== undefined
+					? `\n\nOriginal Content:\n${addLineNumbers(
+							originalLines
+								.slice(
+									Math.max(0, startLine - 1 - this.bufferLines),
+									Math.min(originalLines.length, endLine + this.bufferLines),
+								)
+								.join("\n"),
+							Math.max(1, startLine - this.bufferLines),
+						)}`
+					: `\n\nOriginal Content:\n${addLineNumbers(originalLines.join("\n"))}`
+
+			const bestMatchSection = bestMatchContent
+				? `\n\nBest Match Found:\n${addLineNumbers(bestMatchContent, matchIndex + 1)}`
+				: `\n\nBest Match Found:\n(no match)`
+
+			const lineRange =
+				startLine || endLine
+					? ` at ${startLine ? `start: ${startLine}` : "start"} to ${endLine ? `end: ${endLine}` : "end"}`
+					: ""
+			return {
+				success: false,
+				error: `No sufficiently similar match found${lineRange} (${Math.floor(bestMatchScore * 100)}% similar, needs ${Math.floor(this.fuzzyThreshold * 100)}%)\n\nDebug Info:\n- Similarity Score: ${Math.floor(bestMatchScore * 100)}%\n- Required Threshold: ${Math.floor(this.fuzzyThreshold * 100)}%\n- Search Range: ${startLine && endLine ? `lines ${startLine}-${endLine}` : "start to end"}\n\nSearch Content:\n${searchChunk}${bestMatchSection}${originalContentSection}`,
+			}
+		}
+
+		// Get the matched lines from the original content
+		const matchedLines = originalLines.slice(matchIndex, matchIndex + searchLines.length)
+
+		// Get the exact indentation (preserving tabs/spaces) of each line
+		const originalIndents = matchedLines.map((line) => {
+			const match = line.match(/^[\t ]*/)
+			return match ? match[0] : ""
+		})
+
+		// Get the exact indentation of each line in the search block
+		const searchIndents = searchLines.map((line) => {
+			const match = line.match(/^[\t ]*/)
+			return match ? match[0] : ""
+		})
+
+		// Apply the replacement while preserving exact indentation
+		const indentedReplaceLines = replaceLines.map((line, i) => {
+			// Get the matched line's exact indentation
+			const matchedIndent = originalIndents[0] || ""
+
+			// Get the current line's indentation relative to the search content
+			const currentIndentMatch = line.match(/^[\t ]*/)
+			const currentIndent = currentIndentMatch ? currentIndentMatch[0] : ""
+			const searchBaseIndent = searchIndents[0] || ""
+
+			// Calculate the relative indentation level
+			const searchBaseLevel = searchBaseIndent.length
+			const currentLevel = currentIndent.length
+			const relativeLevel = currentLevel - searchBaseLevel
+
+			// If relative level is negative, remove indentation from matched indent
+			// If positive, add to matched indent
+			const finalIndent =
+				relativeLevel < 0
+					? matchedIndent.slice(0, Math.max(0, matchedIndent.length + relativeLevel))
+					: matchedIndent + currentIndent.slice(searchBaseLevel)
+
+			return finalIndent + line.trim()
+		})
+
+		// Construct the final content
+		const beforeMatch = originalLines.slice(0, matchIndex)
+		const afterMatch = originalLines.slice(matchIndex + searchLines.length)
+
+		const finalContent = [...beforeMatch, ...indentedReplaceLines, ...afterMatch].join(lineEnding)
+		return {
+			success: true,
+			content: finalContent,
+		}
+	}
+}

+ 29 - 29
src/core/diff/strategies/unified.ts

@@ -2,8 +2,8 @@ import { applyPatch } from "diff"
 import { DiffStrategy, DiffResult } from "../types"
 
 export class UnifiedDiffStrategy implements DiffStrategy {
-    getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string {
-        return `## apply_diff
+	getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string {
+		return `## apply_diff
 Description: Apply a unified diff to a file at the specified path. This tool is useful when you need to make specific modifications to a file based on a set of changes provided in unified diff format (diff -U3).
 
 Parameters:
@@ -106,32 +106,32 @@ Usage:
 Your diff here
 </diff>
 </apply_diff>`
-    }
+	}
 
-    async applyDiff(originalContent: string, diffContent: string): Promise<DiffResult> {
-        try {
-            const result = applyPatch(originalContent, diffContent)
-            if (result === false) {
-                return {
-                    success: false,
-                    error: "Failed to apply unified diff - patch rejected",
-                    details: {
-                        searchContent: diffContent
-                    }
-                }
-            }
-            return {
-                success: true,
-                content: result
-            }
-        } catch (error) {
-            return {
-                success: false,
-                error: `Error applying unified diff: ${error.message}`,
-                details: {
-                    searchContent: diffContent
-                }
-            }
-        }
-    }
+	async applyDiff(originalContent: string, diffContent: string): Promise<DiffResult> {
+		try {
+			const result = applyPatch(originalContent, diffContent)
+			if (result === false) {
+				return {
+					success: false,
+					error: "Failed to apply unified diff - patch rejected",
+					details: {
+						searchContent: diffContent,
+					},
+				}
+			}
+			return {
+				success: true,
+				content: result,
+			}
+		} catch (error) {
+			return {
+				success: false,
+				error: `Error applying unified diff: ${error.message}`,
+				details: {
+					searchContent: diffContent,
+				},
+			}
+		}
+	}
 }

+ 29 - 25
src/core/diff/types.ts

@@ -2,31 +2,35 @@
  * Interface for implementing different diff strategies
  */
 
-export type DiffResult = 
-  | { success: true; content: string }
-  | { success: false; error: string; details?: { 
-      similarity?: number;
-      threshold?: number;
-      matchedRange?: { start: number; end: number };
-      searchContent?: string;
-      bestMatch?: string;
-    }};
+export type DiffResult =
+	| { success: true; content: string }
+	| {
+			success: false
+			error: string
+			details?: {
+				similarity?: number
+				threshold?: number
+				matchedRange?: { start: number; end: number }
+				searchContent?: string
+				bestMatch?: string
+			}
+	  }
 
 export interface DiffStrategy {
-    /**
-     * Get the tool description for this diff strategy
-     * @param args The tool arguments including cwd and toolOptions
-     * @returns The complete tool description including format requirements and examples
-     */
-    getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string
+	/**
+	 * Get the tool description for this diff strategy
+	 * @param args The tool arguments including cwd and toolOptions
+	 * @returns The complete tool description including format requirements and examples
+	 */
+	getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string
 
-    /**
-     * Apply a diff to the original content
-     * @param originalContent The original file content
-     * @param diffContent The diff content in the strategy's format
-     * @param startLine Optional line number where the search block starts. If not provided, searches the entire file.
-     * @param endLine Optional line number where the search block ends. If not provided, searches the entire file.
-     * @returns A DiffResult object containing either the successful result or error details
-     */
-    applyDiff(originalContent: string, diffContent: string, startLine?: number, endLine?: number): Promise<DiffResult>
-}
+	/**
+	 * Apply a diff to the original content
+	 * @param originalContent The original file content
+	 * @param diffContent The diff content in the strategy's format
+	 * @param startLine Optional line number where the search block starts. If not provided, searches the entire file.
+	 * @param endLine Optional line number where the search block ends. If not provided, searches the entire file.
+	 * @returns A DiffResult object containing either the successful result or error details
+	 */
+	applyDiff(originalContent: string, diffContent: string, startLine?: number, endLine?: number): Promise<DiffResult>
+}

+ 35 - 39
src/core/mentions/__tests__/index.test.ts

@@ -1,20 +1,20 @@
 // Create mock vscode module before importing anything
 const createMockUri = (scheme: string, path: string) => ({
 	scheme,
-	authority: '',
+	authority: "",
 	path,
-	query: '',
-	fragment: '',
+	query: "",
+	fragment: "",
 	fsPath: path,
 	with: jest.fn(),
 	toString: () => path,
 	toJSON: () => ({
 		scheme,
-		authority: '',
+		authority: "",
 		path,
-		query: '',
-		fragment: ''
-	})
+		query: "",
+		fragment: "",
+	}),
 })
 
 const mockExecuteCommand = jest.fn()
@@ -23,9 +23,11 @@ const mockShowErrorMessage = jest.fn()
 
 const mockVscode = {
 	workspace: {
-		workspaceFolders: [{
-			uri: { fsPath: "/test/workspace" }
-		}]
+		workspaceFolders: [
+			{
+				uri: { fsPath: "/test/workspace" },
+			},
+		],
 	},
 	window: {
 		showErrorMessage: mockShowErrorMessage,
@@ -34,17 +36,17 @@ const mockVscode = {
 		createTextEditorDecorationType: jest.fn(),
 		createOutputChannel: jest.fn(),
 		createWebviewPanel: jest.fn(),
-		activeTextEditor: undefined
+		activeTextEditor: undefined,
 	},
 	commands: {
-		executeCommand: mockExecuteCommand
+		executeCommand: mockExecuteCommand,
 	},
 	env: {
-		openExternal: mockOpenExternal
+		openExternal: mockOpenExternal,
 	},
 	Uri: {
-		parse: jest.fn((url: string) => createMockUri('https', url)),
-		file: jest.fn((path: string) => createMockUri('file', path))
+		parse: jest.fn((url: string) => createMockUri("https", url)),
+		file: jest.fn((path: string) => createMockUri("file", path)),
 	},
 	Position: jest.fn(),
 	Range: jest.fn(),
@@ -54,12 +56,12 @@ const mockVscode = {
 		Error: 0,
 		Warning: 1,
 		Information: 2,
-		Hint: 3
-	}
+		Hint: 3,
+	},
 }
 
 // Mock modules
-jest.mock('vscode', () => mockVscode)
+jest.mock("vscode", () => mockVscode)
 jest.mock("../../../services/browser/UrlContentFetcher")
 jest.mock("../../../utils/git")
 
@@ -74,7 +76,7 @@ describe("mentions", () => {
 
 	beforeEach(() => {
 		jest.clearAllMocks()
-		
+
 		// Create a mock instance with just the methods we need
 		mockUrlContentFetcher = {
 			launchBrowser: jest.fn().mockResolvedValue(undefined),
@@ -94,14 +96,10 @@ Date: Mon Jan 5 23:50:06 2025 -0500
 Detailed commit message with multiple lines
 - Fixed parsing issue
 - Added tests`
-			
+
 			jest.mocked(git.getCommitInfo).mockResolvedValue(commitInfo)
 
-			const result = await parseMentions(
-				`Check out this commit @${commitHash}`,
-				mockCwd,
-				mockUrlContentFetcher
-			)
+			const result = await parseMentions(`Check out this commit @${commitHash}`, mockCwd, mockUrlContentFetcher)
 
 			expect(result).toContain(`'${commitHash}' (see below for commit info)`)
 			expect(result).toContain(`<git_commit hash="${commitHash}">`)
@@ -111,14 +109,10 @@ Detailed commit message with multiple lines
 		it("should handle errors fetching git info", async () => {
 			const commitHash = "abc1234"
 			const errorMessage = "Failed to get commit info"
-			
+
 			jest.mocked(git.getCommitInfo).mockRejectedValue(new Error(errorMessage))
 
-			const result = await parseMentions(
-				`Check out this commit @${commitHash}`,
-				mockCwd,
-				mockUrlContentFetcher
-			)
+			const result = await parseMentions(`Check out this commit @${commitHash}`, mockCwd, mockUrlContentFetcher)
 
 			expect(result).toContain(`'${commitHash}' (see below for commit info)`)
 			expect(result).toContain(`<git_commit hash="${commitHash}">`)
@@ -143,13 +137,15 @@ Detailed commit message with multiple lines
 			const mockUri = mockVscode.Uri.parse(url)
 			expect(mockOpenExternal).toHaveBeenCalled()
 			const calledArg = mockOpenExternal.mock.calls[0][0]
-			expect(calledArg).toEqual(expect.objectContaining({
-				scheme: mockUri.scheme,
-				authority: mockUri.authority,
-				path: mockUri.path,
-				query: mockUri.query,
-				fragment: mockUri.fragment
-			}))
+			expect(calledArg).toEqual(
+				expect.objectContaining({
+					scheme: mockUri.scheme,
+					authority: mockUri.authority,
+					path: mockUri.path,
+					query: mockUri.query,
+					fragment: mockUri.fragment,
+				}),
+			)
 		})
 	})
-})
+})

+ 7 - 9
src/core/mode-validator.ts

@@ -1,12 +1,10 @@
-import { Mode, isToolAllowedForMode, TestToolName, getModeConfig } from '../shared/modes';
+import { Mode, isToolAllowedForMode, TestToolName, getModeConfig } from "../shared/modes"
 
-export { isToolAllowedForMode };
-export type { TestToolName };
+export { isToolAllowedForMode }
+export type { TestToolName }
 
 export function validateToolUse(toolName: TestToolName, mode: Mode): void {
-    if (!isToolAllowedForMode(toolName, mode)) {
-        throw new Error(
-            `Tool "${toolName}" is not allowed in ${mode} mode.`
-        );
-    }
-}
+	if (!isToolAllowedForMode(toolName, mode)) {
+		throw new Error(`Tool "${toolName}" is not allowed in ${mode} mode.`)
+	}
+}

+ 339 - 404
src/core/prompts/__tests__/system.test.ts

@@ -1,422 +1,357 @@
-import { SYSTEM_PROMPT, addCustomInstructions } from '../system'
-import { McpHub } from '../../../services/mcp/McpHub'
-import { McpServer } from '../../../shared/mcp'
-import { ClineProvider } from '../../../core/webview/ClineProvider'
-import { SearchReplaceDiffStrategy } from '../../../core/diff/strategies/search-replace'
-import fs from 'fs/promises'
-import os from 'os'
-import { defaultModeSlug, modes } from '../../../shared/modes'
+import { SYSTEM_PROMPT, addCustomInstructions } from "../system"
+import { McpHub } from "../../../services/mcp/McpHub"
+import { McpServer } from "../../../shared/mcp"
+import { ClineProvider } from "../../../core/webview/ClineProvider"
+import { SearchReplaceDiffStrategy } from "../../../core/diff/strategies/search-replace"
+import fs from "fs/promises"
+import os from "os"
+import { defaultModeSlug, modes } from "../../../shared/modes"
 // Import path utils to get access to toPosix string extension
-import '../../../utils/path'
+import "../../../utils/path"
 
 // Mock environment-specific values for consistent tests
-jest.mock('os', () => ({
-  ...jest.requireActual('os'),
-  homedir: () => '/home/user'
+jest.mock("os", () => ({
+	...jest.requireActual("os"),
+	homedir: () => "/home/user",
 }))
 
-jest.mock('default-shell', () => '/bin/bash')
+jest.mock("default-shell", () => "/bin/bash")
 
-jest.mock('os-name', () => () => 'Linux')
+jest.mock("os-name", () => () => "Linux")
 
 // Mock fs.readFile to return empty mcpServers config and mock rules files
-jest.mock('fs/promises', () => ({
-  ...jest.requireActual('fs/promises'),
-  readFile: jest.fn().mockImplementation(async (path: string) => {
-    if (path.endsWith('mcpSettings.json')) {
-      return '{"mcpServers": {}}'
-    }
-    if (path.endsWith('.clinerules-code')) {
-      return '# Code Mode Rules\n1. Code specific rule'
-    }
-    if (path.endsWith('.clinerules-ask')) {
-      return '# Ask Mode Rules\n1. Ask specific rule'
-    }
-    if (path.endsWith('.clinerules-architect')) {
-      return '# Architect Mode Rules\n1. Architect specific rule'
-    }
-    if (path.endsWith('.clinerules')) {
-      return '# Test Rules\n1. First rule\n2. Second rule'
-    }
-    return ''
-  }),
-  writeFile: jest.fn().mockResolvedValue(undefined)
+jest.mock("fs/promises", () => ({
+	...jest.requireActual("fs/promises"),
+	readFile: jest.fn().mockImplementation(async (path: string) => {
+		if (path.endsWith("mcpSettings.json")) {
+			return '{"mcpServers": {}}'
+		}
+		if (path.endsWith(".clinerules-code")) {
+			return "# Code Mode Rules\n1. Code specific rule"
+		}
+		if (path.endsWith(".clinerules-ask")) {
+			return "# Ask Mode Rules\n1. Ask specific rule"
+		}
+		if (path.endsWith(".clinerules-architect")) {
+			return "# Architect Mode Rules\n1. Architect specific rule"
+		}
+		if (path.endsWith(".clinerules")) {
+			return "# Test Rules\n1. First rule\n2. Second rule"
+		}
+		return ""
+	}),
+	writeFile: jest.fn().mockResolvedValue(undefined),
 }))
 
 // Create a minimal mock of ClineProvider
 const mockProvider = {
-  ensureMcpServersDirectoryExists: async () => '/mock/mcp/path',
-  ensureSettingsDirectoryExists: async () => '/mock/settings/path',
-  postMessageToWebview: async () => {},
-  context: {
-    extension: {
-      packageJSON: {
-        version: '1.0.0'
-      }
-    }
-  }
+	ensureMcpServersDirectoryExists: async () => "/mock/mcp/path",
+	ensureSettingsDirectoryExists: async () => "/mock/settings/path",
+	postMessageToWebview: async () => {},
+	context: {
+		extension: {
+			packageJSON: {
+				version: "1.0.0",
+			},
+		},
+	},
 } as unknown as ClineProvider
 
 // Instead of extending McpHub, create a mock that implements just what we need
-const createMockMcpHub = (): McpHub => ({
-  getServers: () => [],
-  getMcpServersPath: async () => '/mock/mcp/path',
-  getMcpSettingsFilePath: async () => '/mock/settings/path',
-  dispose: async () => {},
-  // Add other required public methods with no-op implementations
-  restartConnection: async () => {},
-  readResource: async () => ({ contents: [] }),
-  callTool: async () => ({ content: [] }),
-  toggleServerDisabled: async () => {},
-  toggleToolAlwaysAllow: async () => {},
-  isConnecting: false,
-  connections: []
-} as unknown as McpHub)
-
-describe('SYSTEM_PROMPT', () => {
-  let mockMcpHub: McpHub
-
-  beforeEach(() => {
-    jest.clearAllMocks()
-  })
-
-  afterEach(async () => {
-    // Clean up any McpHub instances
-    if (mockMcpHub) {
-      await mockMcpHub.dispose()
-    }
-  })
-
-  it('should maintain consistent system prompt', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false, // supportsComputerUse
-      undefined, // mcpHub
-      undefined, // diffStrategy
-      undefined // browserViewportSize
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should include browser actions when supportsComputerUse is true', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      true,
-      undefined,
-      undefined,
-      '1280x800'
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should include MCP server info when mcpHub is provided', async () => {
-    mockMcpHub = createMockMcpHub()
-
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      mockMcpHub
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should explicitly handle undefined mcpHub', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      undefined, // explicitly undefined mcpHub
-      undefined,
-      undefined
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should handle different browser viewport sizes', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      true,
-      undefined,
-      undefined,
-      '900x600' // different viewport size
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should include diff strategy tool description', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      undefined,
-      new SearchReplaceDiffStrategy(), // Use actual diff strategy from the codebase
-      undefined
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  afterAll(() => {
-    jest.restoreAllMocks()
-  })
+const createMockMcpHub = (): McpHub =>
+	({
+		getServers: () => [],
+		getMcpServersPath: async () => "/mock/mcp/path",
+		getMcpSettingsFilePath: async () => "/mock/settings/path",
+		dispose: async () => {},
+		// Add other required public methods with no-op implementations
+		restartConnection: async () => {},
+		readResource: async () => ({ contents: [] }),
+		callTool: async () => ({ content: [] }),
+		toggleServerDisabled: async () => {},
+		toggleToolAlwaysAllow: async () => {},
+		isConnecting: false,
+		connections: [],
+	}) as unknown as McpHub
+
+describe("SYSTEM_PROMPT", () => {
+	let mockMcpHub: McpHub
+
+	beforeEach(() => {
+		jest.clearAllMocks()
+	})
+
+	afterEach(async () => {
+		// Clean up any McpHub instances
+		if (mockMcpHub) {
+			await mockMcpHub.dispose()
+		}
+	})
+
+	it("should maintain consistent system prompt", async () => {
+		const prompt = await SYSTEM_PROMPT(
+			"/test/path",
+			false, // supportsComputerUse
+			undefined, // mcpHub
+			undefined, // diffStrategy
+			undefined, // browserViewportSize
+		)
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should include browser actions when supportsComputerUse is true", async () => {
+		const prompt = await SYSTEM_PROMPT("/test/path", true, undefined, undefined, "1280x800")
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should include MCP server info when mcpHub is provided", async () => {
+		mockMcpHub = createMockMcpHub()
+
+		const prompt = await SYSTEM_PROMPT("/test/path", false, mockMcpHub)
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should explicitly handle undefined mcpHub", async () => {
+		const prompt = await SYSTEM_PROMPT(
+			"/test/path",
+			false,
+			undefined, // explicitly undefined mcpHub
+			undefined,
+			undefined,
+		)
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should handle different browser viewport sizes", async () => {
+		const prompt = await SYSTEM_PROMPT(
+			"/test/path",
+			true,
+			undefined,
+			undefined,
+			"900x600", // different viewport size
+		)
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should include diff strategy tool description", async () => {
+		const prompt = await SYSTEM_PROMPT(
+			"/test/path",
+			false,
+			undefined,
+			new SearchReplaceDiffStrategy(), // Use actual diff strategy from the codebase
+			undefined,
+		)
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	afterAll(() => {
+		jest.restoreAllMocks()
+	})
 })
 
-describe('addCustomInstructions', () => {
-  beforeEach(() => {
-    jest.clearAllMocks()
-  })
-
-  it('should generate correct prompt for architect mode', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      undefined,
-      undefined,
-      undefined,
-      'architect'
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should generate correct prompt for ask mode', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      undefined,
-      undefined,
-      undefined,
-      'ask'
-    )
-    
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should prioritize mode-specific rules for code mode', async () => {
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path',
-      defaultModeSlug
-    )
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should prioritize mode-specific rules for ask mode', async () => {
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path',
-      modes[2].slug
-    )
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should prioritize mode-specific rules for architect mode', async () => {
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path',
-      modes[1].slug
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should prioritize mode-specific rules for test engineer mode', async () => {
-    // Mock readFile to include test engineer rules
-    const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
-      if (path.endsWith('.clinerules-test')) {
-        return '# Test Engineer Rules\n1. Always write tests first\n2. Get approval before modifying non-test code'
-      }
-      if (path.endsWith('.clinerules')) {
-        return '# Test Rules\n1. First rule\n2. Second rule'
-      }
-      return ''
-    })
-    jest.spyOn(fs, 'readFile').mockImplementation(mockReadFile)
-
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path',
-      'test'
-    )
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should prioritize mode-specific rules for code reviewer mode', async () => {
-    // Mock readFile to include code reviewer rules
-    const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
-      if (path.endsWith('.clinerules-review')) {
-        return '# Code Reviewer Rules\n1. Provide specific examples in feedback\n2. Focus on maintainability and best practices'
-      }
-      if (path.endsWith('.clinerules')) {
-        return '# Test Rules\n1. First rule\n2. Second rule'
-      }
-      return ''
-    })
-    jest.spyOn(fs, 'readFile').mockImplementation(mockReadFile)
-
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path',
-      'review'
-    )
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should generate correct prompt for test engineer mode', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      undefined,
-      undefined,
-      undefined,
-      'test'
-    )
-    
-    // Verify test engineer role requirements
-    expect(prompt).toContain('must ask the user to confirm before making ANY changes to non-test code')
-    expect(prompt).toContain('ask the user to confirm your test plan')
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should generate correct prompt for code reviewer mode', async () => {
-    const prompt = await SYSTEM_PROMPT(
-      '/test/path',
-      false,
-      undefined,
-      undefined,
-      undefined,
-      'review'
-    )
-    
-    // Verify code reviewer role constraints
-    expect(prompt).toContain('providing detailed, actionable feedback')
-    expect(prompt).toContain('maintain a read-only approach')
-    expect(prompt).toMatchSnapshot()
-  })
-
-  it('should fall back to generic rules when mode-specific rules not found', async () => {
-    // Mock readFile to return ENOENT for mode-specific file
-    const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
-      if (path.endsWith('.clinerules-code') || 
-          path.endsWith('.clinerules-test') || 
-          path.endsWith('.clinerules-review')) {
-        const error = new Error('ENOENT') as NodeJS.ErrnoException
-        error.code = 'ENOENT'
-        throw error
-      }
-      if (path.endsWith('.clinerules')) {
-        return '# Test Rules\n1. First rule\n2. Second rule'
-      }
-      return ''
-    })
-    jest.spyOn(fs, 'readFile').mockImplementation(mockReadFile)
-
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path',
-      defaultModeSlug
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should include preferred language when provided', async () => {
-    const instructions = await addCustomInstructions(
-      { preferredLanguage: 'Spanish' },
-      '/test/path',
-      defaultModeSlug
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should include custom instructions when provided', async () => {
-    const instructions = await addCustomInstructions(
-      { customInstructions: 'Custom test instructions' },
-      '/test/path'
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should combine all custom instructions', async () => {
-    const instructions = await addCustomInstructions(
-      {
-        customInstructions: 'Custom test instructions',
-        preferredLanguage: 'French'
-      },
-      '/test/path',
-      defaultModeSlug
-    )
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should handle undefined mode-specific instructions', async () => {
-    const instructions = await addCustomInstructions(
-      {},
-      '/test/path'
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should trim mode-specific instructions', async () => {
-    const instructions = await addCustomInstructions(
-      { customInstructions: '  Custom mode instructions  ' },
-      '/test/path'
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should handle empty mode-specific instructions', async () => {
-    const instructions = await addCustomInstructions(
-      { customInstructions: '' },
-      '/test/path'
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should combine global and mode-specific instructions', async () => {
-    const instructions = await addCustomInstructions(
-      {
-        customInstructions: 'Global instructions',
-        customPrompts: {
-          code: { customInstructions: 'Mode-specific instructions' }
-        }
-      },
-      '/test/path',
-      defaultModeSlug
-    )
-    
-    expect(instructions).toMatchSnapshot()
-  })
-
-  it('should prioritize mode-specific instructions after global ones', async () => {
-    const instructions = await addCustomInstructions(
-      {
-        customInstructions: 'First instruction',
-        customPrompts: {
-          code: { customInstructions: 'Second instruction' }
-        }
-      },
-      '/test/path',
-      defaultModeSlug
-    )
-    
-    const instructionParts = instructions.split('\n\n')
-    const globalIndex = instructionParts.findIndex(part => part.includes('First instruction'))
-    const modeSpecificIndex = instructionParts.findIndex(part => part.includes('Second instruction'))
-    
-    expect(globalIndex).toBeLessThan(modeSpecificIndex)
-    expect(instructions).toMatchSnapshot()
-  })
-
-  afterAll(() => {
-    jest.restoreAllMocks()
-  })
+describe("addCustomInstructions", () => {
+	beforeEach(() => {
+		jest.clearAllMocks()
+	})
+
+	it("should generate correct prompt for architect mode", async () => {
+		const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "architect")
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should generate correct prompt for ask mode", async () => {
+		const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "ask")
+
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should prioritize mode-specific rules for code mode", async () => {
+		const instructions = await addCustomInstructions({}, "/test/path", defaultModeSlug)
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should prioritize mode-specific rules for ask mode", async () => {
+		const instructions = await addCustomInstructions({}, "/test/path", modes[2].slug)
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should prioritize mode-specific rules for architect mode", async () => {
+		const instructions = await addCustomInstructions({}, "/test/path", modes[1].slug)
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should prioritize mode-specific rules for test engineer mode", async () => {
+		// Mock readFile to include test engineer rules
+		const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
+			if (path.endsWith(".clinerules-test")) {
+				return "# Test Engineer Rules\n1. Always write tests first\n2. Get approval before modifying non-test code"
+			}
+			if (path.endsWith(".clinerules")) {
+				return "# Test Rules\n1. First rule\n2. Second rule"
+			}
+			return ""
+		})
+		jest.spyOn(fs, "readFile").mockImplementation(mockReadFile)
+
+		const instructions = await addCustomInstructions({}, "/test/path", "test")
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should prioritize mode-specific rules for code reviewer mode", async () => {
+		// Mock readFile to include code reviewer rules
+		const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
+			if (path.endsWith(".clinerules-review")) {
+				return "# Code Reviewer Rules\n1. Provide specific examples in feedback\n2. Focus on maintainability and best practices"
+			}
+			if (path.endsWith(".clinerules")) {
+				return "# Test Rules\n1. First rule\n2. Second rule"
+			}
+			return ""
+		})
+		jest.spyOn(fs, "readFile").mockImplementation(mockReadFile)
+
+		const instructions = await addCustomInstructions({}, "/test/path", "review")
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should generate correct prompt for test engineer mode", async () => {
+		const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "test")
+
+		// Verify test engineer role requirements
+		expect(prompt).toContain("must ask the user to confirm before making ANY changes to non-test code")
+		expect(prompt).toContain("ask the user to confirm your test plan")
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should generate correct prompt for code reviewer mode", async () => {
+		const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "review")
+
+		// Verify code reviewer role constraints
+		expect(prompt).toContain("providing detailed, actionable feedback")
+		expect(prompt).toContain("maintain a read-only approach")
+		expect(prompt).toMatchSnapshot()
+	})
+
+	it("should fall back to generic rules when mode-specific rules not found", async () => {
+		// Mock readFile to return ENOENT for mode-specific file
+		const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
+			if (
+				path.endsWith(".clinerules-code") ||
+				path.endsWith(".clinerules-test") ||
+				path.endsWith(".clinerules-review")
+			) {
+				const error = new Error("ENOENT") as NodeJS.ErrnoException
+				error.code = "ENOENT"
+				throw error
+			}
+			if (path.endsWith(".clinerules")) {
+				return "# Test Rules\n1. First rule\n2. Second rule"
+			}
+			return ""
+		})
+		jest.spyOn(fs, "readFile").mockImplementation(mockReadFile)
+
+		const instructions = await addCustomInstructions({}, "/test/path", defaultModeSlug)
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should include preferred language when provided", async () => {
+		const instructions = await addCustomInstructions(
+			{ preferredLanguage: "Spanish" },
+			"/test/path",
+			defaultModeSlug,
+		)
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should include custom instructions when provided", async () => {
+		const instructions = await addCustomInstructions(
+			{ customInstructions: "Custom test instructions" },
+			"/test/path",
+		)
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should combine all custom instructions", async () => {
+		const instructions = await addCustomInstructions(
+			{
+				customInstructions: "Custom test instructions",
+				preferredLanguage: "French",
+			},
+			"/test/path",
+			defaultModeSlug,
+		)
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should handle undefined mode-specific instructions", async () => {
+		const instructions = await addCustomInstructions({}, "/test/path")
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should trim mode-specific instructions", async () => {
+		const instructions = await addCustomInstructions(
+			{ customInstructions: "  Custom mode instructions  " },
+			"/test/path",
+		)
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should handle empty mode-specific instructions", async () => {
+		const instructions = await addCustomInstructions({ customInstructions: "" }, "/test/path")
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should combine global and mode-specific instructions", async () => {
+		const instructions = await addCustomInstructions(
+			{
+				customInstructions: "Global instructions",
+				customPrompts: {
+					code: { customInstructions: "Mode-specific instructions" },
+				},
+			},
+			"/test/path",
+			defaultModeSlug,
+		)
+
+		expect(instructions).toMatchSnapshot()
+	})
+
+	it("should prioritize mode-specific instructions after global ones", async () => {
+		const instructions = await addCustomInstructions(
+			{
+				customInstructions: "First instruction",
+				customPrompts: {
+					code: { customInstructions: "Second instruction" },
+				},
+			},
+			"/test/path",
+			defaultModeSlug,
+		)
+
+		const instructionParts = instructions.split("\n\n")
+		const globalIndex = instructionParts.findIndex((part) => part.includes("First instruction"))
+		const modeSpecificIndex = instructionParts.findIndex((part) => part.includes("Second instruction"))
+
+		expect(globalIndex).toBeLessThan(modeSpecificIndex)
+		expect(instructions).toMatchSnapshot()
+	})
+
+	afterAll(() => {
+		jest.restoreAllMocks()
+	})
 })

+ 17 - 13
src/core/prompts/sections/capabilities.ts

@@ -2,27 +2,31 @@ import { DiffStrategy } from "../../diff/DiffStrategy"
 import { McpHub } from "../../../services/mcp/McpHub"
 
 export function getCapabilitiesSection(
-    cwd: string,
-    supportsComputerUse: boolean,
-    mcpHub?: McpHub,
-    diffStrategy?: DiffStrategy,
+	cwd: string,
+	supportsComputerUse: boolean,
+	mcpHub?: McpHub,
+	diffStrategy?: DiffStrategy,
 ): string {
-    return `====
+	return `====
 
 CAPABILITIES
 
 - You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search${
-    supportsComputerUse ? ", use the browser" : ""
-}, read and write files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
+		supportsComputerUse ? ", use the browser" : ""
+	}, read and write files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
 - When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
 - You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
 - You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
     - For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file ${diffStrategy ? "or apply_diff " : ""}tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
 - You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
-    supportsComputerUse
-        ? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n  - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
-        : ""
-}${mcpHub ? `
+		supportsComputerUse
+			? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n  - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
+			: ""
+	}${
+		mcpHub
+			? `
 - You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
-` : ''}`
-}
+`
+			: ""
+	}`
+}

+ 42 - 37
src/core/prompts/sections/custom-instructions.ts

@@ -1,46 +1,51 @@
-import fs from 'fs/promises'
-import path from 'path'
+import fs from "fs/promises"
+import path from "path"
 
 export async function loadRuleFiles(cwd: string): Promise<string> {
-    const ruleFiles = ['.clinerules', '.cursorrules', '.windsurfrules']
-    let combinedRules = ''
-
-    for (const file of ruleFiles) {
-        try {
-            const content = await fs.readFile(path.join(cwd, file), 'utf-8')
-            if (content.trim()) {
-                combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
-            }
-        } catch (err) {
-            // Silently skip if file doesn't exist
-            if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
-                throw err
-            }
-        }
-    }
-
-    return combinedRules
+	const ruleFiles = [".clinerules", ".cursorrules", ".windsurfrules"]
+	let combinedRules = ""
+
+	for (const file of ruleFiles) {
+		try {
+			const content = await fs.readFile(path.join(cwd, file), "utf-8")
+			if (content.trim()) {
+				combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
+			}
+		} catch (err) {
+			// Silently skip if file doesn't exist
+			if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
+				throw err
+			}
+		}
+	}
+
+	return combinedRules
 }
 
-export async function addCustomInstructions(customInstructions: string, cwd: string, preferredLanguage?: string): Promise<string> {
-    const ruleFileContent = await loadRuleFiles(cwd)
-    const allInstructions = []
+export async function addCustomInstructions(
+	customInstructions: string,
+	cwd: string,
+	preferredLanguage?: string,
+): Promise<string> {
+	const ruleFileContent = await loadRuleFiles(cwd)
+	const allInstructions = []
 
-    if (preferredLanguage) {
-        allInstructions.push(`You should always speak and think in the ${preferredLanguage} language.`)
-    }
-    
-    if (customInstructions.trim()) {
-        allInstructions.push(customInstructions.trim())
-    }
+	if (preferredLanguage) {
+		allInstructions.push(`You should always speak and think in the ${preferredLanguage} language.`)
+	}
 
-    if (ruleFileContent && ruleFileContent.trim()) {
-        allInstructions.push(ruleFileContent.trim())
-    }
+	if (customInstructions.trim()) {
+		allInstructions.push(customInstructions.trim())
+	}
 
-    const joinedInstructions = allInstructions.join('\n\n')
+	if (ruleFileContent && ruleFileContent.trim()) {
+		allInstructions.push(ruleFileContent.trim())
+	}
 
-    return joinedInstructions ? `
+	const joinedInstructions = allInstructions.join("\n\n")
+
+	return joinedInstructions
+		? `
 ====
 
 USER'S CUSTOM INSTRUCTIONS
@@ -48,5 +53,5 @@ USER'S CUSTOM INSTRUCTIONS
 The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
 
 ${joinedInstructions}`
-        : ""
-}
+		: ""
+}

+ 8 - 8
src/core/prompts/sections/index.ts

@@ -1,8 +1,8 @@
-export { getRulesSection } from './rules'
-export { getSystemInfoSection } from './system-info'
-export { getObjectiveSection } from './objective'
-export { addCustomInstructions } from './custom-instructions'
-export { getSharedToolUseSection } from './tool-use'
-export { getMcpServersSection } from './mcp-servers'
-export { getToolUseGuidelinesSection } from './tool-use-guidelines'
-export { getCapabilitiesSection } from './capabilities'
+export { getRulesSection } from "./rules"
+export { getSystemInfoSection } from "./system-info"
+export { getObjectiveSection } from "./objective"
+export { addCustomInstructions } from "./custom-instructions"
+export { getSharedToolUseSection } from "./tool-use"
+export { getMcpServersSection } from "./mcp-servers"
+export { getToolUseGuidelinesSection } from "./tool-use-guidelines"
+export { getCapabilitiesSection } from "./capabilities"

+ 41 - 40
src/core/prompts/sections/mcp-servers.ts

@@ -2,47 +2,48 @@ import { DiffStrategy } from "../../diff/DiffStrategy"
 import { McpHub } from "../../../services/mcp/McpHub"
 
 export async function getMcpServersSection(mcpHub?: McpHub, diffStrategy?: DiffStrategy): Promise<string> {
-    if (!mcpHub) {
-        return '';
-    }
-
-    const connectedServers = mcpHub.getServers().length > 0
-        ? `${mcpHub
-            .getServers()
-            .filter((server) => server.status === "connected")
-            .map((server) => {
-                const tools = server.tools
-                    ?.map((tool) => {
-                        const schemaStr = tool.inputSchema
-                            ? `    Input Schema:
+	if (!mcpHub) {
+		return ""
+	}
+
+	const connectedServers =
+		mcpHub.getServers().length > 0
+			? `${mcpHub
+					.getServers()
+					.filter((server) => server.status === "connected")
+					.map((server) => {
+						const tools = server.tools
+							?.map((tool) => {
+								const schemaStr = tool.inputSchema
+									? `    Input Schema:
     ${JSON.stringify(tool.inputSchema, null, 2).split("\n").join("\n    ")}`
-                            : ""
+									: ""
 
-                        return `- ${tool.name}: ${tool.description}\n${schemaStr}`
-                    })
-                    .join("\n\n")
+								return `- ${tool.name}: ${tool.description}\n${schemaStr}`
+							})
+							.join("\n\n")
 
-                const templates = server.resourceTemplates
-                    ?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
-                    .join("\n")
+						const templates = server.resourceTemplates
+							?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
+							.join("\n")
 
-                const resources = server.resources
-                    ?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
-                    .join("\n")
+						const resources = server.resources
+							?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
+							.join("\n")
 
-                const config = JSON.parse(server.config)
+						const config = JSON.parse(server.config)
 
-                return (
-                    `## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
-                    (tools ? `\n\n### Available Tools\n${tools}` : "") +
-                    (templates ? `\n\n### Resource Templates\n${templates}` : "") +
-                    (resources ? `\n\n### Direct Resources\n${resources}` : "")
-                )
-            })
-            .join("\n\n")}`
-        : "(No MCP servers currently connected)";
+						return (
+							`## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
+							(tools ? `\n\n### Available Tools\n${tools}` : "") +
+							(templates ? `\n\n### Resource Templates\n${templates}` : "") +
+							(resources ? `\n\n### Direct Resources\n${resources}` : "")
+						)
+					})
+					.join("\n\n")}`
+			: "(No MCP servers currently connected)"
 
-    return `MCP SERVERS
+	return `MCP SERVERS
 
 The Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.
 
@@ -397,11 +398,11 @@ IMPORTANT: Regardless of what else you see in the MCP settings file, you must de
 ## Editing MCP Servers
 
 The user may ask to add tools or resources that may make sense to add to an existing MCP server (listed under 'Connected MCP Servers' above: ${
-    mcpHub
-        .getServers()
-        .map((server) => server.name)
-        .join(", ") || "(None running currently)"
-}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use write_to_file${diffStrategy ? " or apply_diff" : ""} to make changes to the files.
+		mcpHub
+			.getServers()
+			.map((server) => server.name)
+			.join(", ") || "(None running currently)"
+	}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use write_to_file${diffStrategy ? " or apply_diff" : ""} to make changes to the files.
 
 However some MCP servers may be running from installed packages rather than a local repository, in which case it may make more sense to create a new MCP server.
 
@@ -410,4 +411,4 @@ However some MCP servers may be running from installed packages rather than a lo
 The user may not always request the use or creation of MCP servers. Instead, they might provide tasks that can be completed with existing tools. While using the MCP SDK to extend your capabilities can be useful, it's important to understand that this is just one specialized type of task you can accomplish. You should only implement MCP servers when the user explicitly requests it (e.g., "add a tool that...").
 
 Remember: The MCP documentation and example provided above are to help you understand and work with existing MCP servers or create new ones when requested by the user. You already have access to tools and capabilities that can be used to accomplish a wide range of tasks.`
-}
+}

+ 2 - 2
src/core/prompts/sections/objective.ts

@@ -1,5 +1,5 @@
 export function getObjectiveSection(): string {
-    return `====
+	return `====
 
 OBJECTIVE
 
@@ -10,4 +10,4 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
 3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
 4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
 5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
-}
+}

+ 11 - 15
src/core/prompts/sections/rules.ts

@@ -1,11 +1,7 @@
 import { DiffStrategy } from "../../diff/DiffStrategy"
 
-export function getRulesSection(
-    cwd: string,
-    supportsComputerUse: boolean,
-    diffStrategy?: DiffStrategy
-): string {
-    return `====
+export function getRulesSection(cwd: string, supportsComputerUse: boolean, diffStrategy?: DiffStrategy): string {
+	return `====
 
 RULES
 
@@ -23,10 +19,10 @@ ${diffStrategy ? "- You should use apply_diff instead of write_to_file when maki
 - When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ask_followup_question tool to request the user to copy and paste it back to you.
 - The user may provide a file's contents directly in their message, in which case you shouldn't use the read_file tool to get the file contents again since you already have it.
 - Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
-       supportsComputerUse
-               ? '\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.'
-               : ""
-}
+		supportsComputerUse
+			? '\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.'
+			: ""
+	}
 - NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
 - You are STRICTLY FORBIDDEN from starting your messages with "Great", "Certainly", "Okay", "Sure". You should NOT be conversational in your responses, but rather direct and to the point. For example you should NOT say "Great, I've updated the CSS" but instead something like "I've updated the CSS". It is important you be clear and technical in your messages.
 - When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.
@@ -35,8 +31,8 @@ ${diffStrategy ? "- You should use apply_diff instead of write_to_file when maki
 - When using the write_to_file tool, ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.
 - MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
 - It is critical you wait for the user's response after each tool use, in order to confirm the success of the tool use. For example, if asked to make a todo app, you would create a file, wait for the user's response it was created successfully, then create another file if needed, wait for the user's response it was created successfully, etc.${
-       supportsComputerUse
-               ? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
-               : ""
-}`
-}
+		supportsComputerUse
+			? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
+			: ""
+	}`
+}

+ 2 - 2
src/core/prompts/sections/system-info.ts

@@ -3,7 +3,7 @@ import os from "os"
 import osName from "os-name"
 
 export function getSystemInfoSection(cwd: string): string {
-    return `====
+	return `====
 
 SYSTEM INFORMATION
 
@@ -13,4 +13,4 @@ Home Directory: ${os.homedir().toPosix()}
 Current Working Directory: ${cwd.toPosix()}
 
 When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/path') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.`
-}
+}

+ 2 - 2
src/core/prompts/sections/tool-use-guidelines.ts

@@ -1,5 +1,5 @@
 export function getToolUseGuidelinesSection(): string {
-    return `# Tool Use Guidelines
+	return `# Tool Use Guidelines
 
 1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
 2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information. For example using the list_files tool is more effective than running a command like \`ls\` in the terminal. It's critical that you think about each available tool and use the one that best fits the current step in the task.
@@ -19,4 +19,4 @@ It is crucial to proceed step-by-step, waiting for the user's message after each
 4. Ensure that each action builds correctly on the previous ones.
 
 By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.`
-}
+}

+ 2 - 2
src/core/prompts/sections/tool-use.ts

@@ -1,5 +1,5 @@
 export function getSharedToolUseSection(): string {
-    return `====
+	return `====
 
 TOOL USE
 
@@ -22,4 +22,4 @@ For example:
 </read_file>
 
 Always adhere to this format for the tool use to ensure proper parsing and execution.`
-}
+}

+ 102 - 105
src/core/prompts/system.ts

@@ -3,87 +3,84 @@ import { DiffStrategy } from "../diff/DiffStrategy"
 import { McpHub } from "../../services/mcp/McpHub"
 import { getToolDescriptionsForMode } from "./tools"
 import {
-    getRulesSection,
-    getSystemInfoSection,
-    getObjectiveSection,
-    getSharedToolUseSection,
-    getMcpServersSection,
-    getToolUseGuidelinesSection,
-    getCapabilitiesSection
+	getRulesSection,
+	getSystemInfoSection,
+	getObjectiveSection,
+	getSharedToolUseSection,
+	getMcpServersSection,
+	getToolUseGuidelinesSection,
+	getCapabilitiesSection,
 } from "./sections"
-import fs from 'fs/promises'
-import path from 'path'
+import fs from "fs/promises"
+import path from "path"
 
 async function loadRuleFiles(cwd: string, mode: Mode): Promise<string> {
-    let combinedRules = ''
-
-    // First try mode-specific rules
-    const modeSpecificFile = `.clinerules-${mode}`
-    try {
-        const content = await fs.readFile(path.join(cwd, modeSpecificFile), 'utf-8')
-        if (content.trim()) {
-            combinedRules += `\n# Rules from ${modeSpecificFile}:\n${content.trim()}\n`
-        }
-    } catch (err) {
-        // Silently skip if file doesn't exist
-        if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
-            throw err
-        }
-    }
-
-    // Then try generic rules files
-    const genericRuleFiles = ['.clinerules']
-    for (const file of genericRuleFiles) {
-        try {
-            const content = await fs.readFile(path.join(cwd, file), 'utf-8')
-            if (content.trim()) {
-                combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
-            }
-        } catch (err) {
-            // Silently skip if file doesn't exist
-            if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
-                throw err
-            }
-        }
-    }
-
-    return combinedRules
+	let combinedRules = ""
+
+	// First try mode-specific rules
+	const modeSpecificFile = `.clinerules-${mode}`
+	try {
+		const content = await fs.readFile(path.join(cwd, modeSpecificFile), "utf-8")
+		if (content.trim()) {
+			combinedRules += `\n# Rules from ${modeSpecificFile}:\n${content.trim()}\n`
+		}
+	} catch (err) {
+		// Silently skip if file doesn't exist
+		if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
+			throw err
+		}
+	}
+
+	// Then try generic rules files
+	const genericRuleFiles = [".clinerules"]
+	for (const file of genericRuleFiles) {
+		try {
+			const content = await fs.readFile(path.join(cwd, file), "utf-8")
+			if (content.trim()) {
+				combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
+			}
+		} catch (err) {
+			// Silently skip if file doesn't exist
+			if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
+				throw err
+			}
+		}
+	}
+
+	return combinedRules
 }
 
 interface State {
-    customInstructions?: string;
-    customPrompts?: CustomPrompts;
-    preferredLanguage?: string;
+	customInstructions?: string
+	customPrompts?: CustomPrompts
+	preferredLanguage?: string
 }
 
-export async function addCustomInstructions(
-    state: State,
-    cwd: string,
-    mode: Mode = defaultModeSlug
-): Promise<string> {
-    const ruleFileContent = await loadRuleFiles(cwd, mode)
-    const allInstructions = []
+export async function addCustomInstructions(state: State, cwd: string, mode: Mode = defaultModeSlug): Promise<string> {
+	const ruleFileContent = await loadRuleFiles(cwd, mode)
+	const allInstructions = []
 
-    if (state.preferredLanguage) {
-        allInstructions.push(`You should always speak and think in the ${state.preferredLanguage} language.`)
-    }
+	if (state.preferredLanguage) {
+		allInstructions.push(`You should always speak and think in the ${state.preferredLanguage} language.`)
+	}
 
-    if (state.customInstructions?.trim()) {
-        allInstructions.push(state.customInstructions.trim())
-    }
+	if (state.customInstructions?.trim()) {
+		allInstructions.push(state.customInstructions.trim())
+	}
 
-    const customPrompt = state.customPrompts?.[mode]
-    if (typeof customPrompt === 'object' && customPrompt?.customInstructions?.trim()) {
-        allInstructions.push(customPrompt.customInstructions.trim())
-    }
+	const customPrompt = state.customPrompts?.[mode]
+	if (typeof customPrompt === "object" && customPrompt?.customInstructions?.trim()) {
+		allInstructions.push(customPrompt.customInstructions.trim())
+	}
 
-    if (ruleFileContent && ruleFileContent.trim()) {
-        allInstructions.push(ruleFileContent.trim())
-    }
+	if (ruleFileContent && ruleFileContent.trim()) {
+		allInstructions.push(ruleFileContent.trim())
+	}
 
-    const joinedInstructions = allInstructions.join('\n\n')
+	const joinedInstructions = allInstructions.join("\n\n")
 
-    return joinedInstructions ? `
+	return joinedInstructions
+		? `
 ====
 
 USER'S CUSTOM INSTRUCTIONS
@@ -91,19 +88,19 @@ USER'S CUSTOM INSTRUCTIONS
 The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
 
 ${joinedInstructions}`
-        : ""
+		: ""
 }
 
 async function generatePrompt(
-    cwd: string,
-    supportsComputerUse: boolean,
-    mode: Mode,
-    mcpHub?: McpHub,
-    diffStrategy?: DiffStrategy,
-    browserViewportSize?: string,
-    promptComponent?: PromptComponent,
+	cwd: string,
+	supportsComputerUse: boolean,
+	mode: Mode,
+	mcpHub?: McpHub,
+	diffStrategy?: DiffStrategy,
+	browserViewportSize?: string,
+	promptComponent?: PromptComponent,
 ): Promise<string> {
-    const basePrompt = `${promptComponent?.roleDefinition || getRoleDefinition(mode)}
+	const basePrompt = `${promptComponent?.roleDefinition || getRoleDefinition(mode)}
 
 ${getSharedToolUseSection()}
 
@@ -119,38 +116,38 @@ ${getRulesSection(cwd, supportsComputerUse, diffStrategy)}
 
 ${getSystemInfoSection(cwd)}
 
-${getObjectiveSection()}`;
+${getObjectiveSection()}`
 
-    return basePrompt;
+	return basePrompt
 }
 
 export const SYSTEM_PROMPT = async (
-    cwd: string,
-    supportsComputerUse: boolean,
-    mcpHub?: McpHub,
-    diffStrategy?: DiffStrategy,
-    browserViewportSize?: string,
-    mode: Mode = defaultModeSlug,
-    customPrompts?: CustomPrompts,
+	cwd: string,
+	supportsComputerUse: boolean,
+	mcpHub?: McpHub,
+	diffStrategy?: DiffStrategy,
+	browserViewportSize?: string,
+	mode: Mode = defaultModeSlug,
+	customPrompts?: CustomPrompts,
 ) => {
-    const getPromptComponent = (value: unknown) => {
-        if (typeof value === 'object' && value !== null) {
-            return value as PromptComponent;
-        }
-        return undefined;
-    };
-
-    // Use default mode if not found
-    const currentMode = modes.find(m => m.slug === mode) || modes[0];
-    const promptComponent = getPromptComponent(customPrompts?.[currentMode.slug]);
-
-    return generatePrompt(
-        cwd,
-        supportsComputerUse,
-        currentMode.slug,
-        mcpHub,
-        diffStrategy,
-        browserViewportSize,
-        promptComponent
-    );
+	const getPromptComponent = (value: unknown) => {
+		if (typeof value === "object" && value !== null) {
+			return value as PromptComponent
+		}
+		return undefined
+	}
+
+	// Use default mode if not found
+	const currentMode = modes.find((m) => m.slug === mode) || modes[0]
+	const promptComponent = getPromptComponent(customPrompts?.[currentMode.slug])
+
+	return generatePrompt(
+		cwd,
+		supportsComputerUse,
+		currentMode.slug,
+		mcpHub,
+		diffStrategy,
+		browserViewportSize,
+		promptComponent,
+	)
 }

+ 6 - 6
src/core/prompts/tools/access-mcp-resource.ts

@@ -1,10 +1,10 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getAccessMcpResourceDescription(args: ToolArgs): string | undefined {
-    if (!args.mcpHub) {
-        return undefined;
-    }
-    return `## access_mcp_resource
+	if (!args.mcpHub) {
+		return undefined
+	}
+	return `## access_mcp_resource
 Description: Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.
 Parameters:
 - server_name: (required) The name of the MCP server providing the resource
@@ -21,4 +21,4 @@ Example: Requesting to access an MCP resource
 <server_name>weather-server</server_name>
 <uri>weather://san-francisco/current</uri>
 </access_mcp_resource>`
-}
+}

+ 2 - 2
src/core/prompts/tools/ask-followup-question.ts

@@ -1,5 +1,5 @@
 export function getAskFollowupQuestionDescription(): string {
-    return `## ask_followup_question
+	return `## ask_followup_question
 Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
 Parameters:
 - question: (required) The question to ask the user. This should be a clear, specific question that addresses the information you need.
@@ -12,4 +12,4 @@ Example: Requesting to ask the user for the path to the frontend-config.json fil
 <ask_followup_question>
 <question>What is the path to the frontend-config.json file?</question>
 </ask_followup_question>`
-}
+}

+ 2 - 2
src/core/prompts/tools/attempt-completion.ts

@@ -1,5 +1,5 @@
 export function getAttemptCompletionDescription(): string {
-    return `## attempt_completion
+	return `## attempt_completion
 Description: After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
 IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in <thinking></thinking> tags if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool.
 Parameters:
@@ -20,4 +20,4 @@ I've updated the CSS
 </result>
 <command>open index.html</command>
 </attempt_completion>`
-}
+}

+ 6 - 6
src/core/prompts/tools/browser-action.ts

@@ -1,10 +1,10 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getBrowserActionDescription(args: ToolArgs): string | undefined {
-    if (!args.supportsComputerUse) {
-        return undefined;
-    }
-    return `## browser_action
+	if (!args.supportsComputerUse) {
+		return undefined
+	}
+	return `## browser_action
 Description: Request to interact with a Puppeteer-controlled browser. Every action, except \`close\`, will be responded to with a screenshot of the browser's current state, along with any new console logs. You may only perform one browser action per message, and wait for the user's response including a screenshot and logs to determine the next action.
 - The sequence of actions **must always start with** launching the browser at a URL, and **must always end with** closing the browser. If you need to visit a new URL that is not possible to navigate to from the current webpage, you must first close the browser, then launch again at the new URL.
 - While the browser is active, only the \`browser_action\` tool can be used. No other tools should be called during this time. You may proceed to use other tools only after closing the browser. For example if you run into an error and need to fix a file, you must close the browser, then use other tools to make the necessary changes, then re-launch the browser to verify the result.
@@ -49,4 +49,4 @@ Example: Requesting to click on the element at coordinates 450,300
 <action>click</action>
 <coordinate>450,300</coordinate>
 </browser_action>`
-}
+}

+ 3 - 3
src/core/prompts/tools/execute-command.ts

@@ -1,7 +1,7 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getExecuteCommandDescription(args: ToolArgs): string | undefined {
-    return `## execute_command
+	return `## execute_command
 Description: Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: ${args.cwd}
 Parameters:
 - command: (required) The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.
@@ -14,4 +14,4 @@ Example: Requesting to execute npm run dev
 <execute_command>
 <command>npm run dev</command>
 </execute_command>`
-}
+}

+ 67 - 66
src/core/prompts/tools/index.ts

@@ -1,79 +1,80 @@
-import { getExecuteCommandDescription } from './execute-command'
-import { getReadFileDescription } from './read-file'
-import { getWriteToFileDescription } from './write-to-file'
-import { getSearchFilesDescription } from './search-files'
-import { getListFilesDescription } from './list-files'
-import { getListCodeDefinitionNamesDescription } from './list-code-definition-names'
-import { getBrowserActionDescription } from './browser-action'
-import { getAskFollowupQuestionDescription } from './ask-followup-question'
-import { getAttemptCompletionDescription } from './attempt-completion'
-import { getUseMcpToolDescription } from './use-mcp-tool'
-import { getAccessMcpResourceDescription } from './access-mcp-resource'
-import { DiffStrategy } from '../../diff/DiffStrategy'
-import { McpHub } from '../../../services/mcp/McpHub'
-import { Mode, ToolName, getModeConfig, isToolAllowedForMode } from '../../../shared/modes'
-import { ToolArgs } from './types'
+import { getExecuteCommandDescription } from "./execute-command"
+import { getReadFileDescription } from "./read-file"
+import { getWriteToFileDescription } from "./write-to-file"
+import { getSearchFilesDescription } from "./search-files"
+import { getListFilesDescription } from "./list-files"
+import { getListCodeDefinitionNamesDescription } from "./list-code-definition-names"
+import { getBrowserActionDescription } from "./browser-action"
+import { getAskFollowupQuestionDescription } from "./ask-followup-question"
+import { getAttemptCompletionDescription } from "./attempt-completion"
+import { getUseMcpToolDescription } from "./use-mcp-tool"
+import { getAccessMcpResourceDescription } from "./access-mcp-resource"
+import { DiffStrategy } from "../../diff/DiffStrategy"
+import { McpHub } from "../../../services/mcp/McpHub"
+import { Mode, ToolName, getModeConfig, isToolAllowedForMode } from "../../../shared/modes"
+import { ToolArgs } from "./types"
 
 // Map of tool names to their description functions
 const toolDescriptionMap: Record<string, (args: ToolArgs) => string | undefined> = {
-    'execute_command': args => getExecuteCommandDescription(args),
-    'read_file': args => getReadFileDescription(args),
-    'write_to_file': args => getWriteToFileDescription(args),
-    'search_files': args => getSearchFilesDescription(args),
-    'list_files': args => getListFilesDescription(args),
-    'list_code_definition_names': args => getListCodeDefinitionNamesDescription(args),
-    'browser_action': args => getBrowserActionDescription(args),
-    'ask_followup_question': () => getAskFollowupQuestionDescription(),
-    'attempt_completion': () => getAttemptCompletionDescription(),
-    'use_mcp_tool': args => getUseMcpToolDescription(args),
-    'access_mcp_resource': args => getAccessMcpResourceDescription(args),
-    'apply_diff': args => args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : ''
-};
+	execute_command: (args) => getExecuteCommandDescription(args),
+	read_file: (args) => getReadFileDescription(args),
+	write_to_file: (args) => getWriteToFileDescription(args),
+	search_files: (args) => getSearchFilesDescription(args),
+	list_files: (args) => getListFilesDescription(args),
+	list_code_definition_names: (args) => getListCodeDefinitionNamesDescription(args),
+	browser_action: (args) => getBrowserActionDescription(args),
+	ask_followup_question: () => getAskFollowupQuestionDescription(),
+	attempt_completion: () => getAttemptCompletionDescription(),
+	use_mcp_tool: (args) => getUseMcpToolDescription(args),
+	access_mcp_resource: (args) => getAccessMcpResourceDescription(args),
+	apply_diff: (args) =>
+		args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : "",
+}
 
 export function getToolDescriptionsForMode(
-    mode: Mode,
-    cwd: string,
-    supportsComputerUse: boolean,
-    diffStrategy?: DiffStrategy,
-    browserViewportSize?: string,
-    mcpHub?: McpHub
+	mode: Mode,
+	cwd: string,
+	supportsComputerUse: boolean,
+	diffStrategy?: DiffStrategy,
+	browserViewportSize?: string,
+	mcpHub?: McpHub,
 ): string {
-    const config = getModeConfig(mode);
-    const args: ToolArgs = {
-        cwd,
-        supportsComputerUse,
-        diffStrategy,
-        browserViewportSize,
-        mcpHub
-    };
+	const config = getModeConfig(mode)
+	const args: ToolArgs = {
+		cwd,
+		supportsComputerUse,
+		diffStrategy,
+		browserViewportSize,
+		mcpHub,
+	}
 
-    // Map tool descriptions in the exact order specified in the mode's tools array
-    const descriptions = config.tools.map(([toolName, toolOptions]) => {
-        const descriptionFn = toolDescriptionMap[toolName];
-        if (!descriptionFn || !isToolAllowedForMode(toolName as ToolName, mode)) {
-            return undefined;
-        }
+	// Map tool descriptions in the exact order specified in the mode's tools array
+	const descriptions = config.tools.map(([toolName, toolOptions]) => {
+		const descriptionFn = toolDescriptionMap[toolName]
+		if (!descriptionFn || !isToolAllowedForMode(toolName as ToolName, mode)) {
+			return undefined
+		}
 
-        return descriptionFn({
-            ...args,
-            toolOptions
-        });
-    });
+		return descriptionFn({
+			...args,
+			toolOptions,
+		})
+	})
 
-    return `# Tools\n\n${descriptions.filter(Boolean).join('\n\n')}`;
+	return `# Tools\n\n${descriptions.filter(Boolean).join("\n\n")}`
 }
 
 // Export individual description functions for backward compatibility
 export {
-    getExecuteCommandDescription,
-    getReadFileDescription,
-    getWriteToFileDescription,
-    getSearchFilesDescription,
-    getListFilesDescription,
-    getListCodeDefinitionNamesDescription,
-    getBrowserActionDescription,
-    getAskFollowupQuestionDescription,
-    getAttemptCompletionDescription,
-    getUseMcpToolDescription,
-    getAccessMcpResourceDescription
-}
+	getExecuteCommandDescription,
+	getReadFileDescription,
+	getWriteToFileDescription,
+	getSearchFilesDescription,
+	getListFilesDescription,
+	getListCodeDefinitionNamesDescription,
+	getBrowserActionDescription,
+	getAskFollowupQuestionDescription,
+	getAttemptCompletionDescription,
+	getUseMcpToolDescription,
+	getAccessMcpResourceDescription,
+}

+ 3 - 3
src/core/prompts/tools/list-code-definition-names.ts

@@ -1,7 +1,7 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getListCodeDefinitionNamesDescription(args: ToolArgs): string {
-    return `## list_code_definition_names
+	return `## list_code_definition_names
 Description: Request to list definition names (classes, functions, methods, etc.) used in source code files at the top level of the specified directory. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.
 Parameters:
 - path: (required) The path of the directory (relative to the current working directory ${args.cwd}) to list top level source code definitions for.
@@ -14,4 +14,4 @@ Example: Requesting to list all top level source code definitions in the current
 <list_code_definition_names>
 <path>.</path>
 </list_code_definition_names>`
-}
+}

+ 3 - 3
src/core/prompts/tools/list-files.ts

@@ -1,7 +1,7 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getListFilesDescription(args: ToolArgs): string {
-    return `## list_files
+	return `## list_files
 Description: Request to list files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents. Do not use this tool to confirm the existence of files you may have created, as the user will let you know if the files were created successfully or not.
 Parameters:
 - path: (required) The path of the directory to list contents for (relative to the current working directory ${args.cwd})
@@ -17,4 +17,4 @@ Example: Requesting to list all files in the current directory
 <path>.</path>
 <recursive>false</recursive>
 </list_files>`
-}
+}

+ 3 - 3
src/core/prompts/tools/read-file.ts

@@ -1,7 +1,7 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getReadFileDescription(args: ToolArgs): string {
-    return `## read_file
+	return `## read_file
 Description: Request to read the contents of a file at the specified path. Use this when you need to examine the contents of an existing file you do not know the contents of, for example to analyze code, review text files, or extract information from configuration files. The output includes line numbers prefixed to each line (e.g. "1 | const x = 1"), making it easier to reference specific lines when creating diffs or discussing code. Automatically extracts raw text from PDF and DOCX files. May not be suitable for other types of binary files, as it returns the raw content as a string.
 Parameters:
 - path: (required) The path of the file to read (relative to the current working directory ${args.cwd})
@@ -14,4 +14,4 @@ Example: Requesting to read frontend-config.json
 <read_file>
 <path>frontend-config.json</path>
 </read_file>`
-}
+}

+ 2 - 2
src/core/prompts/tools/search-files.ts

@@ -1,7 +1,7 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getSearchFilesDescription(args: ToolArgs): string {
-    return `## search_files
+	return `## search_files
 Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
 Parameters:
 - path: (required) The path of the directory to search in (relative to the current working directory ${args.cwd}). This directory will be recursively searched.

+ 9 - 9
src/core/prompts/tools/types.ts

@@ -1,11 +1,11 @@
-import { DiffStrategy } from '../../diff/DiffStrategy'
-import { McpHub } from '../../../services/mcp/McpHub'
+import { DiffStrategy } from "../../diff/DiffStrategy"
+import { McpHub } from "../../../services/mcp/McpHub"
 
 export type ToolArgs = {
-    cwd: string;
-    supportsComputerUse: boolean;
-    diffStrategy?: DiffStrategy;
-    browserViewportSize?: string;
-    mcpHub?: McpHub;
-    toolOptions?: any;
-};
+	cwd: string
+	supportsComputerUse: boolean
+	diffStrategy?: DiffStrategy
+	browserViewportSize?: string
+	mcpHub?: McpHub
+	toolOptions?: any
+}

+ 6 - 6
src/core/prompts/tools/use-mcp-tool.ts

@@ -1,10 +1,10 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getUseMcpToolDescription(args: ToolArgs): string | undefined {
-    if (!args.mcpHub) {
-        return undefined;
-    }
-    return `## use_mcp_tool
+	if (!args.mcpHub) {
+		return undefined
+	}
+	return `## use_mcp_tool
 Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
 Parameters:
 - server_name: (required) The name of the MCP server providing the tool
@@ -34,4 +34,4 @@ Example: Requesting to use an MCP tool
 }
 </arguments>
 </use_mcp_tool>`
-}
+}

+ 2 - 2
src/core/prompts/tools/write-to-file.ts

@@ -1,7 +1,7 @@
-import { ToolArgs } from './types';
+import { ToolArgs } from "./types"
 
 export function getWriteToFileDescription(args: ToolArgs): string {
-    return `## write_to_file
+	return `## write_to_file
 Description: Request to write full content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
 Parameters:
 - path: (required) The path of the file to write to (relative to the current working directory ${args.cwd})

+ 43 - 43
src/core/prompts/types.ts

@@ -1,52 +1,52 @@
-import { Mode } from '../../shared/modes';
+import { Mode } from "../../shared/modes"
 
-export type { Mode };
+export type { Mode }
 
 export type ToolName =
-  | 'execute_command'
-  | 'read_file'
-  | 'write_to_file'
-  | 'apply_diff'
-  | 'search_files'
-  | 'list_files'
-  | 'list_code_definition_names'
-  | 'browser_action'
-  | 'use_mcp_tool'
-  | 'access_mcp_resource'
-  | 'ask_followup_question'
-  | 'attempt_completion';
+	| "execute_command"
+	| "read_file"
+	| "write_to_file"
+	| "apply_diff"
+	| "search_files"
+	| "list_files"
+	| "list_code_definition_names"
+	| "browser_action"
+	| "use_mcp_tool"
+	| "access_mcp_resource"
+	| "ask_followup_question"
+	| "attempt_completion"
 
 export const CODE_TOOLS: ToolName[] = [
-  'execute_command',
-  'read_file',
-  'write_to_file',
-  'apply_diff',
-  'search_files',
-  'list_files',
-  'list_code_definition_names',
-  'browser_action',
-  'use_mcp_tool',
-  'access_mcp_resource',
-  'ask_followup_question',
-  'attempt_completion'
-];
+	"execute_command",
+	"read_file",
+	"write_to_file",
+	"apply_diff",
+	"search_files",
+	"list_files",
+	"list_code_definition_names",
+	"browser_action",
+	"use_mcp_tool",
+	"access_mcp_resource",
+	"ask_followup_question",
+	"attempt_completion",
+]
 
 export const ARCHITECT_TOOLS: ToolName[] = [
-  'read_file',
-  'search_files',
-  'list_files',
-  'list_code_definition_names',
-  'ask_followup_question',
-  'attempt_completion'
-];
+	"read_file",
+	"search_files",
+	"list_files",
+	"list_code_definition_names",
+	"ask_followup_question",
+	"attempt_completion",
+]
 
 export const ASK_TOOLS: ToolName[] = [
-  'read_file',
-  'search_files',
-  'list_files',
-  'browser_action',
-  'use_mcp_tool',
-  'access_mcp_resource',
-  'ask_followup_question',
-  'attempt_completion'
-];
+	"read_file",
+	"search_files",
+	"list_files",
+	"browser_action",
+	"use_mcp_tool",
+	"access_mcp_resource",
+	"ask_followup_question",
+	"attempt_completion",
+]

+ 25 - 25
src/core/tool-lists.ts

@@ -1,32 +1,32 @@
 // Shared tools for architect and ask modes - read-only operations plus MCP and browser tools
 export const READONLY_ALLOWED_TOOLS = [
-    'read_file',
-    'search_files',
-    'list_files',
-    'list_code_definition_names',
-    'browser_action',
-    'use_mcp_tool',
-    'access_mcp_resource',
-    'ask_followup_question',
-    'attempt_completion'
-] as const;
+	"read_file",
+	"search_files",
+	"list_files",
+	"list_code_definition_names",
+	"browser_action",
+	"use_mcp_tool",
+	"access_mcp_resource",
+	"ask_followup_question",
+	"attempt_completion",
+] as const
 
 // Code mode has access to all tools
 export const CODE_ALLOWED_TOOLS = [
-    'execute_command',
-    'read_file',
-    'write_to_file',
-    'apply_diff',
-    'search_files',
-    'list_files',
-    'list_code_definition_names',
-    'browser_action',
-    'use_mcp_tool',
-    'access_mcp_resource',
-    'ask_followup_question',
-    'attempt_completion'
-] as const;
+	"execute_command",
+	"read_file",
+	"write_to_file",
+	"apply_diff",
+	"search_files",
+	"list_files",
+	"list_code_definition_names",
+	"browser_action",
+	"use_mcp_tool",
+	"access_mcp_resource",
+	"ask_followup_question",
+	"attempt_completion",
+] as const
 
 // Tool name types for type safety
-export type ReadOnlyToolName = typeof READONLY_ALLOWED_TOOLS[number];
-export type ToolName = typeof CODE_ALLOWED_TOOLS[number];
+export type ReadOnlyToolName = (typeof READONLY_ALLOWED_TOOLS)[number]
+export type ToolName = (typeof CODE_ALLOWED_TOOLS)[number]

+ 219 - 204
src/core/webview/ClineProvider.ts

@@ -98,7 +98,7 @@ type GlobalStateKey =
 	| "modeApiConfigs"
 	| "customPrompts"
 	| "enhancementApiConfigId"
-  	| "experimentalDiffStrategy"
+	| "experimentalDiffStrategy"
 	| "autoApprovalEnabled"
 
 export const GlobalFileNames = {
@@ -254,14 +254,12 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			fuzzyMatchThreshold,
 			mode,
 			customInstructions: globalInstructions,
-      experimentalDiffStrategy
+			experimentalDiffStrategy,
 		} = await this.getState()
 
 		const modePrompt = customPrompts?.[mode]
-		const modeInstructions = typeof modePrompt === 'object' ? modePrompt.customInstructions : undefined
-		const effectiveInstructions = [globalInstructions, modeInstructions]
-			.filter(Boolean)
-			.join('\n\n')
+		const modeInstructions = typeof modePrompt === "object" ? modePrompt.customInstructions : undefined
+		const effectiveInstructions = [globalInstructions, modeInstructions].filter(Boolean).join("\n\n")
 
 		this.cline = new Cline(
 			this,
@@ -272,7 +270,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			task,
 			images,
 			undefined,
-			experimentalDiffStrategy
+			experimentalDiffStrategy,
 		)
 	}
 
@@ -285,14 +283,12 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			fuzzyMatchThreshold,
 			mode,
 			customInstructions: globalInstructions,
-      experimentalDiffStrategy
+			experimentalDiffStrategy,
 		} = await this.getState()
 
 		const modePrompt = customPrompts?.[mode]
-		const modeInstructions = typeof modePrompt === 'object' ? modePrompt.customInstructions : undefined
-		const effectiveInstructions = [globalInstructions, modeInstructions]
-			.filter(Boolean)
-			.join('\n\n')
+		const modeInstructions = typeof modePrompt === "object" ? modePrompt.customInstructions : undefined
+		const effectiveInstructions = [globalInstructions, modeInstructions].filter(Boolean).join("\n\n")
 
 		this.cline = new Cline(
 			this,
@@ -303,7 +299,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			undefined,
 			undefined,
 			historyItem,
-			experimentalDiffStrategy
+			experimentalDiffStrategy,
 		)
 	}
 
@@ -403,7 +399,6 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			async (message: WebviewMessage) => {
 				switch (message.type) {
 					case "webviewDidLaunch":
-
 						this.postStateToWebview()
 						this.workspaceTracker?.initializeFilePaths() // don't await
 						getTheme().then((theme) =>
@@ -450,53 +445,53 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 							}
 						})
 
+						this.configManager
+							.ListConfig()
+							.then(async (listApiConfig) => {
+								if (!listApiConfig) {
+									return
+								}
 
-						this.configManager.ListConfig().then(async (listApiConfig) => {
-
-							if (!listApiConfig) {
-								return
-							}
-
-							if (listApiConfig.length === 1) {
-								// check if first time init then sync with exist config
-								if (!checkExistKey(listApiConfig[0])) {
-									const {
-										apiConfiguration,
-									} = await this.getState()
-									await this.configManager.SaveConfig(listApiConfig[0].name ?? "default", apiConfiguration)
-									listApiConfig[0].apiProvider = apiConfiguration.apiProvider
+								if (listApiConfig.length === 1) {
+									// check if first time init then sync with exist config
+									if (!checkExistKey(listApiConfig[0])) {
+										const { apiConfiguration } = await this.getState()
+										await this.configManager.SaveConfig(
+											listApiConfig[0].name ?? "default",
+											apiConfiguration,
+										)
+										listApiConfig[0].apiProvider = apiConfiguration.apiProvider
+									}
 								}
-							}
 
-							let currentConfigName = await this.getGlobalState("currentApiConfigName") as string
+								let currentConfigName = (await this.getGlobalState("currentApiConfigName")) as string
 
-							if (currentConfigName) {
-								if (!await this.configManager.HasConfig(currentConfigName)) {
-									// current config name not valid, get first config in list
-									await this.updateGlobalState("currentApiConfigName", listApiConfig?.[0]?.name)
-									if (listApiConfig?.[0]?.name) {
-										const apiConfig = await this.configManager.LoadConfig(listApiConfig?.[0]?.name);
+								if (currentConfigName) {
+									if (!(await this.configManager.HasConfig(currentConfigName))) {
+										// current config name not valid, get first config in list
+										await this.updateGlobalState("currentApiConfigName", listApiConfig?.[0]?.name)
+										if (listApiConfig?.[0]?.name) {
+											const apiConfig = await this.configManager.LoadConfig(
+												listApiConfig?.[0]?.name,
+											)
 
-										await Promise.all([
-											this.updateGlobalState("listApiConfigMeta", listApiConfig),
-											this.postMessageToWebview({ type: "listApiConfig", listApiConfig }),
-											this.updateApiConfiguration(apiConfig),
-										])
-										await this.postStateToWebview()
-										return
+											await Promise.all([
+												this.updateGlobalState("listApiConfigMeta", listApiConfig),
+												this.postMessageToWebview({ type: "listApiConfig", listApiConfig }),
+												this.updateApiConfiguration(apiConfig),
+											])
+											await this.postStateToWebview()
+											return
+										}
 									}
-
 								}
-							}
-
 
-							await Promise.all(
-								[
+								await Promise.all([
 									await this.updateGlobalState("listApiConfigMeta", listApiConfig),
-									await this.postMessageToWebview({ type: "listApiConfig", listApiConfig })
-								]
-							)
-						}).catch(console.error);
+									await this.postMessageToWebview({ type: "listApiConfig", listApiConfig }),
+								])
+							})
+							.catch(console.error)
 
 						break
 					case "newTask":
@@ -593,7 +588,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 						break
 					case "refreshOpenAiModels":
 						if (message?.values?.baseUrl && message?.values?.apiKey) {
-							const openAiModels = await this.getOpenAiModels(message?.values?.baseUrl, message?.values?.apiKey)
+							const openAiModels = await this.getOpenAiModels(
+								message?.values?.baseUrl,
+								message?.values?.apiKey,
+							)
 							this.postMessageToWebview({ type: "openAiModels", openAiModels })
 						}
 						break
@@ -625,12 +623,12 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 
 						break
 					case "allowedCommands":
-						await this.context.globalState.update('allowedCommands', message.commands);
+						await this.context.globalState.update("allowedCommands", message.commands)
 						// Also update workspace settings
 						await vscode.workspace
-							.getConfiguration('roo-cline')
-							.update('allowedCommands', message.commands, vscode.ConfigurationTarget.Global);
-						break;
+							.getConfiguration("roo-cline")
+							.update("allowedCommands", message.commands, vscode.ConfigurationTarget.Global)
+						break
 					case "openMcpSettings": {
 						const mcpSettingsFilePath = await this.mcpHub?.getMcpSettingsFilePath()
 						if (mcpSettingsFilePath) {
@@ -651,7 +649,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 							await this.mcpHub?.toggleToolAlwaysAllow(
 								message.serverName!,
 								message.toolName!,
-								message.alwaysAllow!
+								message.alwaysAllow!,
 							)
 						} catch (error) {
 							console.error(`Failed to toggle auto-approve for tool ${message.toolName}:`, error)
@@ -660,10 +658,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 					}
 					case "toggleMcpServer": {
 						try {
-							await this.mcpHub?.toggleServerDisabled(
-								message.serverName!,
-								message.disabled!
-							)
+							await this.mcpHub?.toggleServerDisabled(message.serverName!, message.disabled!)
 						} catch (error) {
 							console.error(`Failed to toggle MCP server ${message.serverName}:`, error)
 						}
@@ -683,7 +678,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 					case "soundEnabled":
 						const soundEnabled = message.bool ?? true
 						await this.updateGlobalState("soundEnabled", soundEnabled)
-						setSoundEnabled(soundEnabled)  // Add this line to update the sound utility
+						setSoundEnabled(soundEnabled) // Add this line to update the sound utility
 						await this.postStateToWebview()
 						break
 					case "soundVolume":
@@ -729,84 +724,84 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 					case "mode":
 						const newMode = message.text as Mode
 						await this.updateGlobalState("mode", newMode)
-						
+
 						// Load the saved API config for the new mode if it exists
 						const savedConfigId = await this.configManager.GetModeConfigId(newMode)
 						const listApiConfig = await this.configManager.ListConfig()
-						
+
 						// Update listApiConfigMeta first to ensure UI has latest data
 						await this.updateGlobalState("listApiConfigMeta", listApiConfig)
-						
+
 						// If this mode has a saved config, use it
 						if (savedConfigId) {
-							const config = listApiConfig?.find(c => c.id === savedConfigId)
+							const config = listApiConfig?.find((c) => c.id === savedConfigId)
 							if (config?.name) {
 								const apiConfig = await this.configManager.LoadConfig(config.name)
 								await Promise.all([
 									this.updateGlobalState("currentApiConfigName", config.name),
-									this.updateApiConfiguration(apiConfig)
+									this.updateApiConfiguration(apiConfig),
 								])
 							}
 						} else {
 							// If no saved config for this mode, save current config as default
 							const currentApiConfigName = await this.getGlobalState("currentApiConfigName")
 							if (currentApiConfigName) {
-								const config = listApiConfig?.find(c => c.name === currentApiConfigName)
+								const config = listApiConfig?.find((c) => c.name === currentApiConfigName)
 								if (config?.id) {
 									await this.configManager.SetModeConfig(newMode, config.id)
 								}
 							}
 						}
-						
+
 						await this.postStateToWebview()
 						break
 					case "updateEnhancedPrompt":
-						const existingPrompts = await this.getGlobalState("customPrompts") || {}
-						
+						const existingPrompts = (await this.getGlobalState("customPrompts")) || {}
+
 						const updatedPrompts = {
 							...existingPrompts,
-							enhance: message.text
+							enhance: message.text,
 						}
-						
+
 						await this.updateGlobalState("customPrompts", updatedPrompts)
-						
+
 						// Get current state and explicitly include customPrompts
 						const currentState = await this.getState()
-						
+
 						const stateWithPrompts = {
 							...currentState,
-							customPrompts: updatedPrompts
+							customPrompts: updatedPrompts,
 						}
-						
+
 						// Post state with prompts
 						this.view?.webview.postMessage({
 							type: "state",
-							state: stateWithPrompts
+							state: stateWithPrompts,
 						})
 						break
 					case "updatePrompt":
 						if (message.promptMode && message.customPrompt !== undefined) {
-							const existingPrompts = await this.getGlobalState("customPrompts") || {}
-							
+							const existingPrompts = (await this.getGlobalState("customPrompts")) || {}
+
 							const updatedPrompts = {
 								...existingPrompts,
-								[message.promptMode]: message.customPrompt
+								[message.promptMode]: message.customPrompt,
 							}
-							
+
 							await this.updateGlobalState("customPrompts", updatedPrompts)
-							
+
 							// Get current state and explicitly include customPrompts
 							const currentState = await this.getState()
-							
+
 							const stateWithPrompts = {
 								...currentState,
-								customPrompts: updatedPrompts
+								customPrompts: updatedPrompts,
 							}
-							
+
 							// Post state with prompts
 							this.view?.webview.postMessage({
 								type: "state",
-								state: stateWithPrompts
+								state: stateWithPrompts,
 							})
 						}
 						break
@@ -817,60 +812,79 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 							"Just this message",
 							"This and all subsequent messages",
 						)
-						if ((answer === "Just this message" || answer === "This and all subsequent messages") &&
-							this.cline && typeof message.value === 'number' && message.value) {
-							const timeCutoff = message.value - 1000; // 1 second buffer before the message to delete
-							const messageIndex = this.cline.clineMessages.findIndex(msg => msg.ts && msg.ts >= timeCutoff)
-							const apiConversationHistoryIndex = this.cline.apiConversationHistory.findIndex(msg => msg.ts && msg.ts >= timeCutoff)
-							
+						if (
+							(answer === "Just this message" || answer === "This and all subsequent messages") &&
+							this.cline &&
+							typeof message.value === "number" &&
+							message.value
+						) {
+							const timeCutoff = message.value - 1000 // 1 second buffer before the message to delete
+							const messageIndex = this.cline.clineMessages.findIndex(
+								(msg) => msg.ts && msg.ts >= timeCutoff,
+							)
+							const apiConversationHistoryIndex = this.cline.apiConversationHistory.findIndex(
+								(msg) => msg.ts && msg.ts >= timeCutoff,
+							)
+
 							if (messageIndex !== -1) {
 								const { historyItem } = await this.getTaskWithId(this.cline.taskId)
-								
+
 								if (answer === "Just this message") {
 									// Find the next user message first
 									const nextUserMessage = this.cline.clineMessages
 										.slice(messageIndex + 1)
-										.find(msg => msg.type === "say" && msg.say === "user_feedback")
-									
+										.find((msg) => msg.type === "say" && msg.say === "user_feedback")
+
 									// Handle UI messages
 									if (nextUserMessage) {
 										// Find absolute index of next user message
-										const nextUserMessageIndex = this.cline.clineMessages.findIndex(msg => msg === nextUserMessage)
+										const nextUserMessageIndex = this.cline.clineMessages.findIndex(
+											(msg) => msg === nextUserMessage,
+										)
 										// Keep messages before current message and after next user message
 										await this.cline.overwriteClineMessages([
 											...this.cline.clineMessages.slice(0, messageIndex),
-											...this.cline.clineMessages.slice(nextUserMessageIndex)
+											...this.cline.clineMessages.slice(nextUserMessageIndex),
 										])
 									} else {
 										// If no next user message, keep only messages before current message
 										await this.cline.overwriteClineMessages(
-											this.cline.clineMessages.slice(0, messageIndex)
+											this.cline.clineMessages.slice(0, messageIndex),
 										)
 									}
-									
+
 									// Handle API messages
 									if (apiConversationHistoryIndex !== -1) {
 										if (nextUserMessage && nextUserMessage.ts) {
 											// Keep messages before current API message and after next user message
 											await this.cline.overwriteApiConversationHistory([
-												...this.cline.apiConversationHistory.slice(0, apiConversationHistoryIndex),
-												...this.cline.apiConversationHistory.filter(msg => msg.ts && msg.ts >= nextUserMessage.ts)
+												...this.cline.apiConversationHistory.slice(
+													0,
+													apiConversationHistoryIndex,
+												),
+												...this.cline.apiConversationHistory.filter(
+													(msg) => msg.ts && msg.ts >= nextUserMessage.ts,
+												),
 											])
 										} else {
 											// If no next user message, keep only messages before current API message
 											await this.cline.overwriteApiConversationHistory(
-												this.cline.apiConversationHistory.slice(0, apiConversationHistoryIndex)
+												this.cline.apiConversationHistory.slice(0, apiConversationHistoryIndex),
 											)
 										}
 									}
 								} else if (answer === "This and all subsequent messages") {
 									// Delete this message and all that follow
-									await this.cline.overwriteClineMessages(this.cline.clineMessages.slice(0, messageIndex))
+									await this.cline.overwriteClineMessages(
+										this.cline.clineMessages.slice(0, messageIndex),
+									)
 									if (apiConversationHistoryIndex !== -1) {
-										await this.cline.overwriteApiConversationHistory(this.cline.apiConversationHistory.slice(0, apiConversationHistoryIndex))
+										await this.cline.overwriteApiConversationHistory(
+											this.cline.apiConversationHistory.slice(0, apiConversationHistoryIndex),
+										)
 									}
 								}
-								
+
 								await this.initClineWithHistoryItem(historyItem)
 							}
 						}
@@ -891,12 +905,13 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 					case "enhancePrompt":
 						if (message.text) {
 							try {
-								const { apiConfiguration, customPrompts, listApiConfigMeta, enhancementApiConfigId } = await this.getState()
-								
+								const { apiConfiguration, customPrompts, listApiConfigMeta, enhancementApiConfigId } =
+									await this.getState()
+
 								// Try to get enhancement config first, fall back to current config
 								let configToUse: ApiConfiguration = apiConfiguration
 								if (enhancementApiConfigId) {
-									const config = listApiConfigMeta?.find(c => c.id === enhancementApiConfigId)
+									const config = listApiConfigMeta?.find((c) => c.id === enhancementApiConfigId)
 									if (config?.name) {
 										const loadedConfig = await this.configManager.LoadConfig(config.name)
 										if (loadedConfig.apiProvider) {
@@ -904,41 +919,49 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 										}
 									}
 								}
-								
+
 								const getEnhancePrompt = (value: string | PromptComponent | undefined): string => {
-									if (typeof value === 'string') {
-										return value;
+									if (typeof value === "string") {
+										return value
 									}
-									return enhance.prompt; // Use the constant from modes.ts which we know is a string
+									return enhance.prompt // Use the constant from modes.ts which we know is a string
 								}
 								const enhancedPrompt = await enhancePrompt(
 									configToUse,
 									message.text,
-									getEnhancePrompt(customPrompts?.enhance)
+									getEnhancePrompt(customPrompts?.enhance),
 								)
 								await this.postMessageToWebview({
 									type: "enhancedPrompt",
-									text: enhancedPrompt
+									text: enhancedPrompt,
 								})
 							} catch (error) {
 								console.error("Error enhancing prompt:", error)
 								vscode.window.showErrorMessage("Failed to enhance prompt")
 								await this.postMessageToWebview({
-									type: "enhancedPrompt"
+									type: "enhancedPrompt",
 								})
 							}
 						}
 						break
 					case "getSystemPrompt":
 						try {
-							const { apiConfiguration, customPrompts, customInstructions, preferredLanguage, browserViewportSize, mcpEnabled } = await this.getState()
-							const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) || ''
+							const {
+								apiConfiguration,
+								customPrompts,
+								customInstructions,
+								preferredLanguage,
+								browserViewportSize,
+								mcpEnabled,
+							} = await this.getState()
+							const cwd =
+								vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) || ""
 
 							const mode = message.mode ?? defaultModeSlug
 							const instructions = await addCustomInstructions(
 								{ customInstructions, customPrompts, preferredLanguage },
 								cwd,
-								mode
+								mode,
 							)
 
 							const systemPrompt = await SYSTEM_PROMPT(
@@ -948,14 +971,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 								undefined,
 								browserViewportSize ?? "900x600",
 								mode,
-								customPrompts
+								customPrompts,
 							)
 							const fullPrompt = instructions ? `${systemPrompt}${instructions}` : systemPrompt
-							
+
 							await this.postMessageToWebview({
 								type: "systemPrompt",
 								text: fullPrompt,
-								mode: message.mode
+								mode: message.mode,
 							})
 						} catch (error) {
 							console.error("Error getting system prompt:", error)
@@ -969,7 +992,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 								const commits = await searchCommits(message.query || "", cwd)
 								await this.postMessageToWebview({
 									type: "commitSearchResults",
-									commits
+									commits,
 								})
 							} catch (error) {
 								console.error("Error searching commits:", error)
@@ -981,9 +1004,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 					case "upsertApiConfiguration":
 						if (message.text && message.apiConfiguration) {
 							try {
-								await this.configManager.SaveConfig(message.text, message.apiConfiguration);
-								let listApiConfig = await this.configManager.ListConfig();
-								
+								await this.configManager.SaveConfig(message.text, message.apiConfiguration)
+								let listApiConfig = await this.configManager.ListConfig()
+
 								await Promise.all([
 									this.updateGlobalState("listApiConfigMeta", listApiConfig),
 									this.updateApiConfiguration(message.apiConfiguration),
@@ -1002,18 +1025,16 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 							try {
 								const { oldName, newName } = message.values
 
-								await this.configManager.SaveConfig(newName, message.apiConfiguration);
+								await this.configManager.SaveConfig(newName, message.apiConfiguration)
 								await this.configManager.DeleteConfig(oldName)
 
-								let listApiConfig = await this.configManager.ListConfig();
-								const config = listApiConfig?.find(c => c.name === newName);
-								
+								let listApiConfig = await this.configManager.ListConfig()
+								const config = listApiConfig?.find((c) => c.name === newName)
+
 								// Update listApiConfigMeta first to ensure UI has latest data
-								await this.updateGlobalState("listApiConfigMeta", listApiConfig);
+								await this.updateGlobalState("listApiConfigMeta", listApiConfig)
 
-								await Promise.all([
-									this.updateGlobalState("currentApiConfigName", newName),
-								])
+								await Promise.all([this.updateGlobalState("currentApiConfigName", newName)])
 
 								await this.postStateToWebview()
 							} catch (error) {
@@ -1025,9 +1046,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 					case "loadApiConfiguration":
 						if (message.text) {
 							try {
-								const apiConfig = await this.configManager.LoadConfig(message.text);
-								const listApiConfig = await this.configManager.ListConfig();
-								
+								const apiConfig = await this.configManager.LoadConfig(message.text)
+								const listApiConfig = await this.configManager.ListConfig()
+
 								await Promise.all([
 									this.updateGlobalState("listApiConfigMeta", listApiConfig),
 									this.updateGlobalState("currentApiConfigName", message.text),
@@ -1054,16 +1075,16 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 							}
 
 							try {
-								await this.configManager.DeleteConfig(message.text);
-								const listApiConfig = await this.configManager.ListConfig();
-								
+								await this.configManager.DeleteConfig(message.text)
+								const listApiConfig = await this.configManager.ListConfig()
+
 								// Update listApiConfigMeta first to ensure UI has latest data
-								await this.updateGlobalState("listApiConfigMeta", listApiConfig);
+								await this.updateGlobalState("listApiConfigMeta", listApiConfig)
 
 								// If this was the current config, switch to first available
 								let currentApiConfigName = await this.getGlobalState("currentApiConfigName")
 								if (message.text === currentApiConfigName && listApiConfig?.[0]?.name) {
-									const apiConfig = await this.configManager.LoadConfig(listApiConfig[0].name);
+									const apiConfig = await this.configManager.LoadConfig(listApiConfig[0].name)
 									await Promise.all([
 										this.updateGlobalState("currentApiConfigName", listApiConfig[0].name),
 										this.updateApiConfiguration(apiConfig),
@@ -1079,7 +1100,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 						break
 					case "getListApiConfiguration":
 						try {
-							let listApiConfig = await this.configManager.ListConfig();
+							let listApiConfig = await this.configManager.ListConfig()
 							await this.updateGlobalState("listApiConfigMeta", listApiConfig)
 							this.postMessageToWebview({ type: "listApiConfig", listApiConfig })
 						} catch (error) {
@@ -1087,7 +1108,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 							vscode.window.showErrorMessage("Failed to get list api configuration")
 						}
 						break
-          case "experimentalDiffStrategy":
+					case "experimentalDiffStrategy":
 						await this.updateGlobalState("experimentalDiffStrategy", message.bool ?? false)
 						// Update diffStrategy in current Cline instance if it exists
 						if (this.cline) {
@@ -1103,13 +1124,13 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 
 	private async updateApiConfiguration(apiConfiguration: ApiConfiguration) {
 		// Update mode's default config
-		const { mode } = await this.getState();
+		const { mode } = await this.getState()
 		if (mode) {
-			const currentApiConfigName = await this.getGlobalState("currentApiConfigName");
-			const listApiConfig = await this.configManager.ListConfig();
-			const config = listApiConfig?.find(c => c.name === currentApiConfigName);
+			const currentApiConfigName = await this.getGlobalState("currentApiConfigName")
+			const listApiConfig = await this.configManager.ListConfig()
+			const config = listApiConfig?.find((c) => c.name === currentApiConfigName)
 			if (config?.id) {
-				await this.configManager.SetModeConfig(mode, config.id);
+				await this.configManager.SetModeConfig(mode, config.id)
 			}
 		}
 
@@ -1181,7 +1202,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 		await this.storeSecret("mistralApiKey", mistralApiKey)
 		if (this.cline) {
 			this.cline.api = buildApiHandler(apiConfiguration)
-		} 
+		}
 	}
 
 	async updateCustomInstructions(instructions?: string) {
@@ -1252,11 +1273,11 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 	// VSCode LM API
 	private async getVsCodeLmModels() {
 		try {
-			const models = await vscode.lm.selectChatModels({});
-			return models || [];
+			const models = await vscode.lm.selectChatModels({})
+			return models || []
 		} catch (error) {
-			console.error('Error fetching VS Code LM models:', error);
-			return [];
+			console.error("Error fetching VS Code LM models:", error)
+			return []
 		}
 	}
 
@@ -1346,10 +1367,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 	}
 
 	async readGlamaModels(): Promise<Record<string, ModelInfo> | undefined> {
-		const glamaModelsFilePath = path.join(
-			await this.ensureCacheDirectoryExists(),
-			GlobalFileNames.glamaModels,
-		)
+		const glamaModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.glamaModels)
 		const fileExists = await fileExistsAtPath(glamaModelsFilePath)
 		if (fileExists) {
 			const fileContents = await fs.readFile(glamaModelsFilePath, "utf8")
@@ -1359,10 +1377,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 	}
 
 	async refreshGlamaModels() {
-		const glamaModelsFilePath = path.join(
-			await this.ensureCacheDirectoryExists(),
-			GlobalFileNames.glamaModels,
-		)
+		const glamaModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.glamaModels)
 
 		let models: Record<string, ModelInfo> = {}
 		try {
@@ -1397,7 +1412,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 				}
 			*/
 			if (response.data) {
-				const rawModels = response.data;
+				const rawModels = response.data
 				const parsePrice = (price: any) => {
 					if (price) {
 						return parseFloat(price) * 1_000_000
@@ -1565,7 +1580,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 		uiMessagesFilePath: string
 		apiConversationHistory: Anthropic.MessageParam[]
 	}> {
-		const history = (await this.getGlobalState("taskHistory") as HistoryItem[] | undefined) || []
+		const history = ((await this.getGlobalState("taskHistory")) as HistoryItem[] | undefined) || []
 		const historyItem = history.find((item) => item.id === id)
 		if (historyItem) {
 			const taskDirPath = path.join(this.context.globalStorageUri.fsPath, "tasks", id)
@@ -1630,7 +1645,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 
 	async deleteTaskFromState(id: string) {
 		// Remove the task from history
-		const taskHistory = (await this.getGlobalState("taskHistory") as HistoryItem[]) || []
+		const taskHistory = ((await this.getGlobalState("taskHistory")) as HistoryItem[]) || []
 		const updatedTaskHistory = taskHistory.filter((task) => task.id !== id)
 		await this.updateGlobalState("taskHistory", updatedTaskHistory)
 
@@ -1671,13 +1686,11 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			mode,
 			customPrompts,
 			enhancementApiConfigId,
-      		experimentalDiffStrategy,
+			experimentalDiffStrategy,
 			autoApprovalEnabled,
 		} = await this.getState()
 
-		const allowedCommands = vscode.workspace
-			.getConfiguration('roo-cline')
-			.get<string[]>('allowedCommands') || []
+		const allowedCommands = vscode.workspace.getConfiguration("roo-cline").get<string[]>("allowedCommands") || []
 
 		return {
 			version: this.context.extension?.packageJSON?.version ?? "",
@@ -1700,7 +1713,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			soundVolume: soundVolume ?? 0.5,
 			browserViewportSize: browserViewportSize ?? "900x600",
 			screenshotQuality: screenshotQuality ?? 75,
-			preferredLanguage: preferredLanguage ?? 'English',
+			preferredLanguage: preferredLanguage ?? "English",
 			writeDelayMs: writeDelayMs ?? 1000,
 			terminalOutputLineLimit: terminalOutputLineLimit ?? 500,
 			fuzzyMatchThreshold: fuzzyMatchThreshold ?? 1.0,
@@ -1712,7 +1725,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			mode: mode ?? defaultModeSlug,
 			customPrompts: customPrompts ?? {},
 			enhancementApiConfigId,
-      		experimentalDiffStrategy: experimentalDiffStrategy ?? false,
+			experimentalDiffStrategy: experimentalDiffStrategy ?? false,
 			autoApprovalEnabled: autoApprovalEnabled ?? false,
 		}
 	}
@@ -1829,7 +1842,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			modeApiConfigs,
 			customPrompts,
 			enhancementApiConfigId,
-      		experimentalDiffStrategy,
+			experimentalDiffStrategy,
 			autoApprovalEnabled,
 		] = await Promise.all([
 			this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
@@ -1891,7 +1904,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			this.getGlobalState("modeApiConfigs") as Promise<Record<Mode, string> | undefined>,
 			this.getGlobalState("customPrompts") as Promise<CustomPrompts | undefined>,
 			this.getGlobalState("enhancementApiConfigId") as Promise<string | undefined>,
-      		this.getGlobalState("experimentalDiffStrategy") as Promise<boolean | undefined>,
+			this.getGlobalState("experimentalDiffStrategy") as Promise<boolean | undefined>,
 			this.getGlobalState("autoApprovalEnabled") as Promise<boolean | undefined>,
 		])
 
@@ -1962,48 +1975,50 @@ export class ClineProvider implements vscode.WebviewViewProvider {
 			writeDelayMs: writeDelayMs ?? 1000,
 			terminalOutputLineLimit: terminalOutputLineLimit ?? 500,
 			mode: mode ?? defaultModeSlug,
-			preferredLanguage: preferredLanguage ?? (() => {
-				// Get VSCode's locale setting
-				const vscodeLang = vscode.env.language;
-				// Map VSCode locale to our supported languages
-				const langMap: { [key: string]: string } = {
-					'en': 'English',
-					'ar': 'Arabic',
-					'pt-br': 'Brazilian Portuguese',
-					'cs': 'Czech',
-					'fr': 'French',
-					'de': 'German',
-					'hi': 'Hindi',
-					'hu': 'Hungarian',
-					'it': 'Italian',
-					'ja': 'Japanese',
-					'ko': 'Korean',
-					'pl': 'Polish',
-					'pt': 'Portuguese',
-					'ru': 'Russian',
-					'zh-cn': 'Simplified Chinese',
-					'es': 'Spanish',
-					'zh-tw': 'Traditional Chinese',
-					'tr': 'Turkish'
-				};
-				// Return mapped language or default to English
-				return langMap[vscodeLang.split('-')[0]] ?? 'English';
-			})(),
+			preferredLanguage:
+				preferredLanguage ??
+				(() => {
+					// Get VSCode's locale setting
+					const vscodeLang = vscode.env.language
+					// Map VSCode locale to our supported languages
+					const langMap: { [key: string]: string } = {
+						en: "English",
+						ar: "Arabic",
+						"pt-br": "Brazilian Portuguese",
+						cs: "Czech",
+						fr: "French",
+						de: "German",
+						hi: "Hindi",
+						hu: "Hungarian",
+						it: "Italian",
+						ja: "Japanese",
+						ko: "Korean",
+						pl: "Polish",
+						pt: "Portuguese",
+						ru: "Russian",
+						"zh-cn": "Simplified Chinese",
+						es: "Spanish",
+						"zh-tw": "Traditional Chinese",
+						tr: "Turkish",
+					}
+					// Return mapped language or default to English
+					return langMap[vscodeLang.split("-")[0]] ?? "English"
+				})(),
 			mcpEnabled: mcpEnabled ?? true,
 			alwaysApproveResubmit: alwaysApproveResubmit ?? false,
 			requestDelaySeconds: requestDelaySeconds ?? 5,
 			currentApiConfigName: currentApiConfigName ?? "default",
 			listApiConfigMeta: listApiConfigMeta ?? [],
-			modeApiConfigs: modeApiConfigs ?? {} as Record<Mode, string>,
+			modeApiConfigs: modeApiConfigs ?? ({} as Record<Mode, string>),
 			customPrompts: customPrompts ?? {},
 			enhancementApiConfigId,
-      		experimentalDiffStrategy: experimentalDiffStrategy ?? false,
+			experimentalDiffStrategy: experimentalDiffStrategy ?? false,
 			autoApprovalEnabled: autoApprovalEnabled ?? false,
 		}
 	}
 
 	async updateTaskHistory(item: HistoryItem): Promise<HistoryItem[]> {
-		const history = (await this.getGlobalState("taskHistory") as HistoryItem[] | undefined) || []
+		const history = ((await this.getGlobalState("taskHistory")) as HistoryItem[] | undefined) || []
 		const existingItemIndex = history.findIndex((h) => h.id === item.id)
 
 		if (existingItemIndex !== -1) {

+ 947 - 967
src/core/webview/__tests__/ClineProvider.test.ts

@@ -1,1010 +1,990 @@
-import { ClineProvider } from '../ClineProvider'
-import * as vscode from 'vscode'
-import { ExtensionMessage, ExtensionState } from '../../../shared/ExtensionMessage'
-import { setSoundEnabled } from '../../../utils/sound'
-import { defaultModeSlug, modes } from '../../../shared/modes';
+import { ClineProvider } from "../ClineProvider"
+import * as vscode from "vscode"
+import { ExtensionMessage, ExtensionState } from "../../../shared/ExtensionMessage"
+import { setSoundEnabled } from "../../../utils/sound"
+import { defaultModeSlug, modes } from "../../../shared/modes"
 
 // Mock delay module
-jest.mock('delay', () => {
-    const delayFn = (ms: number) => Promise.resolve();
-    delayFn.createDelay = () => delayFn;
-    delayFn.reject = () => Promise.reject(new Error('Delay rejected'));
-    delayFn.range = () => Promise.resolve();
-    return delayFn;
-});
+jest.mock("delay", () => {
+	const delayFn = (ms: number) => Promise.resolve()
+	delayFn.createDelay = () => delayFn
+	delayFn.reject = () => Promise.reject(new Error("Delay rejected"))
+	delayFn.range = () => Promise.resolve()
+	return delayFn
+})
 
 // Mock MCP-related modules
-jest.mock('@modelcontextprotocol/sdk/types.js', () => ({
-    CallToolResultSchema: {},
-    ListResourcesResultSchema: {},
-    ListResourceTemplatesResultSchema: {},
-    ListToolsResultSchema: {},
-    ReadResourceResultSchema: {},
-    ErrorCode: {
-        InvalidRequest: 'InvalidRequest',
-        MethodNotFound: 'MethodNotFound',
-        InternalError: 'InternalError'
-    },
-    McpError: class McpError extends Error {
-        code: string;
-        constructor(code: string, message: string) {
-            super(message);
-            this.code = code;
-            this.name = 'McpError';
-        }
-    }
-}), { virtual: true });
-
-jest.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
-    Client: jest.fn().mockImplementation(() => ({
-        connect: jest.fn().mockResolvedValue(undefined),
-        close: jest.fn().mockResolvedValue(undefined),
-        listTools: jest.fn().mockResolvedValue({ tools: [] }),
-        callTool: jest.fn().mockResolvedValue({ content: [] })
-    }))
-}), { virtual: true });
-
-jest.mock('@modelcontextprotocol/sdk/client/stdio.js', () => ({
-    StdioClientTransport: jest.fn().mockImplementation(() => ({
-        connect: jest.fn().mockResolvedValue(undefined),
-        close: jest.fn().mockResolvedValue(undefined)
-    }))
-}), { virtual: true });
+jest.mock(
+	"@modelcontextprotocol/sdk/types.js",
+	() => ({
+		CallToolResultSchema: {},
+		ListResourcesResultSchema: {},
+		ListResourceTemplatesResultSchema: {},
+		ListToolsResultSchema: {},
+		ReadResourceResultSchema: {},
+		ErrorCode: {
+			InvalidRequest: "InvalidRequest",
+			MethodNotFound: "MethodNotFound",
+			InternalError: "InternalError",
+		},
+		McpError: class McpError extends Error {
+			code: string
+			constructor(code: string, message: string) {
+				super(message)
+				this.code = code
+				this.name = "McpError"
+			}
+		},
+	}),
+	{ virtual: true },
+)
+
+jest.mock(
+	"@modelcontextprotocol/sdk/client/index.js",
+	() => ({
+		Client: jest.fn().mockImplementation(() => ({
+			connect: jest.fn().mockResolvedValue(undefined),
+			close: jest.fn().mockResolvedValue(undefined),
+			listTools: jest.fn().mockResolvedValue({ tools: [] }),
+			callTool: jest.fn().mockResolvedValue({ content: [] }),
+		})),
+	}),
+	{ virtual: true },
+)
+
+jest.mock(
+	"@modelcontextprotocol/sdk/client/stdio.js",
+	() => ({
+		StdioClientTransport: jest.fn().mockImplementation(() => ({
+			connect: jest.fn().mockResolvedValue(undefined),
+			close: jest.fn().mockResolvedValue(undefined),
+		})),
+	}),
+	{ virtual: true },
+)
 
 // Mock dependencies
-jest.mock('vscode', () => ({
-    ExtensionContext: jest.fn(),
-    OutputChannel: jest.fn(),
-    WebviewView: jest.fn(),
-    Uri: {
-        joinPath: jest.fn(),
-        file: jest.fn()
-    },
-    window: {
-        showInformationMessage: jest.fn(),
-        showErrorMessage: jest.fn(),
-    },
-    workspace: {
-        getConfiguration: jest.fn().mockReturnValue({
-            get: jest.fn().mockReturnValue([]),
-            update: jest.fn()
-        }),
-        onDidChangeConfiguration: jest.fn().mockImplementation((callback) => ({
-            dispose: jest.fn()
-        })),
-        onDidSaveTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
-        onDidChangeTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
-        onDidOpenTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
-        onDidCloseTextDocument: jest.fn(() => ({ dispose: jest.fn() }))
-    },
-    env: {
-        uriScheme: 'vscode',
-        language: 'en'
-    }
+jest.mock("vscode", () => ({
+	ExtensionContext: jest.fn(),
+	OutputChannel: jest.fn(),
+	WebviewView: jest.fn(),
+	Uri: {
+		joinPath: jest.fn(),
+		file: jest.fn(),
+	},
+	window: {
+		showInformationMessage: jest.fn(),
+		showErrorMessage: jest.fn(),
+	},
+	workspace: {
+		getConfiguration: jest.fn().mockReturnValue({
+			get: jest.fn().mockReturnValue([]),
+			update: jest.fn(),
+		}),
+		onDidChangeConfiguration: jest.fn().mockImplementation((callback) => ({
+			dispose: jest.fn(),
+		})),
+		onDidSaveTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
+		onDidChangeTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
+		onDidOpenTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
+		onDidCloseTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
+	},
+	env: {
+		uriScheme: "vscode",
+		language: "en",
+	},
 }))
 
 // Mock sound utility
-jest.mock('../../../utils/sound', () => ({
-    setSoundEnabled: jest.fn()
+jest.mock("../../../utils/sound", () => ({
+	setSoundEnabled: jest.fn(),
 }))
 
 // Mock ESM modules
-jest.mock('p-wait-for', () => ({
-    __esModule: true,
-    default: jest.fn().mockResolvedValue(undefined)
+jest.mock("p-wait-for", () => ({
+	__esModule: true,
+	default: jest.fn().mockResolvedValue(undefined),
 }))
 
 // Mock fs/promises
-jest.mock('fs/promises', () => ({
-    mkdir: jest.fn(),
-    writeFile: jest.fn(),
-    readFile: jest.fn(),
-    unlink: jest.fn(),
-    rmdir: jest.fn()
+jest.mock("fs/promises", () => ({
+	mkdir: jest.fn(),
+	writeFile: jest.fn(),
+	readFile: jest.fn(),
+	unlink: jest.fn(),
+	rmdir: jest.fn(),
 }))
 
 // Mock axios
-jest.mock('axios', () => ({
-    get: jest.fn().mockResolvedValue({ data: { data: [] } }),
-    post: jest.fn()
+jest.mock("axios", () => ({
+	get: jest.fn().mockResolvedValue({ data: { data: [] } }),
+	post: jest.fn(),
 }))
 
 // Mock buildApiHandler
-jest.mock('../../../api', () => ({
-    buildApiHandler: jest.fn()
+jest.mock("../../../api", () => ({
+	buildApiHandler: jest.fn(),
 }))
 
 // Mock system prompt
-jest.mock('../../prompts/system', () => ({
-    SYSTEM_PROMPT: jest.fn().mockImplementation(async () => 'mocked system prompt'),
-    codeMode: 'code',
-    addCustomInstructions: jest.fn().mockImplementation(async () => '')
+jest.mock("../../prompts/system", () => ({
+	SYSTEM_PROMPT: jest.fn().mockImplementation(async () => "mocked system prompt"),
+	codeMode: "code",
+	addCustomInstructions: jest.fn().mockImplementation(async () => ""),
 }))
 
 // Mock WorkspaceTracker
-jest.mock('../../../integrations/workspace/WorkspaceTracker', () => {
-    return jest.fn().mockImplementation(() => ({
-        initializeFilePaths: jest.fn(),
-        dispose: jest.fn()
-    }))
+jest.mock("../../../integrations/workspace/WorkspaceTracker", () => {
+	return jest.fn().mockImplementation(() => ({
+		initializeFilePaths: jest.fn(),
+		dispose: jest.fn(),
+	}))
 })
 
 // Mock Cline
-jest.mock('../../Cline', () => ({
-    Cline: jest.fn().mockImplementation((
-        provider,
-        apiConfiguration,
-        customInstructions,
-        diffEnabled,
-        fuzzyMatchThreshold,
-        task,
-        taskId
-    ) => ({
-        abortTask: jest.fn(),
-        handleWebviewAskResponse: jest.fn(),
-        clineMessages: [],
-        apiConversationHistory: [],
-        overwriteClineMessages: jest.fn(),
-        overwriteApiConversationHistory: jest.fn(),
-        taskId: taskId || 'test-task-id'
-    }))
+jest.mock("../../Cline", () => ({
+	Cline: jest
+		.fn()
+		.mockImplementation(
+			(provider, apiConfiguration, customInstructions, diffEnabled, fuzzyMatchThreshold, task, taskId) => ({
+				abortTask: jest.fn(),
+				handleWebviewAskResponse: jest.fn(),
+				clineMessages: [],
+				apiConversationHistory: [],
+				overwriteClineMessages: jest.fn(),
+				overwriteApiConversationHistory: jest.fn(),
+				taskId: taskId || "test-task-id",
+			}),
+		),
 }))
 
 // Mock extract-text
-jest.mock('../../../integrations/misc/extract-text', () => ({
-    extractTextFromFile: jest.fn().mockImplementation(async (filePath: string) => {
-        const content = 'const x = 1;\nconst y = 2;\nconst z = 3;'
-        const lines = content.split('\n')
-        return lines.map((line, index) => `${index + 1} | ${line}`).join('\n')
-    })
+jest.mock("../../../integrations/misc/extract-text", () => ({
+	extractTextFromFile: jest.fn().mockImplementation(async (filePath: string) => {
+		const content = "const x = 1;\nconst y = 2;\nconst z = 3;"
+		const lines = content.split("\n")
+		return lines.map((line, index) => `${index + 1} | ${line}`).join("\n")
+	}),
 }))
 
 // Spy on console.error and console.log to suppress expected messages
 beforeAll(() => {
-    jest.spyOn(console, 'error').mockImplementation(() => {})
-    jest.spyOn(console, 'log').mockImplementation(() => {})
+	jest.spyOn(console, "error").mockImplementation(() => {})
+	jest.spyOn(console, "log").mockImplementation(() => {})
 })
 
 afterAll(() => {
-    jest.restoreAllMocks()
+	jest.restoreAllMocks()
 })
 
-describe('ClineProvider', () => {
-    let provider: ClineProvider
-    let mockContext: vscode.ExtensionContext
-    let mockOutputChannel: vscode.OutputChannel
-    let mockWebviewView: vscode.WebviewView
-    let mockPostMessage: jest.Mock
-    let visibilityChangeCallback: (e?: unknown) => void
-
-    beforeEach(() => {
-        // Reset mocks
-        jest.clearAllMocks()
-
-        // Mock context
-        mockContext = {
-            extensionPath: '/test/path',
-            extensionUri: {} as vscode.Uri,
-            globalState: {
-                get: jest.fn().mockImplementation((key: string) => {
-                    switch (key) {
-                        case 'mode':
-                            return 'architect'
-                        case 'currentApiConfigName':
-                            return 'new-config'
-                        default:
-                            return undefined
-                    }
-                }),
-                update: jest.fn(),
-                keys: jest.fn().mockReturnValue([]),
-            },
-            secrets: {
-                get: jest.fn(),
-                store: jest.fn(),
-                delete: jest.fn()
-            },
-            subscriptions: [],
-            extension: {
-                packageJSON: { version: '1.0.0' }
-            },
-            globalStorageUri: {
-                fsPath: '/test/storage/path'
-            }
-        } as unknown as vscode.ExtensionContext
-
-        // Mock output channel
-        mockOutputChannel = {
-            appendLine: jest.fn(),
-            clear: jest.fn(),
-            dispose: jest.fn()
-        } as unknown as vscode.OutputChannel
-
-        // Mock webview
-        mockPostMessage = jest.fn()
-        mockWebviewView = {
-            webview: {
-                postMessage: mockPostMessage,
-                html: '',
-                options: {},
-                onDidReceiveMessage: jest.fn(),
-                asWebviewUri: jest.fn()
-            },
-            visible: true,
-            onDidDispose: jest.fn().mockImplementation((callback) => {
-                callback()
-                return { dispose: jest.fn() }
-            }),
-            onDidChangeVisibility: jest.fn().mockImplementation((callback) => {
-                visibilityChangeCallback = callback
-                return { dispose: jest.fn() }
-            })
-        } as unknown as vscode.WebviewView
-
-        provider = new ClineProvider(mockContext, mockOutputChannel)
-    })
-
-    test('constructor initializes correctly', () => {
-        expect(provider).toBeInstanceOf(ClineProvider)
-        // Since getVisibleInstance returns the last instance where view.visible is true
-        // @ts-ignore - accessing private property for testing
-        provider.view = mockWebviewView
-        expect(ClineProvider.getVisibleInstance()).toBe(provider)
-    })
-
-    test('resolveWebviewView sets up webview correctly', () => {
-        provider.resolveWebviewView(mockWebviewView)
-        
-        expect(mockWebviewView.webview.options).toEqual({
-            enableScripts: true,
-            localResourceRoots: [mockContext.extensionUri]
-        })
-        expect(mockWebviewView.webview.html).toContain('<!DOCTYPE html>')
-    })
-
-    test('postMessageToWebview sends message to webview', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        
-        const mockState: ExtensionState = {
-            version: '1.0.0',
-            preferredLanguage: 'English',
-            clineMessages: [],
-            taskHistory: [],
-            shouldShowAnnouncement: false,
-            apiConfiguration: {
-                apiProvider: 'openrouter'
-            },
-            customInstructions: undefined,
-            alwaysAllowReadOnly: false,
-            alwaysAllowWrite: false,
-            alwaysAllowExecute: false,
-            alwaysAllowBrowser: false,
-            alwaysAllowMcp: false,
-            uriScheme: 'vscode',
-            soundEnabled: false,
-            diffEnabled: false,
-            writeDelayMs: 1000,
-            browserViewportSize: "900x600",
-            fuzzyMatchThreshold: 1.0,
-            mcpEnabled: true,
-            requestDelaySeconds: 5,
-            mode: defaultModeSlug,
-        }
-        
-        const message: ExtensionMessage = { 
-            type: 'state', 
-            state: mockState
-        }
-        await provider.postMessageToWebview(message)
-        
-        expect(mockPostMessage).toHaveBeenCalledWith(message)
-    })
-
-    test('handles webviewDidLaunch message', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-
-        // Get the message handler from onDidReceiveMessage
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Simulate webviewDidLaunch message
-        await messageHandler({ type: 'webviewDidLaunch' })
-
-        // Should post state and theme to webview
-        expect(mockPostMessage).toHaveBeenCalled()
-    })
-
-    test('clearTask aborts current task', async () => {
-        const mockAbortTask = jest.fn()
-        // @ts-ignore - accessing private property for testing
-        provider.cline = { abortTask: mockAbortTask }
-
-        await provider.clearTask()
-
-        expect(mockAbortTask).toHaveBeenCalled()
-        // @ts-ignore - accessing private property for testing
-        expect(provider.cline).toBeUndefined()
-    })
-
-    test('getState returns correct initial state', async () => {
-        const state = await provider.getState()
-        
-        expect(state).toHaveProperty('apiConfiguration')
-        expect(state.apiConfiguration).toHaveProperty('apiProvider')
-        expect(state).toHaveProperty('customInstructions')
-        expect(state).toHaveProperty('alwaysAllowReadOnly')
-        expect(state).toHaveProperty('alwaysAllowWrite')
-        expect(state).toHaveProperty('alwaysAllowExecute')
-        expect(state).toHaveProperty('alwaysAllowBrowser')
-        expect(state).toHaveProperty('taskHistory')
-        expect(state).toHaveProperty('soundEnabled')
-        expect(state).toHaveProperty('diffEnabled')
-        expect(state).toHaveProperty('writeDelayMs')
-    })
-
-    test('preferredLanguage defaults to VSCode language when not set', async () => {
-        // Mock VSCode language as Spanish
-        (vscode.env as any).language = 'es-ES';
-        
-        const state = await provider.getState();
-        expect(state.preferredLanguage).toBe('Spanish');
-    })
-
-    test('preferredLanguage defaults to English for unsupported VSCode language', async () => {
-        // Mock VSCode language as an unsupported language
-        (vscode.env as any).language = 'unsupported-LANG';
-        
-        const state = await provider.getState();
-        expect(state.preferredLanguage).toBe('English');
-    })
-
-    test('diffEnabled defaults to true when not set', async () => {
-        // Mock globalState.get to return undefined for diffEnabled
-        (mockContext.globalState.get as jest.Mock).mockReturnValue(undefined)
-        
-        const state = await provider.getState()
-        
-        expect(state.diffEnabled).toBe(true)
-    })
-
-    test('writeDelayMs defaults to 1000ms', async () => {
-        // Mock globalState.get to return undefined for writeDelayMs
-        (mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
-            if (key === 'writeDelayMs') {
-                return undefined
-            }
-            return null
-        })
-        
-        const state = await provider.getState()
-        expect(state.writeDelayMs).toBe(1000)
-    })
-
-    test('handles writeDelayMs message', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-        
-        await messageHandler({ type: 'writeDelayMs', value: 2000 })
-        
-        expect(mockContext.globalState.update).toHaveBeenCalledWith('writeDelayMs', 2000)
-        expect(mockPostMessage).toHaveBeenCalled()
-    })
-
-    test('updates sound utility when sound setting changes', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-
-        // Get the message handler from onDidReceiveMessage
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Simulate setting sound to enabled
-        await messageHandler({ type: 'soundEnabled', bool: true })
-        expect(setSoundEnabled).toHaveBeenCalledWith(true)
-        expect(mockContext.globalState.update).toHaveBeenCalledWith('soundEnabled', true)
-        expect(mockPostMessage).toHaveBeenCalled()
-
-        // Simulate setting sound to disabled
-        await messageHandler({ type: 'soundEnabled', bool: false })
-        expect(setSoundEnabled).toHaveBeenCalledWith(false)
-        expect(mockContext.globalState.update).toHaveBeenCalledWith('soundEnabled', false)
-        expect(mockPostMessage).toHaveBeenCalled()
-    })
-
-    test('requestDelaySeconds defaults to 5 seconds', async () => {
-        // Mock globalState.get to return undefined for requestDelaySeconds
-        (mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
-            if (key === 'requestDelaySeconds') {
-                return undefined
-            }
-            return null
-        })
-
-        const state = await provider.getState()
-        expect(state.requestDelaySeconds).toBe(5)
-    })
-
-    test('alwaysApproveResubmit defaults to false', async () => {
-        // Mock globalState.get to return undefined for alwaysApproveResubmit
-        (mockContext.globalState.get as jest.Mock).mockReturnValue(undefined)
-
-        const state = await provider.getState()
-        expect(state.alwaysApproveResubmit).toBe(false)
-    })
-
-    test('loads saved API config when switching modes', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Mock ConfigManager methods
-        provider.configManager = {
-            GetModeConfigId: jest.fn().mockResolvedValue('test-id'),
-            ListConfig: jest.fn().mockResolvedValue([
-                { name: 'test-config', id: 'test-id', apiProvider: 'anthropic' }
-            ]),
-            LoadConfig: jest.fn().mockResolvedValue({ apiProvider: 'anthropic' }),
-            SetModeConfig: jest.fn()
-        } as any
-
-        // Switch to architect mode
-        await messageHandler({ type: 'mode', text: 'architect' })
-
-        // Should load the saved config for architect mode
-        expect(provider.configManager.GetModeConfigId).toHaveBeenCalledWith('architect')
-        expect(provider.configManager.LoadConfig).toHaveBeenCalledWith('test-config')
-        expect(mockContext.globalState.update).toHaveBeenCalledWith('currentApiConfigName', 'test-config')
-    })
-
-    test('saves current config when switching to mode without config', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Mock ConfigManager methods
-        provider.configManager = {
-            GetModeConfigId: jest.fn().mockResolvedValue(undefined),
-            ListConfig: jest.fn().mockResolvedValue([
-                { name: 'current-config', id: 'current-id', apiProvider: 'anthropic' }
-            ]),
-            SetModeConfig: jest.fn()
-        } as any
-
-        // Mock current config name
-        (mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
-            if (key === 'currentApiConfigName') {
-                return 'current-config'
-            }
-            return undefined
-        })
-
-        // Switch to architect mode
-        await messageHandler({ type: 'mode', text: 'architect' })
-
-        // Should save current config as default for architect mode
-        expect(provider.configManager.SetModeConfig).toHaveBeenCalledWith('architect', 'current-id')
-    })
-
-    test('saves config as default for current mode when loading config', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        provider.configManager = {
-            LoadConfig: jest.fn().mockResolvedValue({ apiProvider: 'anthropic', id: 'new-id' }),
-            ListConfig: jest.fn().mockResolvedValue([
-                { name: 'new-config', id: 'new-id', apiProvider: 'anthropic' }
-            ]),
-            SetModeConfig: jest.fn(),
-            GetModeConfigId: jest.fn().mockResolvedValue(undefined)
-        } as any
-
-        // First set the mode
-        await messageHandler({ type: 'mode', text: 'architect' })
-
-        // Then load the config
-        await messageHandler({ type: 'loadApiConfiguration', text: 'new-config' })
-
-        // Should save new config as default for architect mode
-        expect(provider.configManager.SetModeConfig).toHaveBeenCalledWith('architect', 'new-id')
-    })
-
-    test('handles request delay settings messages', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Test alwaysApproveResubmit
-        await messageHandler({ type: 'alwaysApproveResubmit', bool: true })
-        expect(mockContext.globalState.update).toHaveBeenCalledWith('alwaysApproveResubmit', true)
-        expect(mockPostMessage).toHaveBeenCalled()
-
-        // Test requestDelaySeconds
-        await messageHandler({ type: 'requestDelaySeconds', value: 10 })
-        expect(mockContext.globalState.update).toHaveBeenCalledWith('requestDelaySeconds', 10)
-        expect(mockPostMessage).toHaveBeenCalled()
-    })
-
-    test('handles updatePrompt message correctly', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Mock existing prompts
-        const existingPrompts = {
-            code: 'existing code prompt',
-            architect: 'existing architect prompt'
-        }
-        ;(mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
-            if (key === 'customPrompts') {
-                return existingPrompts
-            }
-            return undefined
-        })
-
-        // Test updating a prompt
-        await messageHandler({
-            type: 'updatePrompt',
-            promptMode: 'code',
-            customPrompt: 'new code prompt'
-        })
-
-        // Verify state was updated correctly
-        expect(mockContext.globalState.update).toHaveBeenCalledWith(
-            'customPrompts',
-            {
-                ...existingPrompts,
-                code: 'new code prompt'
-            }
-        )
-
-        // Verify state was posted to webview
-        expect(mockPostMessage).toHaveBeenCalledWith(
-            expect.objectContaining({
-                type: 'state',
-                state: expect.objectContaining({
-                    customPrompts: {
-                        ...existingPrompts,
-                        code: 'new code prompt'
-                    }
-                })
-            })
-        )
-    })
-
-    test('customPrompts defaults to empty object', async () => {
-        // Mock globalState.get to return undefined for customPrompts
-        (mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
-            if (key === 'customPrompts') {
-                return undefined
-            }
-            return null
-        })
-
-        const state = await provider.getState()
-        expect(state.customPrompts).toEqual({})
-    })
-
-    test('uses mode-specific custom instructions in Cline initialization', async () => {
-        // Setup mock state
-        const modeCustomInstructions = 'Code mode instructions';
-        const mockApiConfig = {
-            apiProvider: 'openrouter',
-            openRouterModelInfo: { supportsComputerUse: true }
-        };
-
-        jest.spyOn(provider, 'getState').mockResolvedValue({
-            apiConfiguration: mockApiConfig,
-            customPrompts: {
-                code: { customInstructions: modeCustomInstructions }
-            },
-            mode: 'code',
-            diffEnabled: true,
-            fuzzyMatchThreshold: 1.0
-        } as any);
-
-        // Reset Cline mock
-        const { Cline } = require('../../Cline');
-        (Cline as jest.Mock).mockClear();
-
-        // Initialize Cline with a task
-        await provider.initClineWithTask('Test task');
-
-        // Verify Cline was initialized with mode-specific instructions
-        expect(Cline).toHaveBeenCalledWith(
-            provider,
-            mockApiConfig,
-            modeCustomInstructions,
-            true,
-            1.0,
-            'Test task',
-            undefined,
-            undefined,
-            undefined
-        );
-    });
-    test('handles mode-specific custom instructions updates', async () => {
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        // Mock existing prompts
-        const existingPrompts = {
-            code: {
-                roleDefinition: 'Code role',
-                customInstructions: 'Old instructions'
-            }
-        }
-        mockContext.globalState.get = jest.fn((key: string) => {
-            if (key === 'customPrompts') {
-                return existingPrompts
-            }
-            return undefined
-        })
-
-        // Update custom instructions for code mode
-        await messageHandler({
-            type: 'updatePrompt',
-            promptMode: 'code',
-            customPrompt: {
-                roleDefinition: 'Code role',
-                customInstructions: 'New instructions'
-            }
-        })
-
-        // Verify state was updated correctly
-        expect(mockContext.globalState.update).toHaveBeenCalledWith(
-            'customPrompts',
-            {
-                code: {
-                    roleDefinition: 'Code role',
-                    customInstructions: 'New instructions'
-                }
-            }
-        )
-    })
-
-    test('saves mode config when updating API configuration', async () => {
-        // Setup mock context with mode and config name
-        mockContext = {
-            ...mockContext,
-            globalState: {
-                ...mockContext.globalState,
-                get: jest.fn((key: string) => {
-                    if (key === 'mode') {
-                        return 'code'
-                    } else if (key === 'currentApiConfigName') {
-                        return 'test-config'
-                    }
-                    return undefined
-                }),
-                update: jest.fn(),
-                keys: jest.fn().mockReturnValue([]),
-            }
-        } as unknown as vscode.ExtensionContext
-
-        // Create new provider with updated mock context
-        provider = new ClineProvider(mockContext, mockOutputChannel)
-        provider.resolveWebviewView(mockWebviewView)
-        const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-
-        provider.configManager = {
-            ListConfig: jest.fn().mockResolvedValue([
-                { name: 'test-config', id: 'test-id', apiProvider: 'anthropic' }
-            ]),
-            SetModeConfig: jest.fn()
-        } as any
-
-        // Update API configuration
-        await messageHandler({
-            type: 'apiConfiguration',
-            apiConfiguration: { apiProvider: 'anthropic' }
-        })
-
-        // Should save config as default for current mode
-        expect(provider.configManager.SetModeConfig).toHaveBeenCalledWith('code', 'test-id')
-    })
-
-    test('file content includes line numbers', async () => {
-        const { extractTextFromFile } = require('../../../integrations/misc/extract-text')
-        const result = await extractTextFromFile('test.js')
-        expect(result).toBe('1 | const x = 1;\n2 | const y = 2;\n3 | const z = 3;')
-    })
-
-    describe('deleteMessage', () => {
-        beforeEach(() => {
-            // Mock window.showInformationMessage
-            ;(vscode.window.showInformationMessage as jest.Mock) = jest.fn()
-            provider.resolveWebviewView(mockWebviewView)
-        })
-
-        test('handles "Just this message" deletion correctly', async () => {
-            // Mock user selecting "Just this message"
-            ;(vscode.window.showInformationMessage as jest.Mock).mockResolvedValue('Just this message')
-
-            // Setup mock messages
-            const mockMessages = [
-                { ts: 1000, type: 'say', say: 'user_feedback' },     // User message 1
-                { ts: 2000, type: 'say', say: 'tool' },             // Tool message
-                { ts: 3000, type: 'say', say: 'text', value: 4000 }, // Message to delete
-                { ts: 4000, type: 'say', say: 'browser_action' },    // Response to delete
-                { ts: 5000, type: 'say', say: 'user_feedback' },     // Next user message
-                { ts: 6000, type: 'say', say: 'user_feedback' }      // Final message
-            ]
-
-            const mockApiHistory = [
-                { ts: 1000 },
-                { ts: 2000 },
-                { ts: 3000 },
-                { ts: 4000 },
-                { ts: 5000 },
-                { ts: 6000 }
-            ]
-
-            // Setup Cline instance with mock data
-            const mockCline = {
-                clineMessages: mockMessages,
-                apiConversationHistory: mockApiHistory,
-                overwriteClineMessages: jest.fn(),
-                overwriteApiConversationHistory: jest.fn(),
-                taskId: 'test-task-id',
-                abortTask: jest.fn(),
-                handleWebviewAskResponse: jest.fn()
-            }
-            // @ts-ignore - accessing private property for testing
-            provider.cline = mockCline
-
-            // Mock getTaskWithId
-            ;(provider as any).getTaskWithId = jest.fn().mockResolvedValue({
-                historyItem: { id: 'test-task-id' }
-            })
-
-            // Trigger message deletion
-            const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-            await messageHandler({ type: 'deleteMessage', value: 4000 })
-
-            // Verify correct messages were kept
-            expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([
-                mockMessages[0],
-                mockMessages[1],
-                mockMessages[4],
-                mockMessages[5]
-            ])
-
-            // Verify correct API messages were kept
-            expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([
-                mockApiHistory[0],
-                mockApiHistory[1],
-                mockApiHistory[4],
-                mockApiHistory[5]
-            ])
-        })
-
-        test('handles "This and all subsequent messages" deletion correctly', async () => {
-            // Mock user selecting "This and all subsequent messages"
-            ;(vscode.window.showInformationMessage as jest.Mock).mockResolvedValue('This and all subsequent messages')
-
-            // Setup mock messages
-            const mockMessages = [
-                { ts: 1000, type: 'say', say: 'user_feedback' },
-                { ts: 2000, type: 'say', say: 'text', value: 3000 },  // Message to delete
-                { ts: 3000, type: 'say', say: 'user_feedback' },
-                { ts: 4000, type: 'say', say: 'user_feedback' }
-            ]
-
-            const mockApiHistory = [
-                { ts: 1000 },
-                { ts: 2000 },
-                { ts: 3000 },
-                { ts: 4000 }
-            ]
-
-            // Setup Cline instance with mock data
-            const mockCline = {
-                clineMessages: mockMessages,
-                apiConversationHistory: mockApiHistory,
-                overwriteClineMessages: jest.fn(),
-                overwriteApiConversationHistory: jest.fn(),
-                taskId: 'test-task-id',
-                abortTask: jest.fn(),
-                handleWebviewAskResponse: jest.fn()
-            }
-            // @ts-ignore - accessing private property for testing
-            provider.cline = mockCline
-
-            // Mock getTaskWithId
-            ;(provider as any).getTaskWithId = jest.fn().mockResolvedValue({
-                historyItem: { id: 'test-task-id' }
-            })
-
-            // Trigger message deletion
-            const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-            await messageHandler({ type: 'deleteMessage', value: 3000 })
-
-            // Verify only messages before the deleted message were kept
-            expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([
-                mockMessages[0]
-            ])
-
-            // Verify only API messages before the deleted message were kept
-            expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([
-                mockApiHistory[0]
-            ])
-        })
-
-        test('handles Cancel correctly', async () => {
-            // Mock user selecting "Cancel"
-            ;(vscode.window.showInformationMessage as jest.Mock).mockResolvedValue('Cancel')
-
-            const mockCline = {
-                clineMessages: [{ ts: 1000 }, { ts: 2000 }],
-                apiConversationHistory: [{ ts: 1000 }, { ts: 2000 }],
-                overwriteClineMessages: jest.fn(),
-                overwriteApiConversationHistory: jest.fn(),
-                taskId: 'test-task-id'
-            }
-            // @ts-ignore - accessing private property for testing
-            provider.cline = mockCline
-
-            // Trigger message deletion
-            const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-            await messageHandler({ type: 'deleteMessage', value: 2000 })
-
-            // Verify no messages were deleted
-            expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled()
-            expect(mockCline.overwriteApiConversationHistory).not.toHaveBeenCalled()
-        })
-    })
-    
-    describe('getSystemPrompt', () => {
-        beforeEach(() => {
-            mockPostMessage.mockClear();
-            provider.resolveWebviewView(mockWebviewView);
-        });
-
-        const getMessageHandler = () => {
-            const mockCalls = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls;
-            expect(mockCalls.length).toBeGreaterThan(0);
-            return mockCalls[0][0];
-        };
-
-        test('handles mcpEnabled setting correctly', async () => {
-            // Mock getState to return mcpEnabled: true
-            jest.spyOn(provider, 'getState').mockResolvedValue({
-                apiConfiguration: {
-                    apiProvider: 'openrouter' as const,
-                    openRouterModelInfo: {
-                        supportsComputerUse: true,
-                        supportsPromptCache: false,
-                        maxTokens: 4096,
-                        contextWindow: 8192,
-                        supportsImages: false,
-                        inputPrice: 0.0,
-                        outputPrice: 0.0,
-                        description: undefined
-                    }
-                },
-                mcpEnabled: true,
-                mode: 'code' as const
-            } as any);
-
-            const handler1 = getMessageHandler();
-            expect(typeof handler1).toBe('function');
-            await handler1({ type: 'getSystemPrompt', mode: 'code' });
-
-            // Verify mcpHub is passed when mcpEnabled is true
-            expect(mockPostMessage).toHaveBeenCalledWith(
-                expect.objectContaining({
-                    type: 'systemPrompt',
-                    text: expect.any(String)
-                })
-            );
-
-            // Mock getState to return mcpEnabled: false
-            jest.spyOn(provider, 'getState').mockResolvedValue({
-                apiConfiguration: {
-                    apiProvider: 'openrouter' as const,
-                    openRouterModelInfo: {
-                        supportsComputerUse: true,
-                        supportsPromptCache: false,
-                        maxTokens: 4096,
-                        contextWindow: 8192,
-                        supportsImages: false,
-                        inputPrice: 0.0,
-                        outputPrice: 0.0,
-                        description: undefined
-                    }
-                },
-                mcpEnabled: false,
-                mode: 'code' as const
-            } as any);
-
-            const handler2 = getMessageHandler();
-            await handler2({ type: 'getSystemPrompt', mode: 'code' });
-
-            // Verify mcpHub is not passed when mcpEnabled is false
-            expect(mockPostMessage).toHaveBeenCalledWith(
-                expect.objectContaining({
-                    type: 'systemPrompt',
-                    text: expect.any(String)
-                })
-            );
-        });
-
-        test('handles errors gracefully', async () => {
-            // Mock SYSTEM_PROMPT to throw an error
-            const systemPrompt = require('../../prompts/system')
-            jest.spyOn(systemPrompt, 'SYSTEM_PROMPT').mockRejectedValueOnce(new Error('Test error'))
-
-            const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-            await messageHandler({ type: 'getSystemPrompt', mode: 'code' })
-
-            expect(vscode.window.showErrorMessage).toHaveBeenCalledWith('Failed to get system prompt')
-        })
-
-        test('uses mode-specific custom instructions in system prompt', async () => {
-            const systemPrompt = require('../../prompts/system')
-            const { addCustomInstructions } = systemPrompt
-
-            // Mock getState to return mode-specific custom instructions
-            jest.spyOn(provider, 'getState').mockResolvedValue({
-                apiConfiguration: {
-                    apiProvider: 'openrouter',
-                    openRouterModelInfo: { supportsComputerUse: true }
-                },
-                customPrompts: {
-                    code: { customInstructions: 'Code mode specific instructions' }
-                },
-                mode: 'code',
-                mcpEnabled: false,
-                browserViewportSize: '900x600'
-            } as any)
-
-            const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-            await messageHandler({ type: 'getSystemPrompt', mode: 'code' })
-
-            // Verify addCustomInstructions was called with mode-specific instructions
-            expect(addCustomInstructions).toHaveBeenCalledWith(
-                {
-                    customInstructions: undefined,
-                    customPrompts: {
-                        code: { customInstructions: 'Code mode specific instructions' }
-                    },
-                    preferredLanguage: undefined
-                },
-                expect.any(String),
-                'code'
-            )
-        })
-
-        test('uses correct mode-specific instructions when mode is specified', async () => {
-            const systemPrompt = require('../../prompts/system')
-            const { addCustomInstructions } = systemPrompt
-
-            // Mock getState to return instructions for multiple modes
-            jest.spyOn(provider, 'getState').mockResolvedValue({
-                apiConfiguration: {
-                    apiProvider: 'openrouter',
-                    openRouterModelInfo: { supportsComputerUse: true }
-                },
-                customPrompts: {
-                    code: { customInstructions: 'Code mode instructions' },
-                    architect: { customInstructions: 'Architect mode instructions' }
-                },
-                mode: 'code',
-                mcpEnabled: false,
-                browserViewportSize: '900x600'
-            } as any)
-
-            const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
-            
-            // Request architect mode prompt
-            await messageHandler({ type: 'getSystemPrompt', mode: 'architect' })
-
-            // Verify architect mode instructions were used
-            expect(addCustomInstructions).toHaveBeenCalledWith(
-                {
-                    customInstructions: undefined,
-                    customPrompts: {
-                        code: { customInstructions: 'Code mode instructions' },
-                        architect: { customInstructions: 'Architect mode instructions' }
-                    },
-                    preferredLanguage: undefined
-                },
-                expect.any(String),
-                'architect'
-            )
-        })
-    })
+describe("ClineProvider", () => {
+	let provider: ClineProvider
+	let mockContext: vscode.ExtensionContext
+	let mockOutputChannel: vscode.OutputChannel
+	let mockWebviewView: vscode.WebviewView
+	let mockPostMessage: jest.Mock
+	let visibilityChangeCallback: (e?: unknown) => void
+
+	beforeEach(() => {
+		// Reset mocks
+		jest.clearAllMocks()
+
+		// Mock context
+		mockContext = {
+			extensionPath: "/test/path",
+			extensionUri: {} as vscode.Uri,
+			globalState: {
+				get: jest.fn().mockImplementation((key: string) => {
+					switch (key) {
+						case "mode":
+							return "architect"
+						case "currentApiConfigName":
+							return "new-config"
+						default:
+							return undefined
+					}
+				}),
+				update: jest.fn(),
+				keys: jest.fn().mockReturnValue([]),
+			},
+			secrets: {
+				get: jest.fn(),
+				store: jest.fn(),
+				delete: jest.fn(),
+			},
+			subscriptions: [],
+			extension: {
+				packageJSON: { version: "1.0.0" },
+			},
+			globalStorageUri: {
+				fsPath: "/test/storage/path",
+			},
+		} as unknown as vscode.ExtensionContext
+
+		// Mock output channel
+		mockOutputChannel = {
+			appendLine: jest.fn(),
+			clear: jest.fn(),
+			dispose: jest.fn(),
+		} as unknown as vscode.OutputChannel
+
+		// Mock webview
+		mockPostMessage = jest.fn()
+		mockWebviewView = {
+			webview: {
+				postMessage: mockPostMessage,
+				html: "",
+				options: {},
+				onDidReceiveMessage: jest.fn(),
+				asWebviewUri: jest.fn(),
+			},
+			visible: true,
+			onDidDispose: jest.fn().mockImplementation((callback) => {
+				callback()
+				return { dispose: jest.fn() }
+			}),
+			onDidChangeVisibility: jest.fn().mockImplementation((callback) => {
+				visibilityChangeCallback = callback
+				return { dispose: jest.fn() }
+			}),
+		} as unknown as vscode.WebviewView
+
+		provider = new ClineProvider(mockContext, mockOutputChannel)
+	})
+
+	test("constructor initializes correctly", () => {
+		expect(provider).toBeInstanceOf(ClineProvider)
+		// Since getVisibleInstance returns the last instance where view.visible is true
+		// @ts-ignore - accessing private property for testing
+		provider.view = mockWebviewView
+		expect(ClineProvider.getVisibleInstance()).toBe(provider)
+	})
+
+	test("resolveWebviewView sets up webview correctly", () => {
+		provider.resolveWebviewView(mockWebviewView)
+
+		expect(mockWebviewView.webview.options).toEqual({
+			enableScripts: true,
+			localResourceRoots: [mockContext.extensionUri],
+		})
+		expect(mockWebviewView.webview.html).toContain("<!DOCTYPE html>")
+	})
+
+	test("postMessageToWebview sends message to webview", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+
+		const mockState: ExtensionState = {
+			version: "1.0.0",
+			preferredLanguage: "English",
+			clineMessages: [],
+			taskHistory: [],
+			shouldShowAnnouncement: false,
+			apiConfiguration: {
+				apiProvider: "openrouter",
+			},
+			customInstructions: undefined,
+			alwaysAllowReadOnly: false,
+			alwaysAllowWrite: false,
+			alwaysAllowExecute: false,
+			alwaysAllowBrowser: false,
+			alwaysAllowMcp: false,
+			uriScheme: "vscode",
+			soundEnabled: false,
+			diffEnabled: false,
+			writeDelayMs: 1000,
+			browserViewportSize: "900x600",
+			fuzzyMatchThreshold: 1.0,
+			mcpEnabled: true,
+			requestDelaySeconds: 5,
+			mode: defaultModeSlug,
+		}
+
+		const message: ExtensionMessage = {
+			type: "state",
+			state: mockState,
+		}
+		await provider.postMessageToWebview(message)
+
+		expect(mockPostMessage).toHaveBeenCalledWith(message)
+	})
+
+	test("handles webviewDidLaunch message", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+
+		// Get the message handler from onDidReceiveMessage
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Simulate webviewDidLaunch message
+		await messageHandler({ type: "webviewDidLaunch" })
+
+		// Should post state and theme to webview
+		expect(mockPostMessage).toHaveBeenCalled()
+	})
+
+	test("clearTask aborts current task", async () => {
+		const mockAbortTask = jest.fn()
+		// @ts-ignore - accessing private property for testing
+		provider.cline = { abortTask: mockAbortTask }
+
+		await provider.clearTask()
+
+		expect(mockAbortTask).toHaveBeenCalled()
+		// @ts-ignore - accessing private property for testing
+		expect(provider.cline).toBeUndefined()
+	})
+
+	test("getState returns correct initial state", async () => {
+		const state = await provider.getState()
+
+		expect(state).toHaveProperty("apiConfiguration")
+		expect(state.apiConfiguration).toHaveProperty("apiProvider")
+		expect(state).toHaveProperty("customInstructions")
+		expect(state).toHaveProperty("alwaysAllowReadOnly")
+		expect(state).toHaveProperty("alwaysAllowWrite")
+		expect(state).toHaveProperty("alwaysAllowExecute")
+		expect(state).toHaveProperty("alwaysAllowBrowser")
+		expect(state).toHaveProperty("taskHistory")
+		expect(state).toHaveProperty("soundEnabled")
+		expect(state).toHaveProperty("diffEnabled")
+		expect(state).toHaveProperty("writeDelayMs")
+	})
+
+	test("preferredLanguage defaults to VSCode language when not set", async () => {
+		// Mock VSCode language as Spanish
+		;(vscode.env as any).language = "es-ES"
+
+		const state = await provider.getState()
+		expect(state.preferredLanguage).toBe("Spanish")
+	})
+
+	test("preferredLanguage defaults to English for unsupported VSCode language", async () => {
+		// Mock VSCode language as an unsupported language
+		;(vscode.env as any).language = "unsupported-LANG"
+
+		const state = await provider.getState()
+		expect(state.preferredLanguage).toBe("English")
+	})
+
+	test("diffEnabled defaults to true when not set", async () => {
+		// Mock globalState.get to return undefined for diffEnabled
+		;(mockContext.globalState.get as jest.Mock).mockReturnValue(undefined)
+
+		const state = await provider.getState()
+
+		expect(state.diffEnabled).toBe(true)
+	})
+
+	test("writeDelayMs defaults to 1000ms", async () => {
+		// Mock globalState.get to return undefined for writeDelayMs
+		;(mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
+			if (key === "writeDelayMs") {
+				return undefined
+			}
+			return null
+		})
+
+		const state = await provider.getState()
+		expect(state.writeDelayMs).toBe(1000)
+	})
+
+	test("handles writeDelayMs message", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		await messageHandler({ type: "writeDelayMs", value: 2000 })
+
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("writeDelayMs", 2000)
+		expect(mockPostMessage).toHaveBeenCalled()
+	})
+
+	test("updates sound utility when sound setting changes", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+
+		// Get the message handler from onDidReceiveMessage
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Simulate setting sound to enabled
+		await messageHandler({ type: "soundEnabled", bool: true })
+		expect(setSoundEnabled).toHaveBeenCalledWith(true)
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("soundEnabled", true)
+		expect(mockPostMessage).toHaveBeenCalled()
+
+		// Simulate setting sound to disabled
+		await messageHandler({ type: "soundEnabled", bool: false })
+		expect(setSoundEnabled).toHaveBeenCalledWith(false)
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("soundEnabled", false)
+		expect(mockPostMessage).toHaveBeenCalled()
+	})
+
+	test("requestDelaySeconds defaults to 5 seconds", async () => {
+		// Mock globalState.get to return undefined for requestDelaySeconds
+		;(mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
+			if (key === "requestDelaySeconds") {
+				return undefined
+			}
+			return null
+		})
+
+		const state = await provider.getState()
+		expect(state.requestDelaySeconds).toBe(5)
+	})
+
+	test("alwaysApproveResubmit defaults to false", async () => {
+		// Mock globalState.get to return undefined for alwaysApproveResubmit
+		;(mockContext.globalState.get as jest.Mock).mockReturnValue(undefined)
+
+		const state = await provider.getState()
+		expect(state.alwaysApproveResubmit).toBe(false)
+	})
+
+	test("loads saved API config when switching modes", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Mock ConfigManager methods
+		provider.configManager = {
+			GetModeConfigId: jest.fn().mockResolvedValue("test-id"),
+			ListConfig: jest.fn().mockResolvedValue([{ name: "test-config", id: "test-id", apiProvider: "anthropic" }]),
+			LoadConfig: jest.fn().mockResolvedValue({ apiProvider: "anthropic" }),
+			SetModeConfig: jest.fn(),
+		} as any
+
+		// Switch to architect mode
+		await messageHandler({ type: "mode", text: "architect" })
+
+		// Should load the saved config for architect mode
+		expect(provider.configManager.GetModeConfigId).toHaveBeenCalledWith("architect")
+		expect(provider.configManager.LoadConfig).toHaveBeenCalledWith("test-config")
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("currentApiConfigName", "test-config")
+	})
+
+	test("saves current config when switching to mode without config", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Mock ConfigManager methods
+		provider.configManager = {
+			GetModeConfigId: jest.fn().mockResolvedValue(undefined),
+			ListConfig: jest
+				.fn()
+				.mockResolvedValue([{ name: "current-config", id: "current-id", apiProvider: "anthropic" }]),
+			SetModeConfig: jest.fn(),
+		} as any
+
+		// Mock current config name
+		;(mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
+			if (key === "currentApiConfigName") {
+				return "current-config"
+			}
+			return undefined
+		})
+
+		// Switch to architect mode
+		await messageHandler({ type: "mode", text: "architect" })
+
+		// Should save current config as default for architect mode
+		expect(provider.configManager.SetModeConfig).toHaveBeenCalledWith("architect", "current-id")
+	})
+
+	test("saves config as default for current mode when loading config", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		provider.configManager = {
+			LoadConfig: jest.fn().mockResolvedValue({ apiProvider: "anthropic", id: "new-id" }),
+			ListConfig: jest.fn().mockResolvedValue([{ name: "new-config", id: "new-id", apiProvider: "anthropic" }]),
+			SetModeConfig: jest.fn(),
+			GetModeConfigId: jest.fn().mockResolvedValue(undefined),
+		} as any
+
+		// First set the mode
+		await messageHandler({ type: "mode", text: "architect" })
+
+		// Then load the config
+		await messageHandler({ type: "loadApiConfiguration", text: "new-config" })
+
+		// Should save new config as default for architect mode
+		expect(provider.configManager.SetModeConfig).toHaveBeenCalledWith("architect", "new-id")
+	})
+
+	test("handles request delay settings messages", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Test alwaysApproveResubmit
+		await messageHandler({ type: "alwaysApproveResubmit", bool: true })
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("alwaysApproveResubmit", true)
+		expect(mockPostMessage).toHaveBeenCalled()
+
+		// Test requestDelaySeconds
+		await messageHandler({ type: "requestDelaySeconds", value: 10 })
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("requestDelaySeconds", 10)
+		expect(mockPostMessage).toHaveBeenCalled()
+	})
+
+	test("handles updatePrompt message correctly", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Mock existing prompts
+		const existingPrompts = {
+			code: "existing code prompt",
+			architect: "existing architect prompt",
+		}
+		;(mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
+			if (key === "customPrompts") {
+				return existingPrompts
+			}
+			return undefined
+		})
+
+		// Test updating a prompt
+		await messageHandler({
+			type: "updatePrompt",
+			promptMode: "code",
+			customPrompt: "new code prompt",
+		})
+
+		// Verify state was updated correctly
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("customPrompts", {
+			...existingPrompts,
+			code: "new code prompt",
+		})
+
+		// Verify state was posted to webview
+		expect(mockPostMessage).toHaveBeenCalledWith(
+			expect.objectContaining({
+				type: "state",
+				state: expect.objectContaining({
+					customPrompts: {
+						...existingPrompts,
+						code: "new code prompt",
+					},
+				}),
+			}),
+		)
+	})
+
+	test("customPrompts defaults to empty object", async () => {
+		// Mock globalState.get to return undefined for customPrompts
+		;(mockContext.globalState.get as jest.Mock).mockImplementation((key: string) => {
+			if (key === "customPrompts") {
+				return undefined
+			}
+			return null
+		})
+
+		const state = await provider.getState()
+		expect(state.customPrompts).toEqual({})
+	})
+
+	test("uses mode-specific custom instructions in Cline initialization", async () => {
+		// Setup mock state
+		const modeCustomInstructions = "Code mode instructions"
+		const mockApiConfig = {
+			apiProvider: "openrouter",
+			openRouterModelInfo: { supportsComputerUse: true },
+		}
+
+		jest.spyOn(provider, "getState").mockResolvedValue({
+			apiConfiguration: mockApiConfig,
+			customPrompts: {
+				code: { customInstructions: modeCustomInstructions },
+			},
+			mode: "code",
+			diffEnabled: true,
+			fuzzyMatchThreshold: 1.0,
+		} as any)
+
+		// Reset Cline mock
+		const { Cline } = require("../../Cline")
+		;(Cline as jest.Mock).mockClear()
+
+		// Initialize Cline with a task
+		await provider.initClineWithTask("Test task")
+
+		// Verify Cline was initialized with mode-specific instructions
+		expect(Cline).toHaveBeenCalledWith(
+			provider,
+			mockApiConfig,
+			modeCustomInstructions,
+			true,
+			1.0,
+			"Test task",
+			undefined,
+			undefined,
+			undefined,
+		)
+	})
+	test("handles mode-specific custom instructions updates", async () => {
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		// Mock existing prompts
+		const existingPrompts = {
+			code: {
+				roleDefinition: "Code role",
+				customInstructions: "Old instructions",
+			},
+		}
+		mockContext.globalState.get = jest.fn((key: string) => {
+			if (key === "customPrompts") {
+				return existingPrompts
+			}
+			return undefined
+		})
+
+		// Update custom instructions for code mode
+		await messageHandler({
+			type: "updatePrompt",
+			promptMode: "code",
+			customPrompt: {
+				roleDefinition: "Code role",
+				customInstructions: "New instructions",
+			},
+		})
+
+		// Verify state was updated correctly
+		expect(mockContext.globalState.update).toHaveBeenCalledWith("customPrompts", {
+			code: {
+				roleDefinition: "Code role",
+				customInstructions: "New instructions",
+			},
+		})
+	})
+
+	test("saves mode config when updating API configuration", async () => {
+		// Setup mock context with mode and config name
+		mockContext = {
+			...mockContext,
+			globalState: {
+				...mockContext.globalState,
+				get: jest.fn((key: string) => {
+					if (key === "mode") {
+						return "code"
+					} else if (key === "currentApiConfigName") {
+						return "test-config"
+					}
+					return undefined
+				}),
+				update: jest.fn(),
+				keys: jest.fn().mockReturnValue([]),
+			},
+		} as unknown as vscode.ExtensionContext
+
+		// Create new provider with updated mock context
+		provider = new ClineProvider(mockContext, mockOutputChannel)
+		provider.resolveWebviewView(mockWebviewView)
+		const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+		provider.configManager = {
+			ListConfig: jest.fn().mockResolvedValue([{ name: "test-config", id: "test-id", apiProvider: "anthropic" }]),
+			SetModeConfig: jest.fn(),
+		} as any
+
+		// Update API configuration
+		await messageHandler({
+			type: "apiConfiguration",
+			apiConfiguration: { apiProvider: "anthropic" },
+		})
+
+		// Should save config as default for current mode
+		expect(provider.configManager.SetModeConfig).toHaveBeenCalledWith("code", "test-id")
+	})
+
+	test("file content includes line numbers", async () => {
+		const { extractTextFromFile } = require("../../../integrations/misc/extract-text")
+		const result = await extractTextFromFile("test.js")
+		expect(result).toBe("1 | const x = 1;\n2 | const y = 2;\n3 | const z = 3;")
+	})
+
+	describe("deleteMessage", () => {
+		beforeEach(() => {
+			// Mock window.showInformationMessage
+			;(vscode.window.showInformationMessage as jest.Mock) = jest.fn()
+			provider.resolveWebviewView(mockWebviewView)
+		})
+
+		test('handles "Just this message" deletion correctly', async () => {
+			// Mock user selecting "Just this message"
+			;(vscode.window.showInformationMessage as jest.Mock).mockResolvedValue("Just this message")
+
+			// Setup mock messages
+			const mockMessages = [
+				{ ts: 1000, type: "say", say: "user_feedback" }, // User message 1
+				{ ts: 2000, type: "say", say: "tool" }, // Tool message
+				{ ts: 3000, type: "say", say: "text", value: 4000 }, // Message to delete
+				{ ts: 4000, type: "say", say: "browser_action" }, // Response to delete
+				{ ts: 5000, type: "say", say: "user_feedback" }, // Next user message
+				{ ts: 6000, type: "say", say: "user_feedback" }, // Final message
+			]
+
+			const mockApiHistory = [{ ts: 1000 }, { ts: 2000 }, { ts: 3000 }, { ts: 4000 }, { ts: 5000 }, { ts: 6000 }]
+
+			// Setup Cline instance with mock data
+			const mockCline = {
+				clineMessages: mockMessages,
+				apiConversationHistory: mockApiHistory,
+				overwriteClineMessages: jest.fn(),
+				overwriteApiConversationHistory: jest.fn(),
+				taskId: "test-task-id",
+				abortTask: jest.fn(),
+				handleWebviewAskResponse: jest.fn(),
+			}
+			// @ts-ignore - accessing private property for testing
+			provider.cline = mockCline
+
+			// Mock getTaskWithId
+			;(provider as any).getTaskWithId = jest.fn().mockResolvedValue({
+				historyItem: { id: "test-task-id" },
+			})
+
+			// Trigger message deletion
+			const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+			await messageHandler({ type: "deleteMessage", value: 4000 })
+
+			// Verify correct messages were kept
+			expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([
+				mockMessages[0],
+				mockMessages[1],
+				mockMessages[4],
+				mockMessages[5],
+			])
+
+			// Verify correct API messages were kept
+			expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([
+				mockApiHistory[0],
+				mockApiHistory[1],
+				mockApiHistory[4],
+				mockApiHistory[5],
+			])
+		})
+
+		test('handles "This and all subsequent messages" deletion correctly', async () => {
+			// Mock user selecting "This and all subsequent messages"
+			;(vscode.window.showInformationMessage as jest.Mock).mockResolvedValue("This and all subsequent messages")
+
+			// Setup mock messages
+			const mockMessages = [
+				{ ts: 1000, type: "say", say: "user_feedback" },
+				{ ts: 2000, type: "say", say: "text", value: 3000 }, // Message to delete
+				{ ts: 3000, type: "say", say: "user_feedback" },
+				{ ts: 4000, type: "say", say: "user_feedback" },
+			]
+
+			const mockApiHistory = [{ ts: 1000 }, { ts: 2000 }, { ts: 3000 }, { ts: 4000 }]
+
+			// Setup Cline instance with mock data
+			const mockCline = {
+				clineMessages: mockMessages,
+				apiConversationHistory: mockApiHistory,
+				overwriteClineMessages: jest.fn(),
+				overwriteApiConversationHistory: jest.fn(),
+				taskId: "test-task-id",
+				abortTask: jest.fn(),
+				handleWebviewAskResponse: jest.fn(),
+			}
+			// @ts-ignore - accessing private property for testing
+			provider.cline = mockCline
+
+			// Mock getTaskWithId
+			;(provider as any).getTaskWithId = jest.fn().mockResolvedValue({
+				historyItem: { id: "test-task-id" },
+			})
+
+			// Trigger message deletion
+			const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+			await messageHandler({ type: "deleteMessage", value: 3000 })
+
+			// Verify only messages before the deleted message were kept
+			expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0]])
+
+			// Verify only API messages before the deleted message were kept
+			expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([mockApiHistory[0]])
+		})
+
+		test("handles Cancel correctly", async () => {
+			// Mock user selecting "Cancel"
+			;(vscode.window.showInformationMessage as jest.Mock).mockResolvedValue("Cancel")
+
+			const mockCline = {
+				clineMessages: [{ ts: 1000 }, { ts: 2000 }],
+				apiConversationHistory: [{ ts: 1000 }, { ts: 2000 }],
+				overwriteClineMessages: jest.fn(),
+				overwriteApiConversationHistory: jest.fn(),
+				taskId: "test-task-id",
+			}
+			// @ts-ignore - accessing private property for testing
+			provider.cline = mockCline
+
+			// Trigger message deletion
+			const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+			await messageHandler({ type: "deleteMessage", value: 2000 })
+
+			// Verify no messages were deleted
+			expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled()
+			expect(mockCline.overwriteApiConversationHistory).not.toHaveBeenCalled()
+		})
+	})
+
+	describe("getSystemPrompt", () => {
+		beforeEach(() => {
+			mockPostMessage.mockClear()
+			provider.resolveWebviewView(mockWebviewView)
+		})
+
+		const getMessageHandler = () => {
+			const mockCalls = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls
+			expect(mockCalls.length).toBeGreaterThan(0)
+			return mockCalls[0][0]
+		}
+
+		test("handles mcpEnabled setting correctly", async () => {
+			// Mock getState to return mcpEnabled: true
+			jest.spyOn(provider, "getState").mockResolvedValue({
+				apiConfiguration: {
+					apiProvider: "openrouter" as const,
+					openRouterModelInfo: {
+						supportsComputerUse: true,
+						supportsPromptCache: false,
+						maxTokens: 4096,
+						contextWindow: 8192,
+						supportsImages: false,
+						inputPrice: 0.0,
+						outputPrice: 0.0,
+						description: undefined,
+					},
+				},
+				mcpEnabled: true,
+				mode: "code" as const,
+			} as any)
+
+			const handler1 = getMessageHandler()
+			expect(typeof handler1).toBe("function")
+			await handler1({ type: "getSystemPrompt", mode: "code" })
+
+			// Verify mcpHub is passed when mcpEnabled is true
+			expect(mockPostMessage).toHaveBeenCalledWith(
+				expect.objectContaining({
+					type: "systemPrompt",
+					text: expect.any(String),
+				}),
+			)
+
+			// Mock getState to return mcpEnabled: false
+			jest.spyOn(provider, "getState").mockResolvedValue({
+				apiConfiguration: {
+					apiProvider: "openrouter" as const,
+					openRouterModelInfo: {
+						supportsComputerUse: true,
+						supportsPromptCache: false,
+						maxTokens: 4096,
+						contextWindow: 8192,
+						supportsImages: false,
+						inputPrice: 0.0,
+						outputPrice: 0.0,
+						description: undefined,
+					},
+				},
+				mcpEnabled: false,
+				mode: "code" as const,
+			} as any)
+
+			const handler2 = getMessageHandler()
+			await handler2({ type: "getSystemPrompt", mode: "code" })
+
+			// Verify mcpHub is not passed when mcpEnabled is false
+			expect(mockPostMessage).toHaveBeenCalledWith(
+				expect.objectContaining({
+					type: "systemPrompt",
+					text: expect.any(String),
+				}),
+			)
+		})
+
+		test("handles errors gracefully", async () => {
+			// Mock SYSTEM_PROMPT to throw an error
+			const systemPrompt = require("../../prompts/system")
+			jest.spyOn(systemPrompt, "SYSTEM_PROMPT").mockRejectedValueOnce(new Error("Test error"))
+
+			const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+			await messageHandler({ type: "getSystemPrompt", mode: "code" })
+
+			expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to get system prompt")
+		})
+
+		test("uses mode-specific custom instructions in system prompt", async () => {
+			const systemPrompt = require("../../prompts/system")
+			const { addCustomInstructions } = systemPrompt
+
+			// Mock getState to return mode-specific custom instructions
+			jest.spyOn(provider, "getState").mockResolvedValue({
+				apiConfiguration: {
+					apiProvider: "openrouter",
+					openRouterModelInfo: { supportsComputerUse: true },
+				},
+				customPrompts: {
+					code: { customInstructions: "Code mode specific instructions" },
+				},
+				mode: "code",
+				mcpEnabled: false,
+				browserViewportSize: "900x600",
+			} as any)
+
+			const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+			await messageHandler({ type: "getSystemPrompt", mode: "code" })
+
+			// Verify addCustomInstructions was called with mode-specific instructions
+			expect(addCustomInstructions).toHaveBeenCalledWith(
+				{
+					customInstructions: undefined,
+					customPrompts: {
+						code: { customInstructions: "Code mode specific instructions" },
+					},
+					preferredLanguage: undefined,
+				},
+				expect.any(String),
+				"code",
+			)
+		})
+
+		test("uses correct mode-specific instructions when mode is specified", async () => {
+			const systemPrompt = require("../../prompts/system")
+			const { addCustomInstructions } = systemPrompt
+
+			// Mock getState to return instructions for multiple modes
+			jest.spyOn(provider, "getState").mockResolvedValue({
+				apiConfiguration: {
+					apiProvider: "openrouter",
+					openRouterModelInfo: { supportsComputerUse: true },
+				},
+				customPrompts: {
+					code: { customInstructions: "Code mode instructions" },
+					architect: { customInstructions: "Architect mode instructions" },
+				},
+				mode: "code",
+				mcpEnabled: false,
+				browserViewportSize: "900x600",
+			} as any)
+
+			const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]
+
+			// Request architect mode prompt
+			await messageHandler({ type: "getSystemPrompt", mode: "architect" })
+
+			// Verify architect mode instructions were used
+			expect(addCustomInstructions).toHaveBeenCalledWith(
+				{
+					customInstructions: undefined,
+					customPrompts: {
+						code: { customInstructions: "Code mode instructions" },
+						architect: { customInstructions: "Architect mode instructions" },
+					},
+					preferredLanguage: undefined,
+				},
+				expect.any(String),
+				"architect",
+			)
+		})
+	})
 })

+ 3 - 5
src/extension.ts

@@ -27,13 +27,11 @@ export function activate(context: vscode.ExtensionContext) {
 	outputChannel.appendLine("Cline extension activated")
 
 	// Get default commands from configuration
-	const defaultCommands = vscode.workspace
-		.getConfiguration('roo-cline')
-		.get<string[]>('allowedCommands') || [];
+	const defaultCommands = vscode.workspace.getConfiguration("roo-cline").get<string[]>("allowedCommands") || []
 
 	// Initialize global state if not already set
-	if (!context.globalState.get('allowedCommands')) {
-		context.globalState.update('allowedCommands', defaultCommands);
+	if (!context.globalState.get("allowedCommands")) {
+		context.globalState.update("allowedCommands", defaultCommands)
 	}
 
 	const sidebarProvider = new ClineProvider(context, outputChannel)

+ 5 - 5
src/integrations/editor/DiffViewProvider.ts

@@ -132,10 +132,10 @@ export class DiffViewProvider {
 			// Apply the final content
 			const finalEdit = new vscode.WorkspaceEdit()
 			finalEdit.replace(document.uri, new vscode.Range(0, 0, document.lineCount, 0), accumulatedContent)
-						await vscode.workspace.applyEdit(finalEdit)
-						// Clear all decorations at the end (after applying final edit)
-						this.fadedOverlayController.clear()
-						this.activeLineController.clear()
+			await vscode.workspace.applyEdit(finalEdit)
+			// Clear all decorations at the end (after applying final edit)
+			this.fadedOverlayController.clear()
+			this.activeLineController.clear()
 		}
 	}
 
@@ -352,4 +352,4 @@ export class DiffViewProvider {
 		this.streamedLines = []
 		this.preDiagnostics = []
 	}
-}
+}

+ 40 - 44
src/integrations/editor/__tests__/DiffViewProvider.test.ts

@@ -1,8 +1,8 @@
-import { DiffViewProvider } from '../DiffViewProvider';
-import * as vscode from 'vscode';
+import { DiffViewProvider } from "../DiffViewProvider"
+import * as vscode from "vscode"
 
 // Mock vscode
-jest.mock('vscode', () => ({
+jest.mock("vscode", () => ({
 	workspace: {
 		applyEdit: jest.fn(),
 	},
@@ -19,34 +19,34 @@ jest.mock('vscode', () => ({
 	TextEditorRevealType: {
 		InCenter: 2,
 	},
-}));
+}))
 
 // Mock DecorationController
-jest.mock('../DecorationController', () => ({
+jest.mock("../DecorationController", () => ({
 	DecorationController: jest.fn().mockImplementation(() => ({
 		setActiveLine: jest.fn(),
 		updateOverlayAfterLine: jest.fn(),
 		clear: jest.fn(),
 	})),
-}));
+}))
 
-describe('DiffViewProvider', () => {
-	let diffViewProvider: DiffViewProvider;
-	const mockCwd = '/mock/cwd';
-	let mockWorkspaceEdit: { replace: jest.Mock; delete: jest.Mock };
+describe("DiffViewProvider", () => {
+	let diffViewProvider: DiffViewProvider
+	const mockCwd = "/mock/cwd"
+	let mockWorkspaceEdit: { replace: jest.Mock; delete: jest.Mock }
 
 	beforeEach(() => {
-		jest.clearAllMocks();
+		jest.clearAllMocks()
 		mockWorkspaceEdit = {
 			replace: jest.fn(),
 			delete: jest.fn(),
-		};
-		(vscode.WorkspaceEdit as jest.Mock).mockImplementation(() => mockWorkspaceEdit);
+		}
+		;(vscode.WorkspaceEdit as jest.Mock).mockImplementation(() => mockWorkspaceEdit)
 
-		diffViewProvider = new DiffViewProvider(mockCwd);
+		diffViewProvider = new DiffViewProvider(mockCwd)
 		// Mock the necessary properties and methods
-		(diffViewProvider as any).relPath = 'test.txt';
-		(diffViewProvider as any).activeDiffEditor = {
+		;(diffViewProvider as any).relPath = "test.txt"
+		;(diffViewProvider as any).activeDiffEditor = {
 			document: {
 				uri: { fsPath: `${mockCwd}/test.txt` },
 				getText: jest.fn(),
@@ -58,43 +58,39 @@ describe('DiffViewProvider', () => {
 			},
 			edit: jest.fn().mockResolvedValue(true),
 			revealRange: jest.fn(),
-		};
-		(diffViewProvider as any).activeLineController = { setActiveLine: jest.fn(), clear: jest.fn() };
-		(diffViewProvider as any).fadedOverlayController = { updateOverlayAfterLine: jest.fn(), clear: jest.fn() };
-	});
+		}
+		;(diffViewProvider as any).activeLineController = { setActiveLine: jest.fn(), clear: jest.fn() }
+		;(diffViewProvider as any).fadedOverlayController = { updateOverlayAfterLine: jest.fn(), clear: jest.fn() }
+	})
 
-	describe('update method', () => {
-		it('should preserve empty last line when original content has one', async () => {
-			(diffViewProvider as any).originalContent = 'Original content\n';
-			await diffViewProvider.update('New content', true);
+	describe("update method", () => {
+		it("should preserve empty last line when original content has one", async () => {
+			;(diffViewProvider as any).originalContent = "Original content\n"
+			await diffViewProvider.update("New content", true)
 
 			expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith(
 				expect.anything(),
 				expect.anything(),
-				'New content\n'
-			);
-		});
+				"New content\n",
+			)
+		})
 
-		it('should not add extra newline when accumulated content already ends with one', async () => {
-			(diffViewProvider as any).originalContent = 'Original content\n';
-			await diffViewProvider.update('New content\n', true);
+		it("should not add extra newline when accumulated content already ends with one", async () => {
+			;(diffViewProvider as any).originalContent = "Original content\n"
+			await diffViewProvider.update("New content\n", true)
 
 			expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith(
 				expect.anything(),
 				expect.anything(),
-				'New content\n'
-			);
-		});
+				"New content\n",
+			)
+		})
 
-		it('should not add newline when original content does not end with one', async () => {
-			(diffViewProvider as any).originalContent = 'Original content';
-			await diffViewProvider.update('New content', true);
+		it("should not add newline when original content does not end with one", async () => {
+			;(diffViewProvider as any).originalContent = "Original content"
+			await diffViewProvider.update("New content", true)
 
-			expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith(
-				expect.anything(),
-				expect.anything(),
-				'New content'
-			);
-		});
-	});
-});
+			expect(mockWorkspaceEdit.replace).toHaveBeenCalledWith(expect.anything(), expect.anything(), "New content")
+		})
+	})
+})

+ 47 - 39
src/integrations/editor/__tests__/detect-omission.test.ts

@@ -1,6 +1,6 @@
-import { detectCodeOmission } from '../detect-omission'
+import { detectCodeOmission } from "../detect-omission"
 
-describe('detectCodeOmission', () => {
+describe("detectCodeOmission", () => {
 	const originalContent = `function example() {
   // Some code
   const x = 1;
@@ -10,124 +10,132 @@ describe('detectCodeOmission', () => {
 
 	const generateLongContent = (commentLine: string, length: number = 90) => {
 		return `${commentLine}
-	${Array.from({ length }, (_, i) => `const x${i} = ${i};`).join('\n')}
+	${Array.from({ length }, (_, i) => `const x${i} = ${i};`).join("\n")}
 	const y = 2;`
 	}
 
-	it('should skip comment checks for files under 100 lines', () => {
+	it("should skip comment checks for files under 100 lines", () => {
 		const newContent = `// Lines 1-50 remain unchanged
 const z = 3;`
 		const predictedLineCount = 50
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should not detect regular comments without omission keywords', () => {
-		const newContent = generateLongContent('// Adding new functionality')
+	it("should not detect regular comments without omission keywords", () => {
+		const newContent = generateLongContent("// Adding new functionality")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should not detect when comment is part of original content', () => {
+	it("should not detect when comment is part of original content", () => {
 		const originalWithComment = `// Content remains unchanged
 ${originalContent}`
-		const newContent = generateLongContent('// Content remains unchanged')
+		const newContent = generateLongContent("// Content remains unchanged")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalWithComment, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should not detect code that happens to contain omission keywords', () => {
+	it("should not detect code that happens to contain omission keywords", () => {
 		const newContent = generateLongContent(`const remains = 'some value';
 const unchanged = true;`)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should detect suspicious single-line comment when content is more than 20% shorter', () => {
-		const newContent = generateLongContent('// Previous content remains here\nconst x = 1;')
+	it("should detect suspicious single-line comment when content is more than 20% shorter", () => {
+		const newContent = generateLongContent("// Previous content remains here\nconst x = 1;")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(true)
 	})
 
-	it('should not flag suspicious single-line comment when content is less than 20% shorter', () => {
-		const newContent = generateLongContent('// Previous content remains here', 130)
+	it("should not flag suspicious single-line comment when content is less than 20% shorter", () => {
+		const newContent = generateLongContent("// Previous content remains here", 130)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should detect suspicious Python-style comment when content is more than 20% shorter', () => {
-		const newContent = generateLongContent('# Previous content remains here\nconst x = 1;')
+	it("should detect suspicious Python-style comment when content is more than 20% shorter", () => {
+		const newContent = generateLongContent("# Previous content remains here\nconst x = 1;")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(true)
 	})
 
-	it('should not flag suspicious Python-style comment when content is less than 20% shorter', () => {
-		const newContent = generateLongContent('# Previous content remains here', 130)
+	it("should not flag suspicious Python-style comment when content is less than 20% shorter", () => {
+		const newContent = generateLongContent("# Previous content remains here", 130)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should detect suspicious multi-line comment when content is more than 20% shorter', () => {
-		const newContent = generateLongContent('/* Previous content remains the same */\nconst x = 1;')
+	it("should detect suspicious multi-line comment when content is more than 20% shorter", () => {
+		const newContent = generateLongContent("/* Previous content remains the same */\nconst x = 1;")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(true)
 	})
 
-	it('should not flag suspicious multi-line comment when content is less than 20% shorter', () => {
-		const newContent = generateLongContent('/* Previous content remains the same */', 130)
+	it("should not flag suspicious multi-line comment when content is less than 20% shorter", () => {
+		const newContent = generateLongContent("/* Previous content remains the same */", 130)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should detect suspicious JSX comment when content is more than 20% shorter', () => {
-		const newContent = generateLongContent('{/* Rest of the code remains the same */}\nconst x = 1;')
+	it("should detect suspicious JSX comment when content is more than 20% shorter", () => {
+		const newContent = generateLongContent("{/* Rest of the code remains the same */}\nconst x = 1;")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(true)
 	})
 
-	it('should not flag suspicious JSX comment when content is less than 20% shorter', () => {
-		const newContent = generateLongContent('{/* Rest of the code remains the same */}', 130)
+	it("should not flag suspicious JSX comment when content is less than 20% shorter", () => {
+		const newContent = generateLongContent("{/* Rest of the code remains the same */}", 130)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should detect suspicious HTML comment when content is more than 20% shorter', () => {
-		const newContent = generateLongContent('<!-- Existing content unchanged -->\nconst x = 1;')
+	it("should detect suspicious HTML comment when content is more than 20% shorter", () => {
+		const newContent = generateLongContent("<!-- Existing content unchanged -->\nconst x = 1;")
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(true)
 	})
 
-	it('should not flag suspicious HTML comment when content is less than 20% shorter', () => {
-		const newContent = generateLongContent('<!-- Existing content unchanged -->', 130)
+	it("should not flag suspicious HTML comment when content is less than 20% shorter", () => {
+		const newContent = generateLongContent("<!-- Existing content unchanged -->", 130)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should detect suspicious square bracket notation when content is more than 20% shorter', () => {
-		const newContent = generateLongContent('[Previous content from line 1-305 remains exactly the same]\nconst x = 1;')
+	it("should detect suspicious square bracket notation when content is more than 20% shorter", () => {
+		const newContent = generateLongContent(
+			"[Previous content from line 1-305 remains exactly the same]\nconst x = 1;",
+		)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(true)
 	})
 
-	it('should not flag suspicious square bracket notation when content is less than 20% shorter', () => {
-		const newContent = generateLongContent('[Previous content from line 1-305 remains exactly the same]', 130)
+	it("should not flag suspicious square bracket notation when content is less than 20% shorter", () => {
+		const newContent = generateLongContent("[Previous content from line 1-305 remains exactly the same]", 130)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should not flag content very close to predicted length', () => {
-		const newContent = generateLongContent(`const x = 1;
+	it("should not flag content very close to predicted length", () => {
+		const newContent = generateLongContent(
+			`const x = 1;
 const y = 2;
-// This is a legitimate comment that remains here`, 130)
+// This is a legitimate comment that remains here`,
+			130,
+		)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})
 
-	it('should not flag when content is longer than predicted', () => {
-		const newContent = generateLongContent(`const x = 1;
+	it("should not flag when content is longer than predicted", () => {
+		const newContent = generateLongContent(
+			`const x = 1;
 const y = 2;
 // Previous content remains here but we added more
 const z = 3;
-const w = 4;`, 160)
+const w = 4;`,
+			160,
+		)
 		const predictedLineCount = 150
 		expect(detectCodeOmission(originalContent, newContent, predictedLineCount)).toBe(false)
 	})

Неке датотеке нису приказане због велике количине промена