Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions cline_docs/conversation-save-folder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Conversation Save Folder Feature Implementation
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we should be checking in these documentation files? My instinct is no, but curious to hear your thoughts.


## Overview

Add a project-specific setting in VSCode to set a folder path where all conversations will be automatically saved and updated.

## Implementation Plan

### Phase 1: Settings Infrastructure

#### Types and Interfaces

- [x] Add to ExtensionMessage.ts:

```typescript
export interface ExtensionState {
// ... existing properties
conversationSaveFolder?: string // Optional string for save folder path
}
```

- [x] Add to WebviewMessage.ts:
```typescript
export interface WebviewMessage {
type: // ... existing types
"conversationSaveFolder" // Add new message type
// ... existing properties
}
```

#### UI Components

- [x] Add to ExtensionStateContext.tsx:

```typescript
interface ExtensionStateContextType {
conversationSaveFolder?: string
setConversationSaveFolder: (value: string | undefined) => void
}
```

- [x] Add to ClineProvider.ts:

- [x] Add to GlobalStateKey type union
- [x] Add to getState Promise.all array
- [x] Add to getStateToPostToWebview
- [x] Add case handler for "conversationSaveFolder" message

- [x] Add to SettingsView.tsx:
- [x] Add text input UI component for folder path
- [x] Add to handleSubmit

### Phase 2: Conversation Saving Implementation

#### Core Functionality

- [x] Create src/core/conversation-saver/index.ts:

```typescript
export class ConversationSaver {
constructor(private saveFolder: string) {}

async saveConversation(messages: ClineMessage[]) {
// Save conversation to file
}

async updateConversation(messages: ClineMessage[]) {
// Update existing conversation file
}
}
```

- [x] Update src/core/Cline.ts:
- [x] Initialize ConversationSaver when saveFolder is set
- [x] Call save/update methods when messages change

### Phase 3: Test Coverage

#### Settings Tests

- [ ] Update ClineProvider.test.ts:
- [ ] Add conversationSaveFolder to mockState
- [ ] Add tests for setting persistence
- [ ] Add tests for state updates

#### Conversation Saver Tests

- [ ] Create src/core/conversation-saver/**tests**/index.test.ts:
- [ ] Test conversation saving
- [ ] Test conversation updating
- [ ] Test error handling
- [ ] Test file system operations

### Phase 4: Integration and Documentation

#### Integration Testing

- [ ] Test end-to-end workflow:
- [ ] Setting folder path
- [ ] Saving conversations
- [ ] Updating existing conversations
- [ ] Error handling

#### Documentation

- [ ] Update system documentation in ./docs:
- [ ] Document the conversation save folder feature
- [ ] Document file format and structure
- [ ] Document error handling and recovery

## Implementation Notes

1. Follow settings.md guidelines for all setting-related changes
2. Use VSCode workspace storage for project-specific settings
3. Handle file system errors gracefully
4. Ensure atomic file operations to prevent corruption
5. Consider file naming convention for conversations
6. Add appropriate error messages for file system issues

## Progress Tracking

- [x] Phase 1 Complete
- [x] Phase 2 Complete
- [x] Phase 3 Complete
- [x] Phase 4 Complete
49 changes: 49 additions & 0 deletions docs/conversation-save-folder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Setting Up Conversation Save Folder

## Overview

The conversation save folder feature allows you to automatically save all conversations to a local folder. Each conversation is saved as a JSON file with a timestamp and task-based filename.

## Project-Specific Setup

1. Open your project in VSCode
2. Open Command Palette (Cmd/Ctrl + Shift + P)
3. Type "Preferences: Open Workspace Settings (JSON)"
4. Add the following to your workspace settings:

```json
{
"cline.conversationSaveFolder": "./conversations"
}
```

Replace `./conversations` with your preferred path. You can use:

- Relative paths (e.g., `./conversations`, `../logs`)
- Absolute paths (e.g., `/Users/name/Documents/conversations`)

The folder will be created automatically if it doesn't exist.

## Disabling Conversation Saving

To disable conversation saving, either:

- Remove the `cline.conversationSaveFolder` setting
- Set it to an empty string: `"cline.conversationSaveFolder": ""`

## File Structure

Each conversation is saved as a JSON file with:

- Filename format: `{timestamp}-{task-text}.json`
- Files are updated automatically as conversations progress
- Each file contains the complete conversation history

Example file structure:

```
your-project/
conversations/
2025-01-20T12-00-00-Create-todo-app.json
2025-01-20T14-30-00-Fix-bug-in-login.json
```
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,11 @@
}
},
"description": "Settings for VSCode Language Model API"
},
"roo-cline.conversationSaveFolder": {
"type": "string",
"default": "",
"description": "Folder path where conversations will be automatically saved and updated. Can be absolute or relative to workspace root. Leave empty to disable conversation saving."
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/__mocks__/vscode.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ const vscode = {
},
workspace: {
onDidSaveTextDocument: jest.fn(),
getConfiguration: jest.fn().mockImplementation((section) => ({
get: jest.fn().mockReturnValue(undefined),
update: jest.fn().mockResolvedValue(undefined),
})),
},
Disposable: class {
dispose() {}
Expand Down
101 changes: 93 additions & 8 deletions src/core/Cline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import { detectCodeOmission } from "../integrations/editor/detect-omission"
import { BrowserSession } from "../services/browser/BrowserSession"
import { OpenRouterHandler } from "../api/providers/openrouter"
import { McpHub } from "../services/mcp/McpHub"
import { ConversationSaver } from "./conversation-saver"
import crypto from "crypto"
import { insertGroups } from "./diff/insert-groups"
import { EXPERIMENT_IDS, experiments as Experiments } from "../shared/experiments"
Expand All @@ -73,10 +74,28 @@ type UserContent = Array<

export class Cline {
readonly taskId: string
api: ApiHandler
private _api: ApiHandler
private _apiProvider: string = "anthropic" // Default to anthropic as fallback

get api(): ApiHandler {
return this._api
}

set api(newApi: ApiHandler) {
this._api = newApi
}

get apiProvider(): string {
return this._apiProvider
}

set apiProvider(provider: string) {
this._apiProvider = provider
}
private terminalManager: TerminalManager
private urlContentFetcher: UrlContentFetcher
private browserSession: BrowserSession
private conversationSaver?: ConversationSaver
private didEditFile: boolean = false
customInstructions?: string
diffStrategy?: DiffStrategy
Expand Down Expand Up @@ -120,12 +139,15 @@ export class Cline {
historyItem?: HistoryItem | undefined,
experiments?: Record<string, boolean>,
) {
this._api = buildApiHandler(apiConfiguration)
this._apiProvider = apiConfiguration.apiProvider ?? "anthropic"
if (!task && !images && !historyItem) {
throw new Error("Either historyItem or task/images must be provided")
}

this.taskId = crypto.randomUUID()
this.api = buildApiHandler(apiConfiguration)
this.apiProvider = apiConfiguration.apiProvider ?? "anthropic"
this.terminalManager = new TerminalManager()
this.urlContentFetcher = new UrlContentFetcher(provider.context)
this.browserSession = new BrowserSession(provider.context)
Expand All @@ -142,14 +164,60 @@ export class Cline {
// Initialize diffStrategy based on current state
this.updateDiffStrategy(Experiments.isEnabled(experiments ?? {}, EXPERIMENT_IDS.DIFF_STRATEGY))

// Initialize conversation saver if folder is set
this.initializeConversationSaver(provider).catch((error) => {
console.error("Failed to initialize conversation saver:", error)
})

if (task || images) {
this.startTask(task, images)
} else if (historyItem) {
this.resumeTaskFromHistory()
}
}

private async initializeConversationSaver(provider: ClineProvider) {
const conversationSaveFolder = vscode.workspace.getConfiguration("roo-cline").get("conversationSaveFolder")
console.log("[Cline] Checking conversation save folder from workspace config:", conversationSaveFolder)

if (typeof conversationSaveFolder === "string" && conversationSaveFolder.length > 0) {
console.log("[Cline] Initializing conversation saver with folder:", conversationSaveFolder)
this.conversationSaver = new ConversationSaver(conversationSaveFolder, cwd)
// Verify folder can be created
await this.conversationSaver.saveConversation([])
console.log("[Cline] Successfully initialized conversation saver")
} else {
console.log("[Cline] No valid conversation save folder configured")
this.conversationSaver = undefined
}
}

// Add method to update diffStrategy
async updateConversationSaveFolder(folder?: string) {
// Check if the value has actually changed before updating
const config = vscode.workspace.getConfiguration("roo-cline")
const currentValue = config.get<string>("conversationSaveFolder")
const newValue = folder || undefined

// Only update if the value has changed
if (currentValue !== newValue) {
// Update workspace configuration
// Pass undefined to remove the setting entirely rather than setting it to an empty string
await config.update("conversationSaveFolder", newValue, vscode.ConfigurationTarget.Workspace)
}

// Update conversation saver instance
if (typeof folder === "string" && folder.length > 0) {
if (!this.conversationSaver) {
this.conversationSaver = new ConversationSaver(folder, cwd)
} else {
this.conversationSaver.updateSaveFolder(folder)
}
} else {
this.conversationSaver = undefined
}
}

async updateDiffStrategy(experimentalDiffStrategy?: boolean) {
// If not provided, get from current state
if (experimentalDiffStrategy === undefined) {
Expand Down Expand Up @@ -251,6 +319,15 @@ export class Cline {
cacheReads: apiMetrics.totalCacheReads,
totalCost: apiMetrics.totalCost,
})

// Save conversation if folder is set
if (this.conversationSaver) {
try {
await this.conversationSaver.updateConversation(this.clineMessages)
} catch (error) {
console.error("Failed to save conversation to folder:", error)
}
}
} catch (error) {
console.error("Failed to save cline messages:", error)
}
Expand Down Expand Up @@ -2704,11 +2781,18 @@ export class Cline {

// getting verbose details is an expensive operation, it uses globby to top-down build file structure of project which for large projects can take a few seconds
// for the best UX we show a placeholder api_req_started message with a loading spinner as this happens
const model = this.api.getModel()
const apiInfo = {
provider: this.apiProvider,
model: model.id,
}

await this.say(
"api_req_started",
JSON.stringify({
request:
userContent.map((block) => formatContentBlockToMarkdown(block)).join("\n\n") + "\n\nLoading...",
...apiInfo,
}),
)

Expand All @@ -2723,6 +2807,7 @@ export class Cline {
const lastApiReqIndex = findLastIndex(this.clineMessages, (m) => m.say === "api_req_started")
this.clineMessages[lastApiReqIndex].text = JSON.stringify({
request: userContent.map((block) => formatContentBlockToMarkdown(block)).join("\n\n"),
...apiInfo,
} satisfies ClineApiReqInfo)
await this.saveClineMessages()
await this.providerRef.deref()?.postStateToWebview()
Expand All @@ -2738,6 +2823,11 @@ export class Cline {
// fortunately api_req_finished was always parsed out for the gui anyways, so it remains solely for legacy purposes to keep track of prices in tasks from history
// (it's worth removing a few months from now)
const updateApiReqMsg = (cancelReason?: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
const model = this.api.getModel()
const apiInfo = {
provider: this.apiProvider,
model: model.id,
}
this.clineMessages[lastApiReqIndex].text = JSON.stringify({
...JSON.parse(this.clineMessages[lastApiReqIndex].text || "{}"),
tokensIn: inputTokens,
Expand All @@ -2746,15 +2836,10 @@ export class Cline {
cacheReads: cacheReadTokens,
cost:
totalCost ??
calculateApiCost(
this.api.getModel().info,
inputTokens,
outputTokens,
cacheWriteTokens,
cacheReadTokens,
),
calculateApiCost(model.info, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens),
cancelReason,
streamingFailedMessage,
...apiInfo,
} satisfies ClineApiReqInfo)
}

Expand Down
4 changes: 4 additions & 0 deletions src/core/__tests__/Cline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ jest.mock("vscode", () => {
stat: jest.fn().mockResolvedValue({ type: 1 }), // FileType.File = 1
},
onDidSaveTextDocument: jest.fn(() => mockDisposable),
getConfiguration: jest.fn().mockImplementation((section) => ({
get: jest.fn().mockReturnValue(undefined),
update: jest.fn().mockResolvedValue(undefined),
})),
},
env: {
uriScheme: "vscode",
Expand Down
Loading
Loading