Merge branch 'main' of https://github.com/RooVetGit/Roo-Cline into feature/pupeteer-updates

This commit is contained in:
a8trejo 2024-12-09 09:27:28 -08:00
commit 000eed630a
30 changed files with 1473 additions and 1573 deletions

View file

@ -28,6 +28,5 @@ jobs:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
run: |
current_package_version=$(node -p "require('./package.json').version")
npm run vsix
npm run publish:marketplace
echo "Successfully published version $current_package_version to VS Code Marketplace"

5
.gitignore vendored
View file

@ -7,5 +7,8 @@ node_modules
# Builds
bin
roo-cline-*.vsix
# Prompts
prompts
prompts

View file

@ -1,5 +1,27 @@
# Roo Cline Changelog
## [2.1.15]
- Incorporate dbasclpy's [PR](https://github.com/RooVetGit/Roo-Cline/pull/54) to add support for gemini-exp-1206
- Make it clear that diff editing is very experimental
## [2.1.14]
- Fix bug where diffs were not being applied correctly and try Aider's [unified diff prompt](https://github.com/Aider-AI/aider/blob/3995accd0ca71cea90ef76d516837f8c2731b9fe/aider/coders/udiff_prompts.py#L75-L105)
- If diffs are enabled, automatically reject write_to_file commands that lead to truncated output
## [2.1.13]
- Fix https://github.com/RooVetGit/Roo-Cline/issues/50 where sound effects were not respecting settings
## [2.1.12]
- Incorporate JoziGila's [PR](https://github.com/cline/cline/pull/158) to add support for editing through diffs
## [2.1.11]
- Incorporate lloydchang's [PR](https://github.com/RooVetGit/Roo-Cline/pull/42) to add support for OpenRouter compression
## [2.1.10]
- Incorporate HeavenOSK's [PR](https://github.com/cline/cline/pull/818) to add sound effects to Cline
@ -35,4 +57,4 @@
## [2.1.2]
- Support for auto-approval of write operations and command execution
- Support for .clinerules custom instructions
- Support for .clinerules custom instructions

View file

@ -1,9 +1,21 @@
# Roo-Cline
A fork of Cline, an autonomous coding agent, with some added experimental configuration and automation features.
- Auto-approval capabilities for commands, write, and browser operations
- Support for .clinerules per-project custom instructions
- Ability to run side-by-side with Cline
- Code is unit-tested
- Support for playing sound effects
- Support for OpenRouter compression
- Support for editing through diffs (very experimental)
- Support for gemini-exp-1206
Here's an example of Roo-Cline autonomously creating a snake game with "Always approve write operations" and "Always approve browser actions" turned on:
https://github.com/user-attachments/assets/c2bb31dc-e9b2-4d73-885d-17f1471a4987
### Installation
If you want to install the latest extension from the Marketplace, just search for "Roo Cline" in your VSCode-compatible editor's Extensions panel (Cmd/Ctrl+Shift+X).
After installation, Roo Cline will appear in your VSCode-compatible editor's installed extensions list. You can verify this by opening your editor's Extensions panel (Cmd/Ctrl+Shift+X) and checking under the "Installed" section.
### Testing Builds
1. Install dependencies:
@ -86,10 +98,10 @@ Each browser action provides feedback through screenshots and console logs, allo
<a href="https://discord.gg/cline" target="_blank"><strong>Join the Discord</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/wiki" target="_blank"><strong>Docs</strong></a>
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
<a href="https://cline.bot/join-us" target="_blank"><strong>We're Hiring!</strong></a>
</td>
</tbody>
</table>
@ -171,7 +183,7 @@ Try asking Cline to "test the app", and watch as he runs a command like `npm run
## Contributing
To contribute to the project, start by exploring [open issues](https://github.com/cline/cline/issues) or checking our [feature request board](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop). We'd also love to have you join our [Discord](https://discord.gg/cline) to share ideas and connect with other contributors.
To contribute to the project, start by exploring [open issues](https://github.com/cline/cline/issues) or checking our [feature request board](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop). We'd also love to have you join our [Discord](https://discord.gg/cline) to share ideas and connect with other contributors. If you're interested in joining the team, check out our [careers page](https://cline.bot/join-us)!
<details>
<summary>Local Development Instructions</summary>

Binary file not shown.

1886
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -3,10 +3,7 @@
"displayName": "Roo Cline",
"description": "A fork of Cline, an autonomous coding agent, with some added experimental configuration and automation features.",
"publisher": "RooVeterinaryInc",
"version": "2.1.10",
"files": [
"assets/icons/icon_Roo.png"
],
"version": "2.1.15",
"icon": "assets/icons/rocket.png",
"galleryBanner": {
"color": "#617A91",

View file

@ -0,0 +1,121 @@
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('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
}))
})
})

View file

@ -4,9 +4,19 @@ import OpenAI from "openai"
import { ApiHandler } from "../"
import { ApiHandlerOptions, ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import { ApiStreamChunk, ApiStreamUsageChunk } from "../transform/stream"
import delay from "delay"
// Add custom interface for OpenRouter params
interface OpenRouterChatCompletionParams extends OpenAI.Chat.ChatCompletionCreateParamsStreaming {
transforms?: string[];
}
// Add custom interface for OpenRouter usage chunk
interface OpenRouterApiStreamUsageChunk extends ApiStreamUsageChunk {
fullResponseText: string;
}
export class OpenRouterHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI
@ -17,13 +27,13 @@ export class OpenRouterHandler implements ApiHandler {
baseURL: "https://openrouter.ai/api/v1",
apiKey: this.options.openRouterApiKey,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot", // Optional, for including your app on openrouter.ai rankings.
"X-Title": "Cline", // Optional. Shows in rankings on openrouter.ai.
"HTTP-Referer": "https://github.com/RooVetGit/Roo-Cline", // Optional, for including your app on openrouter.ai rankings.
"X-Title": "Roo-Cline", // Optional. Shows in rankings on openrouter.ai.
},
})
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
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 },
@ -95,17 +105,21 @@ export class OpenRouterHandler implements ApiHandler {
maxTokens = 8_192
break
}
// https://openrouter.ai/docs/transforms
let fullResponseText = "";
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
max_tokens: maxTokens,
temperature: 0,
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);
let genId: string | undefined
for await (const chunk of stream) {
for await (const chunk of stream as unknown as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {
// openrouter returns an error object instead of the openai sdk throwing an error
if ("error" in chunk) {
const error = chunk.error as { message?: string; code?: number }
@ -119,10 +133,11 @@ export class OpenRouterHandler implements ApiHandler {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
fullResponseText += delta.content;
yield {
type: "text",
text: delta.content,
}
} as ApiStreamChunk;
}
// if (chunk.usage) {
// yield {
@ -153,13 +168,14 @@ export class OpenRouterHandler implements ApiHandler {
inputTokens: generation?.native_tokens_prompt || 0,
outputTokens: generation?.native_tokens_completion || 0,
totalCost: generation?.total_cost || 0,
}
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
const modelInfo = this.options.openRouterModelInfo

View file

@ -1,5 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import cloneDeep from "clone-deep"
import { DiffStrategy, getDiffStrategy, UnifiedDiffStrategy } from "./diff/DiffStrategy"
import delay from "delay"
import fs from "fs/promises"
import os from "os"
@ -11,7 +12,7 @@ import { ApiHandler, 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 } from "../integrations/misc/extract-text"
import { extractTextFromFile, addLineNumbers } from "../integrations/misc/extract-text"
import { TerminalManager } from "../integrations/terminal/TerminalManager"
import { UrlContentFetcher } from "../services/browser/UrlContentFetcher"
import { listFiles } from "../services/glob/list-files"
@ -45,7 +46,7 @@ import { formatResponse } from "./prompts/responses"
import { addCustomInstructions, SYSTEM_PROMPT } from "./prompts/system"
import { truncateHalfConversation } from "./sliding-window"
import { ClineProvider, GlobalFileNames } from "./webview/ClineProvider"
import { showOmissionWarning } from "../integrations/editor/detect-omission"
import { detectCodeOmission } from "../integrations/editor/detect-omission"
import { BrowserSession } from "../services/browser/BrowserSession"
const cwd =
@ -66,6 +67,7 @@ export class Cline {
private isInteractiveMode: boolean = false
private browserPort: string = '7333'
customInstructions?: string
diffStrategy?: DiffStrategy
apiConversationHistory: Anthropic.MessageParam[] = []
clineMessages: ClineMessage[] = []
@ -95,6 +97,7 @@ export class Cline {
provider: ClineProvider,
apiConfiguration: ApiConfiguration,
customInstructions?: string,
diffEnabled?: boolean,
task?: string,
images?: string[],
historyItem?: HistoryItem,
@ -106,7 +109,9 @@ export class Cline {
this.browserSession = new BrowserSession(provider.context)
this.diffViewProvider = new DiffViewProvider(cwd)
this.customInstructions = customInstructions
if (diffEnabled && this.api.getModel().id) {
this.diffStrategy = getDiffStrategy(this.api.getModel().id)
}
if (historyItem) {
this.taskId = historyItem.id
this.resumeTaskFromHistory()
@ -790,7 +795,7 @@ export class Cline {
}
async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false) + await addCustomInstructions(this.customInstructions ?? '', cwd)
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false, this.diffStrategy) + await addCustomInstructions(this.customInstructions ?? '', cwd)
// 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) {
@ -917,6 +922,8 @@ export class Cline {
return `[${block.name} for '${block.params.path}']`
case "write_to_file":
return `[${block.name} for '${block.params.path}']`
case "apply_diff":
return `[${block.name} for '${block.params.path}']`
case "search_files":
return `[${block.name} for '${block.params.regex}'${
block.params.file_pattern ? ` in '${block.params.file_pattern}'` : ""
@ -1137,7 +1144,32 @@ export class Cline {
await this.diffViewProvider.update(newContent, true)
await delay(300) // wait for diff view to update
this.diffViewProvider.scrollToFirstDiff()
showOmissionWarning(this.diffViewProvider.originalContent || "", newContent)
// Check for code omissions before proceeding
if (detectCodeOmission(this.diffViewProvider.originalContent || "", newContent)) {
if (this.diffStrategy) {
await this.diffViewProvider.revertChanges()
pushToolResult(formatResponse.toolError(
"Content appears to be truncated. 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
.showWarningMessage(
"Potential code truncation detected. This happens when the AI reaches its max output limit.",
"Follow this guide to fix the issue",
)
.then((selection) => {
if (selection === "Follow this guide to fix the issue") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://github.com/cline/cline/wiki/Troubleshooting-%E2%80%90-Cline-Deleting-Code-with-%22Rest-of-Code-Here%22-Comments",
),
)
}
})
}
}
const completeMessage = JSON.stringify({
...sharedMessageProps,
@ -1169,8 +1201,8 @@ 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:\n\n` +
`<final_file_content path="${relPath.toPosix()}">\n${finalContent}\n</final_file_content>\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` +
`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` +
@ -1191,6 +1223,104 @@ export class Cline {
break
}
}
case "apply_diff": {
const relPath: string | undefined = block.params.path
const diffContent: string | undefined = block.params.diff
const sharedMessageProps: ClineSayTool = {
tool: "appliedDiff",
path: getReadablePath(cwd, removeClosingTag("path", relPath)),
}
try {
if (block.partial) {
// update gui message
const partialMessage = JSON.stringify(sharedMessageProps)
await this.ask("tool", partialMessage, block.partial).catch(() => {})
break
} else {
if (!relPath) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("apply_diff", "path"))
break
}
if (!diffContent) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("apply_diff", "diff"))
break
}
this.consecutiveMistakeCount = 0
const absolutePath = path.resolve(cwd, relPath)
const fileExists = await fileExistsAtPath(absolutePath)
if (!fileExists) {
await this.say("error", `File does not exist at path: ${absolutePath}`)
pushToolResult(`Error: File does not exist at path: ${absolutePath}`)
break
}
const originalContent = await fs.readFile(absolutePath, "utf-8")
// Apply the diff to the original content
let newContent = this.diffStrategy?.applyDiff(originalContent, diffContent) ?? false
if (newContent === false) {
await this.say("error", `Error applying diff to file: ${absolutePath}`)
pushToolResult(`Error applying diff to file: ${absolutePath}`)
break
}
// Show diff view before asking for approval
this.diffViewProvider.editType = "modify"
await this.diffViewProvider.open(relPath);
await this.diffViewProvider.update(newContent, true);
await this.diffViewProvider.scrollToFirstDiff();
const completeMessage = JSON.stringify({
...sharedMessageProps,
diff: diffContent,
} satisfies ClineSayTool)
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
await this.diffViewProvider.revertChanges() // This likely handles closing the diff view
break
}
const { newProblemsMessage, userEdits, finalContent } =
await this.diffViewProvider.saveChanges()
this.didEditFile = true // used to determine if we should wait for busy terminal to update before sending api request
if (userEdits) {
await this.say(
"user_feedback_diff",
JSON.stringify({
tool: fileExists ? "editedExistingFile" : "newFileCreated",
path: getReadablePath(cwd, relPath),
diff: userEdits,
} satisfies ClineSayTool),
)
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` +
`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` +
`3. If the user's edits have addressed part of the task or changed the requirements, adjust your approach accordingly.` +
`${newProblemsMessage}`,
)
} else {
pushToolResult(`Changes successfully applied to ${relPath.toPosix()}:\n\n${newProblemsMessage}`)
}
await this.diffViewProvider.reset()
break
}
} catch (error) {
await handleError("applying diff", error)
await this.diffViewProvider.reset()
break
}
}
case "read_file": {
const relPath: string | undefined = block.params.path
const sharedMessageProps: ClineSayTool = {
@ -2186,4 +2316,4 @@ export class Cline {
return `<environment_details>\n${details.trim()}\n</environment_details>`
}
}
}

View file

@ -236,6 +236,7 @@ describe('Cline', () => {
mockProvider,
mockApiConfig,
'custom instructions',
false,
'test task'
);

View file

@ -12,6 +12,7 @@ export const toolUseNames = [
"execute_command",
"read_file",
"write_to_file",
"apply_diff",
"search_files",
"list_files",
"list_code_definition_names",
@ -36,6 +37,7 @@ export const toolParamNames = [
"text",
"question",
"result",
"diff",
] as const
export type ToolParamName = (typeof toolParamNames)[number]

View file

@ -0,0 +1,16 @@
import type { DiffStrategy } from './types'
import { UnifiedDiffStrategy } from './strategies/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): DiffStrategy {
// For now, return UnifiedDiffStrategy for all models
// This architecture allows for future optimizations based on model capabilities
return new UnifiedDiffStrategy()
}
export type { DiffStrategy }
export { UnifiedDiffStrategy }

View file

@ -0,0 +1,214 @@
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', () => {
const originalContent = `import { Logger } from '../logger';
function calculateTotal(items: number[]): number {
return items.reduce((sum, item) => {
return sum + item;
}, 0);
}
export { calculateTotal };`
const diffContent = `--- src/utils/helper.ts
+++ src/utils/helper.ts
@@ -1,9 +1,10 @@
import { Logger } from '../logger';
function calculateTotal(items: number[]): number {
- return items.reduce((sum, item) => {
- return sum + item;
+ const total = items.reduce((sum, item) => {
+ return sum + item * 1.1; // Add 10% markup
}, 0);
+ return Math.round(total * 100) / 100; // Round to 2 decimal places
}
export { calculateTotal };`
const expected = `import { Logger } from '../logger';
function calculateTotal(items: number[]): number {
const total = items.reduce((sum, item) => {
return sum + item * 1.1; // Add 10% markup
}, 0);
return Math.round(total * 100) / 100; // Round to 2 decimal places
}
export { calculateTotal };`
const result = strategy.applyDiff(originalContent, diffContent)
expect(result).toBe(expected)
})
it('should successfully apply a diff adding a new method', () => {
const originalContent = `class Calculator {
add(a: number, b: number): number {
return a + b;
}
}`
const diffContent = `--- src/Calculator.ts
+++ src/Calculator.ts
@@ -1,5 +1,9 @@
class Calculator {
add(a: number, b: number): number {
return a + b;
}
+
+ multiply(a: number, b: number): number {
+ return a * b;
+ }
}`
const expected = `class Calculator {
add(a: number, b: number): number {
return a + b;
}
multiply(a: number, b: number): number {
return a * b;
}
}`
const result = strategy.applyDiff(originalContent, diffContent)
expect(result).toBe(expected)
})
it('should successfully apply a diff modifying imports', () => {
const originalContent = `import { useState } from 'react';
import { Button } from './components';
function App() {
const [count, setCount] = useState(0);
return <Button onClick={() => setCount(count + 1)}>{count}</Button>;
}`
const diffContent = `--- src/App.tsx
+++ src/App.tsx
@@ -1,7 +1,8 @@
-import { useState } from 'react';
+import { useState, useEffect } from 'react';
import { Button } from './components';
function App() {
const [count, setCount] = useState(0);
+ useEffect(() => { document.title = \`Count: \${count}\` }, [count]);
return <Button onClick={() => setCount(count + 1)}>{count}</Button>;
}`
const expected = `import { useState, useEffect } from 'react';
import { Button } from './components';
function App() {
const [count, setCount] = useState(0);
useEffect(() => { document.title = \`Count: \${count}\` }, [count]);
return <Button onClick={() => setCount(count + 1)}>{count}</Button>;
}`
const result = strategy.applyDiff(originalContent, diffContent)
expect(result).toBe(expected)
})
it('should successfully apply a diff with multiple hunks', () => {
const originalContent = `import { readFile, writeFile } from 'fs';
function processFile(path: string) {
readFile(path, 'utf8', (err, data) => {
if (err) throw err;
const processed = data.toUpperCase();
writeFile(path, processed, (err) => {
if (err) throw err;
});
});
}
export { processFile };`
const diffContent = `--- src/file-processor.ts
+++ src/file-processor.ts
@@ -1,12 +1,14 @@
-import { readFile, writeFile } from 'fs';
+import { promises as fs } from 'fs';
+import { join } from 'path';
-function processFile(path: string) {
- readFile(path, 'utf8', (err, data) => {
- if (err) throw err;
+async function processFile(path: string) {
+ try {
+ const data = await fs.readFile(join(__dirname, path), 'utf8');
const processed = data.toUpperCase();
- writeFile(path, processed, (err) => {
- if (err) throw err;
- });
- });
+ await fs.writeFile(join(__dirname, path), processed);
+ } catch (error) {
+ console.error('Failed to process file:', error);
+ throw error;
+ }
}
export { processFile };`
const expected = `import { promises as fs } from 'fs';
import { join } from 'path';
async function processFile(path: string) {
try {
const data = await fs.readFile(join(__dirname, path), 'utf8');
const processed = data.toUpperCase();
await fs.writeFile(join(__dirname, path), processed);
} catch (error) {
console.error('Failed to process file:', error);
throw error;
}
}
export { processFile };`
const result = strategy.applyDiff(originalContent, diffContent)
expect(result).toBe(expected)
})
it('should handle empty original content', () => {
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 {
return \`Hello, \${name}!\`;
}\n`
const result = strategy.applyDiff(originalContent, diffContent)
expect(result).toBe(expected)
})
})
})

View file

@ -0,0 +1,114 @@
import { applyPatch } from "diff"
import { DiffStrategy } from "../types"
export class UnifiedDiffStrategy implements DiffStrategy {
getToolDescription(cwd: 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:
- path: (required) The path of the file to apply the diff to (relative to the current working directory ${cwd})
- diff: (required) The diff content in unified format to apply to the file.
Format Requirements:
1. Header (REQUIRED):
\`\`\`
--- path/to/original/file
+++ path/to/modified/file
\`\`\`
- Must include both lines exactly as shown
- Use actual file paths
- NO timestamps after paths
2. Hunks:
\`\`\`
@@ -lineStart,lineCount +lineStart,lineCount @@
-removed line
+added line
\`\`\`
- Each hunk starts with @@ showing line numbers for changes
- Format: @@ -originalStart,originalCount +newStart,newCount @@
- Use - for removed/changed lines
- Use + for new/modified lines
- Indentation must match exactly
Complete Example:
Original file (with line numbers):
\`\`\`
1 | import { Logger } from '../logger';
2 |
3 | function calculateTotal(items: number[]): number {
4 | return items.reduce((sum, item) => {
5 | return sum + item;
6 | }, 0);
7 | }
8 |
9 | export { calculateTotal };
\`\`\`
After applying the diff, the file would look like:
\`\`\`
1 | import { Logger } from '../logger';
2 |
3 | function calculateTotal(items: number[]): number {
4 | const total = items.reduce((sum, item) => {
5 | return sum + item * 1.1; // Add 10% markup
6 | }, 0);
7 | return Math.round(total * 100) / 100; // Round to 2 decimal places
8 | }
9 |
10 | export { calculateTotal };
\`\`\`
Diff to modify the file:
\`\`\`
--- src/utils/helper.ts
+++ src/utils/helper.ts
@@ -1,9 +1,10 @@
import { Logger } from '../logger';
function calculateTotal(items: number[]): number {
- return items.reduce((sum, item) => {
- return sum + item;
+ const total = items.reduce((sum, item) => {
+ return sum + item * 1.1; // Add 10% markup
}, 0);
+ return Math.round(total * 100) / 100; // Round to 2 decimal places
}
export { calculateTotal };
\`\`\`
Common Pitfalls:
1. Missing or incorrect header lines
2. Incorrect line numbers in @@ lines
3. Wrong indentation in changed lines
4. Incomplete context (missing lines that need changing)
5. Not marking all modified lines with - and +
Best Practices:
1. Replace entire code blocks:
- Remove complete old version with - lines
- Add complete new version with + lines
- Include correct line numbers
2. Moving code requires two hunks:
- First hunk: Remove from old location
- Second hunk: Add to new location
3. One hunk per logical change
4. Verify line numbers match the line numbers you have in the file
Usage:
<apply_diff>
<path>File path here</path>
<diff>
Your diff here
</diff>
</apply_diff>`
}
applyDiff(originalContent: string, diffContent: string): string | false {
return applyPatch(originalContent, diffContent) as string | false
}
}

19
src/core/diff/types.ts Normal file
View file

@ -0,0 +1,19 @@
/**
* Interface for implementing different diff strategies
*/
export interface DiffStrategy {
/**
* Get the tool description for this diff strategy
* @param cwd The current working directory
* @returns The complete tool description including format requirements and examples
*/
getToolDescription(cwd: 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
* @returns The new content after applying the diff, or false if the diff could not be applied
*/
applyDiff(originalContent: string, diffContent: string): string | false
}

View file

@ -1,4 +1,5 @@
import osName from "os-name"
import { DiffStrategy } from "../diff/DiffStrategy"
import defaultShell from "default-shell"
import os from "os"
import fs from 'fs/promises'
@ -7,6 +8,7 @@ import path from 'path'
export const SYSTEM_PROMPT = async (
cwd: string,
supportsComputerUse: boolean,
diffStrategy?: DiffStrategy
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
@ -45,7 +47,7 @@ Usage:
</execute_command>
## 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. 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.
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 ${cwd.toPosix()})
Usage:
@ -54,7 +56,7 @@ Usage:
</read_file>
## write_to_file
Description: Request to write 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.
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 ${cwd.toPosix()})
- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
@ -66,6 +68,8 @@ Your file content here
</content>
</write_to_file>
${diffStrategy ? diffStrategy.getToolDescription(cwd.toPosix()) : ""}
## 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:
@ -221,7 +225,7 @@ CAPABILITIES
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd.toPosix()}') 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 tool to implement 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.
- 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."
@ -238,6 +242,7 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
${diffStrategy ? "- Prefer to use apply_diff over write_to_file when making changes to existing files, particularly when editing files more than 200 lines of code, as it allows you to apply specific modifications based on a set of changes provided in a diff. This is particularly useful when you need to make targeted edits or updates to a file without overwriting the entire content." : ""}
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool.

View file

@ -61,8 +61,10 @@ type GlobalStateKey =
| "azureApiVersion"
| "openRouterModelId"
| "openRouterModelInfo"
| "openRouterUseMiddleOutTransform"
| "allowedCommands"
| "soundEnabled"
| "diffEnabled"
export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
@ -200,12 +202,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const {
apiConfiguration,
customInstructions,
diffEnabled,
} = await this.getState()
this.cline = new Cline(
this,
apiConfiguration,
customInstructions,
diffEnabled,
task,
images
)
@ -216,12 +220,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const {
apiConfiguration,
customInstructions,
diffEnabled,
} = await this.getState()
this.cline = new Cline(
this,
apiConfiguration,
customInstructions,
diffEnabled,
undefined,
undefined,
historyItem,
@ -391,6 +397,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
azureApiVersion,
openRouterModelId,
openRouterModelInfo,
openRouterUseMiddleOutTransform,
} = message.apiConfiguration
await this.updateGlobalState("apiProvider", apiProvider)
await this.updateGlobalState("apiModelId", apiModelId)
@ -416,6 +423,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.updateGlobalState("azureApiVersion", azureApiVersion)
await this.updateGlobalState("openRouterModelId", openRouterModelId)
await this.updateGlobalState("openRouterModelInfo", openRouterModelInfo)
await this.updateGlobalState("openRouterUseMiddleOutTransform", openRouterUseMiddleOutTransform)
if (this.cline) {
this.cline.api = buildApiHandler(message.apiConfiguration)
}
@ -529,9 +537,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
break
case "soundEnabled":
const enabled = message.bool ?? true
await this.updateGlobalState("soundEnabled", enabled)
setSoundEnabled(enabled)
const soundEnabled = message.bool ?? true
await this.updateGlobalState("soundEnabled", soundEnabled)
setSoundEnabled(soundEnabled) // Add this line to update the sound utility
await this.postStateToWebview()
break
case "diffEnabled":
const diffEnabled = message.bool ?? true
await this.updateGlobalState("diffEnabled", diffEnabled)
await this.postStateToWebview()
break
}
@ -840,6 +853,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
alwaysAllowExecute,
alwaysAllowBrowser,
soundEnabled,
diffEnabled,
taskHistory,
} = await this.getState()
@ -860,7 +874,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory: (taskHistory || [])
.filter((item) => item.ts && item.task)
.sort((a, b) => b.ts - a.ts),
soundEnabled: soundEnabled ?? true,
soundEnabled: soundEnabled ?? false,
diffEnabled: diffEnabled ?? false,
shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
allowedCommands,
}
@ -943,6 +958,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
azureApiVersion,
openRouterModelId,
openRouterModelInfo,
openRouterUseMiddleOutTransform,
lastShownAnnouncementId,
customInstructions,
alwaysAllowReadOnly,
@ -952,6 +968,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory,
allowedCommands,
soundEnabled,
diffEnabled,
] = await Promise.all([
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("apiModelId") as Promise<string | undefined>,
@ -977,6 +994,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("azureApiVersion") as Promise<string | undefined>,
this.getGlobalState("openRouterModelId") as Promise<string | undefined>,
this.getGlobalState("openRouterModelInfo") as Promise<ModelInfo | undefined>,
this.getGlobalState("openRouterUseMiddleOutTransform") as Promise<boolean | undefined>,
this.getGlobalState("lastShownAnnouncementId") as Promise<string | undefined>,
this.getGlobalState("customInstructions") as Promise<string | undefined>,
this.getGlobalState("alwaysAllowReadOnly") as Promise<boolean | undefined>,
@ -986,6 +1004,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>,
this.getGlobalState("allowedCommands") as Promise<string[] | undefined>,
this.getGlobalState("soundEnabled") as Promise<boolean | undefined>,
this.getGlobalState("diffEnabled") as Promise<boolean | undefined>,
])
let apiProvider: ApiProvider
@ -1028,6 +1047,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
azureApiVersion,
openRouterModelId,
openRouterModelInfo,
openRouterUseMiddleOutTransform,
},
lastShownAnnouncementId,
customInstructions,
@ -1038,6 +1058,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
taskHistory,
allowedCommands,
soundEnabled,
diffEnabled,
}
}

View file

@ -0,0 +1,276 @@
import { ClineProvider } from '../ClineProvider'
import * as vscode from 'vscode'
import { ExtensionMessage, ExtensionState } from '../../../shared/ExtensionMessage'
import { setSoundEnabled } from '../../../utils/sound'
// Mock dependencies
jest.mock('vscode', () => ({
ExtensionContext: jest.fn(),
OutputChannel: jest.fn(),
WebviewView: jest.fn(),
Uri: {
joinPath: jest.fn(),
file: jest.fn()
},
workspace: {
getConfiguration: jest.fn().mockReturnValue({
get: jest.fn().mockReturnValue([]),
update: jest.fn()
}),
onDidChangeConfiguration: jest.fn().mockImplementation((callback) => ({
dispose: jest.fn()
}))
},
env: {
uriScheme: 'vscode'
}
}))
// Mock sound utility
jest.mock('../../../utils/sound', () => ({
setSoundEnabled: jest.fn()
}))
// Mock ESM modules
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()
}))
// Mock axios
jest.mock('axios', () => ({
get: jest.fn().mockResolvedValue({ data: { data: [] } }),
post: jest.fn()
}))
// Mock buildApiHandler
jest.mock('../../../api', () => ({
buildApiHandler: jest.fn()
}))
// Mock WorkspaceTracker
jest.mock('../../../integrations/workspace/WorkspaceTracker', () => {
return jest.fn().mockImplementation(() => ({
initializeFilePaths: jest.fn(),
dispose: jest.fn()
}))
})
// Mock Cline
jest.mock('../../Cline', () => {
return {
Cline: jest.fn().mockImplementation(() => ({
abortTask: jest.fn(),
handleWebviewAskResponse: jest.fn(),
clineMessages: []
}))
}
})
// 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')
})
}))
// Spy on console.error and console.log to suppress expected messages
beforeAll(() => {
jest.spyOn(console, 'error').mockImplementation(() => {})
jest.spyOn(console, 'log').mockImplementation(() => {})
})
afterAll(() => {
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(),
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',
clineMessages: [],
taskHistory: [],
shouldShowAnnouncement: false,
apiConfiguration: {
apiProvider: 'openrouter'
},
customInstructions: undefined,
alwaysAllowReadOnly: false,
alwaysAllowWrite: false,
alwaysAllowExecute: false,
alwaysAllowBrowser: false,
uriScheme: 'vscode',
soundEnabled: false,
diffEnabled: false
}
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')
})
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('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;')
})
})

View file

@ -1,12 +1,10 @@
import * as vscode from "vscode"
/**
* Detects potential AI-generated code omissions in the given file content.
* @param originalFileContent The original content of the file.
* @param newFileContent The new content of the file to check.
* @returns True if a potential omission is detected, false otherwise.
*/
function detectCodeOmission(originalFileContent: string, newFileContent: string): boolean {
export function detectCodeOmission(originalFileContent: string, newFileContent: string): boolean {
const originalLines = originalFileContent.split("\n")
const newLines = newFileContent.split("\n")
const omissionKeywords = ["remain", "remains", "unchanged", "rest", "previous", "existing", "..."]
@ -33,26 +31,3 @@ function detectCodeOmission(originalFileContent: string, newFileContent: string)
return false
}
/**
* Shows a warning in VSCode if a potential code omission is detected.
* @param originalFileContent The original content of the file.
* @param newFileContent The new content of the file to check.
*/
export function showOmissionWarning(originalFileContent: string, newFileContent: string): void {
if (detectCodeOmission(originalFileContent, newFileContent)) {
vscode.window
.showWarningMessage(
"Potential code truncation detected. This happens when the AI reaches its max output limit.",
"Follow this guide to fix the issue",
)
.then((selection) => {
if (selection === "Follow this guide to fix the issue") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://github.com/cline/cline/wiki/Troubleshooting-%E2%80%90-Cline-Deleting-Code-with-%22Rest-of-Code-Here%22-Comments",
),
)
}
})
}
}

View file

@ -22,7 +22,7 @@ export async function extractTextFromFile(filePath: string): Promise<string> {
default:
const isBinary = await isBinaryFile(filePath).catch(() => false)
if (!isBinary) {
return await fs.readFile(filePath, "utf8")
return addLineNumbers(await fs.readFile(filePath, "utf8"))
} else {
throw new Error(`Cannot read text for file type: ${fileExtension}`)
}
@ -32,12 +32,12 @@ export async function extractTextFromFile(filePath: string): Promise<string> {
async function extractTextFromPDF(filePath: string): Promise<string> {
const dataBuffer = await fs.readFile(filePath)
const data = await pdf(dataBuffer)
return data.text
return addLineNumbers(data.text)
}
async function extractTextFromDOCX(filePath: string): Promise<string> {
const result = await mammoth.extractRawText({ path: filePath })
return result.value
return addLineNumbers(result.value)
}
async function extractTextFromIPYNB(filePath: string): Promise<string> {
@ -51,5 +51,17 @@ async function extractTextFromIPYNB(filePath: string): Promise<string> {
}
}
return extractedText
return addLineNumbers(extractedText)
}
export function addLineNumbers(content: string): string {
const lines = content.split('\n')
const maxLineNumberWidth = String(lines.length).length
return lines
.map((line, index) => {
const lineNumber = String(index + 1).padStart(maxLineNumberWidth, ' ')
return `${lineNumber} | ${line}`
}).join('\n')
}

View file

@ -42,6 +42,7 @@ export interface ExtensionState {
uriScheme?: string
allowedCommands?: string[]
soundEnabled?: boolean
diffEnabled?: boolean
}
export interface ClineMessage {
@ -86,6 +87,7 @@ export type ClineSay =
export interface ClineSayTool {
tool:
| "editedExistingFile"
| "appliedDiff"
| "newFileCreated"
| "readFile"
| "listFilesTopLevel"

View file

@ -31,6 +31,7 @@ export interface WebviewMessage {
| "alwaysAllowBrowser"
| "playSound"
| "soundEnabled"
| "diffEnabled"
text?: string
askResponse?: ClineAskResponse
apiConfiguration?: ApiConfiguration

View file

@ -33,6 +33,7 @@ export interface ApiHandlerOptions {
geminiApiKey?: string
openAiNativeApiKey?: string
azureApiVersion?: string
openRouterUseMiddleOutTransform?: boolean
}
export type ApiConfiguration = ApiHandlerOptions & {
@ -277,6 +278,14 @@ export const geminiModels = {
inputPrice: 0,
outputPrice: 0,
},
"gemini-exp-1206": {
maxTokens: 8192,
contextWindow: 2_097_152,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
},
} as const satisfies Record<string, ModelInfo>
// OpenAI Native

View file

@ -20,7 +20,7 @@ export const isWAV = (filepath: string): boolean => {
return path.extname(filepath).toLowerCase() === ".wav"
}
let isSoundEnabled = true
let isSoundEnabled = false
/**
* Set sound configuration

View file

@ -213,10 +213,11 @@ export const ChatRowContent = ({
switch (tool.tool) {
case "editedExistingFile":
case "appliedDiff":
return (
<>
<div style={headerStyle}>
{toolIcon("edit")}
{toolIcon(tool.tool === "appliedDiff" ? "diff" : "edit")}
<span style={{ fontWeight: "bold" }}>Cline wants to edit this file:</span>
</div>
<CodeAccordian

View file

@ -121,6 +121,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool
switch (tool.tool) {
case "editedExistingFile":
case "appliedDiff":
case "newFileCreated":
setPrimaryButtonText("Save")
setSecondaryButtonText("Reject")
@ -747,7 +748,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
const lastMessage = messages.at(-1)
if (lastMessage?.type === "ask" && lastMessage.text) {
const tool = JSON.parse(lastMessage.text)
return ["editedExistingFile", "newFileCreated"].includes(tool.tool)
return ["editedExistingFile", "appliedDiff", "newFileCreated"].includes(tool.tool)
}
return false
}

View file

@ -249,6 +249,15 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage }:
</span>
)} */}
</p>
<VSCodeCheckbox
checked={apiConfiguration?.openRouterUseMiddleOutTransform || false}
onChange={(e: any) => {
const isChecked = e.target.checked === true
setApiConfiguration({ ...apiConfiguration, openRouterUseMiddleOutTransform: isChecked })
}}>
Compress prompts and message chains to the context size (<a href="https://openrouter.ai/docs/transforms">OpenRouter Transforms</a>)
</VSCodeCheckbox>
<br/>
</div>
)}

View file

@ -27,6 +27,8 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
setAlwaysAllowBrowser,
soundEnabled,
setSoundEnabled,
diffEnabled,
setDiffEnabled,
openRouterModels,
setAllowedCommands,
allowedCommands,
@ -50,6 +52,7 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
vscode.postMessage({ type: "alwaysAllowBrowser", bool: alwaysAllowBrowser })
vscode.postMessage({ type: "allowedCommands", commands: allowedCommands ?? [] })
vscode.postMessage({ type: "soundEnabled", bool: soundEnabled })
vscode.postMessage({ type: "diffEnabled", bool: diffEnabled })
onDone()
}
}
@ -289,17 +292,35 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
)}
<div style={{ marginBottom: 5 }}>
<VSCodeCheckbox checked={soundEnabled} onChange={(e: any) => setSoundEnabled(e.target.checked)}>
<span style={{ fontWeight: "500" }}>Enable sound effects</span>
</VSCodeCheckbox>
<p
style={{
fontSize: "12px",
marginTop: "5px",
color: "var(--vscode-descriptionForeground)",
}}>
When enabled, Cline will play sound effects for notifications and events.
</p>
<h4 style={{ fontWeight: 500, marginBottom: 10 }}>Experimental Features</h4>
<div style={{ marginBottom: 5 }}>
<VSCodeCheckbox checked={diffEnabled} onChange={(e: any) => setDiffEnabled(e.target.checked)}>
<span style={{ fontWeight: "500" }}>Enable editing through diffs (very experimental!)</span>
</VSCodeCheckbox>
<p
style={{
fontSize: "12px",
marginTop: "5px",
color: "var(--vscode-descriptionForeground)",
}}>
When enabled, Cline will be able to apply diffs to make changes to files and will automatically reject truncated full-file edits.
</p>
</div>
<div style={{ marginBottom: 5 }}>
<VSCodeCheckbox checked={soundEnabled} onChange={(e: any) => setSoundEnabled(e.target.checked)}>
<span style={{ fontWeight: "500" }}>Enable sound effects</span>
</VSCodeCheckbox>
<p
style={{
fontSize: "12px",
marginTop: "5px",
color: "var(--vscode-descriptionForeground)",
}}>
When enabled, Cline will play sound effects for notifications and events.
</p>
</div>
</div>
{IS_DEV && (

View file

@ -26,6 +26,7 @@ export interface ExtensionStateContextType extends ExtensionState {
setShowAnnouncement: (value: boolean) => void
setAllowedCommands: (value: string[]) => void
setSoundEnabled: (value: boolean) => void
setDiffEnabled: (value: boolean) => void
}
const ExtensionStateContext = createContext<ExtensionStateContextType | undefined>(undefined)
@ -38,6 +39,7 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
shouldShowAnnouncement: false,
allowedCommands: [],
soundEnabled: false,
diffEnabled: false,
})
const [didHydrateState, setDidHydrateState] = useState(false)
const [showWelcome, setShowWelcome] = useState(false)
@ -127,6 +129,7 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
setShowAnnouncement: (value) => setState((prevState) => ({ ...prevState, shouldShowAnnouncement: value })),
setAllowedCommands: (value) => setState((prevState) => ({ ...prevState, allowedCommands: value })),
setSoundEnabled: (value) => setState((prevState) => ({ ...prevState, soundEnabled: value })),
setDiffEnabled: (value) => setState((prevState) => ({ ...prevState, diffEnabled: value })),
}
return <ExtensionStateContext.Provider value={contextValue}>{children}</ExtensionStateContext.Provider>