| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 0 | 19 | 37 | 0% |
| Commands | 0 | 3 | 1 | 0% |
| Section tags | 1 | 4 | 2 | 14% |
What each file covers
Sections
0 shared · 19 only in A · 37 only in B- − Debug Harness
- − Quick start
- − Build extension first if needed (protos + esbuild):
- − Launch (skip-build if already built). Run with node, NOT bun — Playwright's
- − Electron launch times out under bun:
- − In another terminal:
- − Data Isolation
- − Browser Capture & OAuth
- − OAuth API
- − OAuth testing flow
- − Navigating Views — Use Commands, Not Clicks
- − Key commands
- − Typical Session
- − 1. Launch
- − 2. Open sidebar + dismiss overlays (ALWAYS do this first)
- − 3. Navigate to view
- − 4. Check captured OAuth URLs if testing auth
- − 5. Verify
- − Caveats
- + Cline Extension Architecture & Development Guide
- + Project Overview
- + Architecture Overview
- + Definitions
- + Core Extension Architecture
- + WebviewProvider Implementation
- + Core Extension State
- + Webview State
- + API Provider System
- + API Provider Architecture
- + API Configuration Management
- + Plan/Act Mode API Configuration
- + Task Execution System
- + Task Execution Loop
- + Message Streaming System
- + Tool Execution Flow
- + Error Handling & Recovery
- + API Request & Token Management
- + Context Management System
- + Task State & Resumption
- + Plan/Act Mode System
- + Mode Architecture
- + Mode Switching Process
- + Plan Mode
- + Act Mode
- + Data Flow & State Management
- + Core Extension Role
- + Terminal Management
- + Browser Session Management
- + MCP (Model Context Protocol) Integration
- + MCP Architecture
- + MCP Server Types
- + MCP Server Management
- + MCP Tool Integration
- + MCP Marketplace
- + Conclusion
- + Contributing
Commands
0 shared · 3 only in A · 1 only in B- − bun run protos && IS_DEV=true bun esbuild.mjs
- − node src/dev/debug-harness/server.ts --skip-build --auto-launch
- − bun run dev:mcp-oauth-test-server
- + task: taskMessage.text,
Section tags
1 shared · 4 only in A · 2 only in B- − build
- − test
- − testing-strategy
- − security
- + architecture
- + types
- api
Line diff
cline/cline · .clinerules/debug-harness.md
@@ −1 @@
1# Debug Harness
2
3HTTP-controlled debugger for the VSCode extension at `src/dev/debug-harness/server.ts`.
4
5## Quick start
6
7```bash
8# Build extension first if needed (protos + esbuild):
9bun run protos && IS_DEV=true bun esbuild.mjs
10
11# Launch (skip-build if already built). Run with node, NOT bun — Playwright's
12# Electron launch times out under bun:
13node src/dev/debug-harness/server.ts --skip-build --auto-launch
14
15# In another terminal:
16curl localhost:19229/api -d '{"method":"status"}'
17```
18
19## Data Isolation
20
21The debugee runs with `CLINE_DIR=~/.cline2` by default, separate from your real `~/.cline`.
22This prevents the debugee's logout from logging out the debugger, and vice versa.
23Override with `--cline-dir /tmp/test-dir`. Check with `status()` → `clineDir`.
24
25## Browser Capture & OAuth
26
27The debugee runs with `CLINE_CAPTURE_BROWSER=1`, which intercepts `openExternal()` in
28`src/utils/env.ts`. URLs are captured instead of opening a real browser:
29
30- Logged to `$CLINE_DIR/data/debug-captured-urls.jsonl`
31- POSTed in real-time to `/captured-url` on the harness server
32- Queryable via `oauth.captured_urls`
33
34### OAuth API
35
36- **`oauth.captured_urls`** `{clear?}` — URLs the debugee tried to open
37- **`oauth.read_stored_token`** — Check auth token presence in secrets.json
38- **`oauth.simulate_callback`** `{path, code?, state?, provider?, token?}` — Build vscode:// callback URI
39- **`oauth.read_captured_urls_file`** — Read on-disk JSONL of captured URLs
40
41### OAuth testing flow
42
43For **Cline OAuth** (SDK local callback): The SDK starts a local HTTP server, the auth URL
44is captured. To complete: open the captured URL in a real browser (it redirects back to the
45SDK's callback server), OR extract the callback port and `curl http://127.0.0.1:PORT/callback?code=...`.
46
47For **MCP/Provider OAuth** (vscode:// URI): The redirect goes to a vscode:// URI.
48`oauth.simulate_callback` only *builds* the URI — it does not deliver it, and the ESM
49extension host can't `require()` the handler. To actually deliver the callback, call the
50debug-only hook via `ext.evaluate` (with `awaitPromise: true`):
51`globalThis.__clineHandleUri("vscode://saoudrizwan.claude-dev/...?code=...&state=...")`.
52It runs the same `SharedUriHandler.handleUri` as VSCode's real URI handler and exists only
53when `CLINE_CAPTURE_BROWSER` is set (the harness always sets it; never ships in prod).
54For end-to-end MCP OAuth, get a real `code` from the local MCP OAuth test server
55(`bun run dev:mcp-oauth-test-server`).
56
57## Navigating Views — Use Commands, Not Clicks
58
59Don't try to find/click small sidebar icons. Use VSCode commands via command palette.
60Registered in `src/registry.ts`:
61
62| Command | View |
63|---------|------|
64| `cline.accountButtonClicked` | Account / sign-in |
65| `cline.historyButtonClicked` | Task history |
66| `cline.settingsButtonClicked` | Settings |
67| `cline.mcpButtonClicked` | MCP servers |
68| `cline.plusButtonClicked` | New task (chat) |
69| `cline.worktreesButtonClicked` | Worktrees |
70
71```bash
72curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
73```
74
75## Key commands
76
77All via `POST localhost:19229/api` with `{"method":"...", "params":{...}}`:
78
79- **`launch`** / **`shutdown`** — lifecycle
80- **`ui.screenshot`** — screenshot to `/tmp/cline-debug/`; returns `{path}` — **use `read_file` on the path to examine, do NOT `open` the file** (Preview.app covers the VSCode window)
81- **`ui.open_sidebar`** — open the Cline sidebar
82- **`ext.set_breakpoint`** `{file, line, condition?}` — breakpoint by source file (sourcemap-resolved)
83- **`ext.evaluate`** `{expression, callFrameId?}` — eval in extension host
84- **`ext.resume`** / **`ext.step_over`** / **`ext.step_into`** — stepping
85- **`ext.call_stack`** — inspect when paused
86- **`web.evaluate`** `{expression}` — eval in webview
87- **`web.post_message`** `{message}` — send postMessage to extension host via exposed vsCodeApi
88- **`wait_for_pause`** `{timeout?}` — block until breakpoint hit
89- **`ui.locator`** `{role?, testId?, text?, frame?}` — Playwright locator (auto-retries on stale sidebar frame)
90- **`ui.react_input`** `{text, selector?, clear?, submit?}` — set React textarea value via `execCommand('insertText')`; works reliably across multiple tasks
91- **`ui.send_message`** `{text, images?, files?, responseType?}` — send chat message bypassing the textarea entirely (via gRPC postMessage)
92- **`ui.command_palette`** `{command}` — run VSCode command
93
94## Typical Session
95
96```bash
97# 1. Launch
98curl localhost:19229/api -d '{"method":"launch","params":{"skipBuild":true}}'
99
100# 2. Open sidebar + dismiss overlays (ALWAYS do this first)
101curl localhost:19229/api -d '{"method":"ui.open_sidebar"}'
102curl localhost:19229/api -d '{"method":"web.evaluate","params":{"expression":"document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
103
104# 3. Navigate to view
105curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
106
107# 4. Check captured OAuth URLs if testing auth
108curl localhost:19229/api -d '{"method":"oauth.captured_urls"}'
109
110# 5. Verify
111curl localhost:19229/api -d '{"method":"ui.screenshot"}'
112```
113
114## Caveats
115
116- **⚠️ Dismiss promotional overlays FIRST**: On fresh launches, full-screen promo overlays block the sidebar. **Dismiss immediately after `ui.open_sidebar`**, before any other interaction or screenshot. May need to run twice:
117 ```bash
118 curl localhost:19229/api -d '{"method": "ui.open_sidebar"}'
119 curl localhost:19229/api -d '{"method": "web.evaluate", "params": {"expression": "document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
120 ```
121- **Screenshots — don't open the file**: `ui.screenshot` and `ui.sidebar_screenshot` save PNGs to `/tmp/cline-debug/` and return the `{path}`. Use `read_file` on that path to examine screenshots. Running `open <path>` launches Preview.app on macOS which covers the VSCode window.
122- **Scripts count = 0 after launch**: CDP connects after extension host starts, so scripts parsed during startup aren't tracked. Breakpoints still work via sourcemap resolution.
123- **Port 9230**: Extension host inspector. If another VSCode instance uses this port, the harness will fail to connect. Kill other debug instances first.
124- **macOS only** for now (Playwright Electron launch behavior).
125- **Webview CDP**: `connect_webview` may fail depending on Electron version. `web.evaluate` still works via Playwright's `frame.evaluate()` fallback.
126- **Sourcemap paths**: esbuild outputs relative paths like `../src/extension.ts` in the sourcemap. The resolver handles this, but if a file isn't found, use `ext.source_files` to see exact paths.
127- **OAuth with fake codes**: Browser capture intercepts the URL but doesn't provide a valid auth code. For real OAuth testing, open the captured URL in a browser. For unit testing, mock the token exchange.
128
129See `src/dev/debug-harness/README.md` for full API reference.
130
cline/cline · .clinerules/cline-overview.md
@@ +1 @@
1# Cline Extension Architecture & Development Guide
2
3## Project Overview
4
5Cline is a VSCode extension that provides AI assistance through a combination of a core extension backend and a React-based webview frontend. The extension is built with TypeScript and follows a modular architecture pattern.
6
7## Architecture Overview
8
9```mermaid
10graph TB
11 subgraph VSCodeExtensionHost[VSCode Extension Host]
12 subgraph CoreExtension[Core Extension]
13 ExtensionEntry[Extension Entry<br/>src/extension.ts]
14 WebviewProvider[WebviewProvider<br/>src/core/webview/index.ts]
15 Controller[Controller<br/>src/core/controller/index.ts]
16 Task[Task<br/>src/core/task/index.ts]
17 GlobalState[VSCode Global State]
18 SecretsStorage[VSCode Secrets Storage]
19 McpHub[McpHub<br/>src/services/mcp/McpHub.ts]
20 end
21
22 subgraph WebviewUI[Webview UI]
23 WebviewApp[React App<br/>webview-ui/src/App.tsx]
24 ExtStateContext[ExtensionStateContext<br/>webview-ui/src/context/ExtensionStateContext.tsx]
25 ReactComponents[React Components]
26 end
27
28 subgraph Storage
29 TaskStorage[Task Storage<br/>Per-Task Files & History]
30 CheckpointSystem[Git-based Checkpoints]
31 end
32
33 subgraph apiProviders[API Providers]
34 AnthropicAPI[Anthropic]
35 OpenRouterAPI[OpenRouter]
36 BedrockAPI[AWS Bedrock]
37 OtherAPIs[Other Providers]
38 end
39
40 subgraph MCPServers[MCP Servers]
41 ExternalMcpServers[External MCP Servers]
42 end
43 end
44
45 %% Core Extension Data Flow
46 ExtensionEntry --> WebviewProvider
47 WebviewProvider --> Controller
48 Controller --> Task
49 Controller --> McpHub
50 Task --> GlobalState
51 Task --> SecretsStorage
52 Task --> TaskStorage
53 Task --> CheckpointSystem
54 Task --> |API Requests| apiProviders
55 McpHub --> |Connects to| ExternalMcpServers
56 Task --> |Uses| McpHub
57
58 %% Webview Data Flow
59 WebviewApp --> ExtStateContext
60 ExtStateContext --> ReactComponents
61
62 %% Bidirectional Communication
63 WebviewProvider <-->|postMessage| ExtStateContext
64
65 style GlobalState fill:#f9f,stroke:#333,stroke-width:2px
66 style SecretsStorage fill:#f9f,stroke:#333,stroke-width:2px
67 style ExtStateContext fill:#bbf,stroke:#333,stroke-width:2px
68 style WebviewProvider fill:#bfb,stroke:#333,stroke-width:2px
69 style McpHub fill:#bfb,stroke:#333,stroke-width:2px
70 style apiProviders fill:#fdb,stroke:#333,stroke-width:2px
71```
72
73## Definitions
74
75- **Core Extension**: Anything inside the src folder, organized into modular components
76- **Core Extension State**: Managed by the Controller class in src/core/controller/index.ts, which serves as the single source of truth for the extension's state. It manages multiple types of persistent storage (global state, workspace state, and secrets), handles state distribution to both the core extension and webview components, and coordinates state across multiple extension instances. This includes managing API configurations, task history, settings, and MCP configurations.
77- **Webview**: Anything inside the webview-ui. All the react or view's seen by the user and user interaction components
78- **Webview State**: Managed by ExtensionStateContext in webview-ui/src/context/ExtensionStateContext.tsx, which provides React components with access to the extension's state through a context provider pattern. It maintains local state for UI components, handles real-time updates through message events, manages partial message updates, and provides methods for state modifications. The context includes extension version, messages, task history, theme, API configurations, MCP servers, marketplace catalog, and workspace file paths. It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to state through a custom hook (useExtensionState).
79
80### Core Extension Architecture
81
82The core extension follows a clear hierarchical structure:
83
841. **WebviewProvider** (src/core/webview/index.ts): Manages the webview lifecycle and communication
852. **Controller** (src/core/controller/index.ts): Handles webview messages and task management
863. **Task** (src/core/task/index.ts): Executes API requests and tool operations
87
88This architecture provides clear separation of concerns:
89- WebviewProvider focuses on VSCode webview integration
90- Controller manages state and coordinates tasks
91- Task handles the execution of AI requests and tool operations
92
93### WebviewProvider Implementation
94
95The WebviewProvider class in `src/core/webview/index.ts` is responsible for:
96
97- Managing multiple active instances through a static set (`activeInstances`)
98- Handling webview lifecycle events (creation, visibility changes, disposal)
99- Implementing HTML content generation with proper CSP headers
100- Supporting Hot Module Replacement (HMR) for development
101- Setting up message listeners between the webview and extension
102
103The WebviewProvider maintains a reference to the Controller and delegates message handling to it. It also handles the creation of both sidebar and tab panel webviews, allowing Cline to be used in different contexts within VSCode.
104
105### Core Extension State
106
107The `Controller` class manages multiple types of persistent storage:
108
109- **Global State:** Stored across all VSCode instances. Used for settings and data that should persist globally.
110- **Workspace State:** Specific to the current workspace. Used for task-specific data and settings.
111- **Secrets:** Secure storage for sensitive information like API keys.
112
113The `Controller` handles the distribution of state to both the core extension and webview components. It also coordinates state across multiple extension instances, ensuring consistency.
114
115State synchronization between instances is handled through:
116- File-based storage for task history and conversation data
117- VSCode's global state API for settings and configuration
118- Secrets storage for sensitive information
119- Event listeners for file changes and configuration updates
120
121The Controller implements methods for:
122- Saving and loading task state
123- Managing API configurations
124- Handling user authentication
125- Coordinating MCP server connections
126- Managing task history and checkpoints
127
128### Webview State
129
130The `ExtensionStateContext` in `webview-ui/src/context/ExtensionStateContext.tsx` provides React components with access to the extension's state. It uses a context provider pattern and maintains local state for UI components. The context includes:
131
132- Extension version
133- Messages
134- Task history
135- Theme
136- API configurations
137- MCP servers
138- Marketplace catalog
139- Workspace file paths
140
141It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to the state via a custom hook (`useExtensionState`).
142
143The ExtensionStateContext handles:
144- Real-time updates through message events
145- Partial message updates for streaming content
146- State modifications through setter methods
147- Type-safe access to state through a custom hook
148
149## API Provider System
150
151Cline supports multiple AI providers through a modular API provider system. Each provider is implemented as a separate module in the `src/api/providers/` directory and follows a common interface.
152
153### API Provider Architecture
154
155The API system consists of:
156
1571. **API Handlers**: Provider-specific implementations in `src/api/providers/`
1582. **API Transformers**: Stream transformation utilities in `src/api/transform/`
1593. **API Configuration**: User settings for API keys and endpoints
1604. **API Factory**: Builder function to create the appropriate handler
161
162Key providers include:
163- **Anthropic**: Direct integration with Claude models
164- **OpenRouter**: Meta-provider supporting multiple model providers
165- **AWS Bedrock**: Integration with Amazon's AI services
166- **Gemini**: Google's AI models
167- **Cerebras**: High-performance inference with Llama, Qwen, and DeepSeek models
168- **Ollama**: Local model hosting
169- **LM Studio**: Local model hosting
170- **VSCode LM**: VSCode's built-in language models
171
172### API Configuration Management
173
174API configurations are stored securely:
175- API keys are stored in VSCode's secrets storage
176- Model selections and non-sensitive settings are stored in global state
177- The Controller manages switching between providers and updating configurations
178
179The system supports:
180- Secure storage of API keys
181- Model selection and configuration
182- Automatic retry and error handling
183- Token usage tracking and cost calculation
184- Context window management
185
186### Plan/Act Mode API Configuration
187
188Cline supports separate model configurations for Plan and Act modes:
189- Different models can be used for planning vs. execution
190- The system preserves model selections when switching modes
191- The Controller handles the transition between modes and updates the API configuration accordingly
192
193## Task Execution System
194
195The Task class is responsible for executing AI requests and tool operations. Each task runs in its own instance of the Task class, ensuring isolation and proper state management.
196
197### Task Execution Loop
198
199The core task execution loop follows this pattern:
200
201```typescript
202class Task {
203 async initiateTaskLoop(userContent: UserContent, isNewTask: boolean) {
204 while (!this.abort) {
205 // 1. Make API request and stream response
206 const stream = this.attemptApiRequest()
207
208 // 2. Parse and present content blocks
209 for await (const chunk of stream) {
210 switch (chunk.type) {
211 case "text":
212 // Parse into content blocks
213 this.assistantMessageContent = parseAssistantMessageV2(chunk.text)
214 // Present blocks to user
215 await this.presentAssistantMessage()
216 break
217 }
218 }
219
220 // 3. Wait for tool execution to complete
221 await pWaitFor(() => this.userMessageContentReady)
222
223 // 4. Continue loop with tool result
224 const recDidEndLoop = await this.recursivelyMakeClineRequests(
225 this.userMessageContent
226 )
227 }
228 }
229}
230```
231
232### Message Streaming System
233
234The streaming system handles real-time updates and partial content:
235
236```typescript
237class Task {
238 async presentAssistantMessage() {
239 // Handle streaming locks to prevent race conditions
240 if (this.presentAssistantMessageLocked) {
241 this.presentAssistantMessageHasPendingUpdates = true
242 return
243 }
244 this.presentAssistantMessageLocked = true
245
246 // Present current content block
247 const block = this.assistantMessageContent[this.currentStreamingContentIndex]
248
249 // Handle different types of content
250 switch (block.type) {
251 case "text":
252 await this.say("text", content, undefined, block.partial)
253 break
254 case "tool_use":
255 // Handle tool execution
256 break
257 }
258
259 // Move to next block if complete
260 if (!block.partial) {
261 this.currentStreamingContentIndex++
262 }
263 }
264}
265```
266
267### Tool Execution Flow
268
269Tools follow a strict execution pattern:
270
271```typescript
272class Task {
273 async executeToolWithApproval(block: ToolBlock) {
274 // 1. Check auto-approval settings
275 if (this.shouldAutoApproveTool(block.name)) {
276 await this.say("tool", message)
277 this.consecutiveAutoApprovedRequestsCount++
278 } else {
279 // 2. Request user approval
280 const didApprove = await askApproval("tool", message)
281 if (!didApprove) {
282 this.didRejectTool = true
283 return
284 }
285 }
286
287 // 3. Execute tool
288 const result = await this.executeTool(block)
289
290 // 4. Save checkpoint
291 await this.saveCheckpoint()
292
293 // 5. Return result to API
294 return result
295 }
296}
297```
298
299### Error Handling & Recovery
300
301The system includes robust error handling:
302
303```typescript
304class Task {
305 async handleError(action: string, error: Error) {
306 // 1. Check if task was abandoned
307 if (this.abandoned) return
308
309 // 2. Format error message
310 const errorString = `Error ${action}: ${error.message}`
311
312 // 3. Present error to user
313 await this.say("error", errorString)
314
315 // 4. Add error to tool results
316 pushToolResult(formatResponse.toolError(errorString))
317
318 // 5. Cleanup resources
319 await this.diffViewProvider.revertChanges()
320 await this.browserSession.closeBrowser()
321 }
322}
323```
324
325### API Request & Token Management
326
327The Task class handles API requests with built-in retry, streaming, and token management:
328
329```typescript
330class Task {
331 async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
332 // 1. Wait for MCP servers to connect
333 await pWaitFor(() => this.controllerRef.deref()?.mcpHub?.isConnecting !== true)
334
335 // 2. Manage context window
336 const previousRequest = this.clineMessages[previousApiReqIndex]
337 if (previousRequest?.text) {
338 const { tokensIn, tokensOut } = JSON.parse(previousRequest.text || "{}")
339 const totalTokens = (tokensIn || 0) + (tokensOut || 0)
340
341 // Truncate conversation if approaching context limit
342 if (totalTokens >= maxAllowedSize) {
343 this.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
344 this.apiConversationHistory,
345 this.conversationHistoryDeletedRange,
346 totalTokens / 2 > maxAllowedSize ? "quarter" : "half"
347 )
348 }
349 }
350
351 // 3. Handle streaming with automatic retry
352 try {
353 this.isWaitingForFirstChunk = true
354 const firstChunk = await iterator.next()
355 yield firstChunk.value
356 this.isWaitingForFirstChunk = false
357
358 // Stream remaining chunks
359 yield* iterator
360 } catch (error) {
361 // 4. Error handling with retry
362 if (isOpenRouter && !this.didAutomaticallyRetryFailedApiRequest) {
363 await setTimeoutPromise(1000)
364 this.didAutomaticallyRetryFailedApiRequest = true
365 yield* this.attemptApiRequest(previousApiReqIndex)
366 return
367 }
368
369 // 5. Ask user to retry if automatic retry failed
370 const { response } = await this.ask(
371 "api_req_failed",
372 this.formatErrorWithStatusCode(error)
373 )
374 if (response === "yesButtonClicked") {
375 await this.say("api_req_retried")
376 yield* this.attemptApiRequest(previousApiReqIndex)
377 return
378 }
379 }
380 }
381}
382```
383
384Key features:
385
3861. **Context Window Management**
387 - Tracks token usage across requests
388 - Automatically truncates conversation when needed
389 - Preserves important context while freeing space
390 - Handles different model context sizes
391
3922. **Streaming Architecture**
393 - Real-time chunk processing
394 - Partial content handling
395 - Race condition prevention
396 - Error recovery during streaming
397
3983. **Error Handling**
399 - Automatic retry for transient failures
400 - User-prompted retry for persistent issues
401 - Detailed error reporting
402 - State cleanup on failure
403
4044. **Token Tracking**
405 - Per-request token counting
406 - Cumulative usage tracking
407 - Cost calculation
408 - Cache hit monitoring
409
410### Context Management System
411
412The Context Management System handles conversation history truncation to prevent context window overflow errors. Implemented in the `ContextManager` class, it ensures long-running conversations remain within model context limits while preserving critical context.
413
414Key features:
415
4161. **Model-Aware Sizing**: Dynamically adjusts based on different model context windows (64K for DeepSeek, 128K for most models, 200K for Claude).
417
4182. **Proactive Truncation**: Monitors token usage and preemptively truncates conversations when approaching limits, maintaining buffers of 27K-40K tokens depending on the model.
419
4203. **Intelligent Preservation**: Always preserves the original task message and maintains the user-assistant conversation structure when truncating.
421
4224. **Adaptive Strategies**: Uses different truncation strategies based on context pressure - removing half of the conversation for moderate pressure or three-quarters for severe pressure.
423
4245. **Error Recovery**: Includes specialized detection for context window errors from different providers with automatic retry and more aggressive truncation when needed.
425
426### Task State & Resumption
427
428The Task class provides robust task state management and resumption capabilities:
429
430```typescript
431class Task {
432 async resumeTaskFromHistory() {
433 // 1. Load saved state
434 this.clineMessages = await getSavedClineMessages(this.getContext(), this.taskId)
435 this.apiConversationHistory = await getSavedApiConversationHistory(this.getContext(), this.taskId)
436
437 // 2. Handle interrupted tool executions
438 const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
439 if (lastMessage.role === "assistant") {
440 const toolUseBlocks = content.filter(block => block.type === "tool_use")
441 if (toolUseBlocks.length > 0) {
442 // Add interrupted tool responses
443 const toolResponses = toolUseBlocks.map(block => ({
444 type: "tool_result",
445 tool_use_id: block.id,
446 content: "Task was interrupted before this tool call could be completed."
447 }))
448 modifiedOldUserContent = [...toolResponses]
449 }
450 }
451
452 // 3. Notify about interruption
453 const agoText = this.getTimeAgoText(lastMessage?.ts)
454 newUserContent.push({
455 type: "text",
456 text: `[TASK RESUMPTION] This task was interrupted ${agoText}. It may or may not be complete, so please reassess the task context.`
457 })
458
459 // 4. Resume task execution
460 await this.initiateTaskLoop(newUserContent, false)
461 }
462
463 private async saveTaskState() {
464 // Save conversation history
465 await saveApiConversationHistory(this.getContext(), this.taskId, this.apiConversationHistory)
466 await saveClineMessages(this.getContext(), this.taskId, this.clineMessages)
467
468 // Create checkpoint
469 const commitHash = await this.checkpointTracker?.commit()
470
471 // Update task history
472 await this.controllerRef.deref()?.updateTaskHistory({
473 id: this.taskId,
474 ts: lastMessage.ts,
475 task: taskMessage.text,
476 // ... other metadata
477 })
478 }
479}
480```
481
482Key aspects of task state management:
483
4841. **Task Persistence**
485 - Each task has a unique ID and dedicated storage directory
486 - Conversation history is saved after each message
487 - File changes are tracked through Git-based checkpoints
488 - Terminal output and browser state are preserved
489
4902. **State Recovery**
491 - Tasks can be resumed from any point
492 - Interrupted tool executions are handled gracefully
493 - File changes can be restored from checkpoints
494 - Context is preserved across VSCode sessions
495
4963. **Workspace Synchronization**
497 - File changes are tracked through Git
498 - Checkpoints are created after tool executions
499 - State can be restored to any checkpoint
500 - Changes can be compared between checkpoints
501
5024. **Error Recovery**
503 - Failed API requests can be retried
504 - Interrupted tool executions are marked
505 - Resources are cleaned up properly
506 - User is notified of state changes
507
508## Plan/Act Mode System
509
510Cline implements a dual-mode system that separates planning from execution:
511
512### Mode Architecture
513
514The Plan/Act mode system consists of:
515
5161. **Mode State**: Stored in `chatSettings.mode` in the Controller's state
5172. **Mode Switching**: Handled by `togglePlanActModeWithChatSettings` in the Controller
5183. **Mode-specific Models**: Optional configuration to use different models for each mode
5194. **Mode-specific Prompting**: Different system prompts for planning vs. execution
520
521### Mode Switching Process
522
523When switching between modes:
524
5251. The current model configuration is saved to mode-specific state
5262. The previous mode's model configuration is restored
5273. The Task instance is updated with the new mode
5284. The webview is notified of the mode change
5295. Telemetry events are captured for analytics
530
531### Plan Mode
532
533Plan mode is designed for:
534- Information gathering and context building
535- Asking clarifying questions
536- Creating detailed execution plans
537- Discussing approaches with the user
538
539In Plan mode, the AI uses the `plan_mode_respond` tool to engage in conversational planning without executing actions.
540
541### Act Mode
542
543Act mode is designed for:
544- Executing the planned actions
545- Using tools to modify files, run commands, etc.
546- Implementing the solution
547- Providing results and completion feedback
548
549In Act mode, the AI has access to all tools except `plan_mode_respond` and focuses on implementation rather than discussion.
550
551## Data Flow & State Management
552
553### Core Extension Role
554
555The Controller acts as the single source of truth for all persistent state. It:
556- Manages VSCode global state and secrets storage
557- Coordinates state updates between components
558- Ensures state consistency across webview reloads
559- Handles task-specific state persistence
560- Manages checkpoint creation and restoration
561
562### Terminal Management
563
564The Task class manages terminal instances and command execution:
565
566```typescript
567class Task {
568 async executeCommandTool(command: string): Promise<[boolean, ToolResponse]> {
569 // 1. Get or create terminal
570 const terminalInfo = await this.terminalManager.getOrCreateTerminal(cwd)
571 terminalInfo.terminal.show()
572
573 // 2. Execute command with output streaming
574 const process = this.terminalManager.runCommand(terminalInfo, command)
575
576 // 3. Handle real-time output
577 let result = ""
578 process.on("line", (line) => {
579 result += line + "\n"
580 if (!didContinue) {
581 sendCommandOutput(line)
582 } else {
583 this.say("command_output", line)
584 }
585 })
586
587 // 4. Wait for completion or user feedback
588 let completed = false
589 process.once("completed", () => {
590 completed = true
591 })
592
593 await process
594
595 // 5. Return result
596 if (completed) {
597 return [false, `Command executed.\n${result}`]
598 } else {
599 return [
600 false,
601 `Command is still running in the user's terminal.\n${result}\n\nYou will be updated on the terminal status and new output in the future.`
602 ]
603 }
604 }
605}
606```
607
608Key features:
6091. **Terminal Instance Management**
610 - Multiple terminal support
611 - Terminal state tracking (busy/inactive)
612 - Process cooldown monitoring
613 - Output history per terminal
614
6152. **Command Execution**
616 - Real-time output streaming
617 - User feedback handling
618 - Process state monitoring
619 - Error recovery
620
621### Browser Session Management
622
623The Task class handles browser automation through Puppeteer:
624
625```typescript
626class Task {
627 async executeBrowserAction(action: BrowserAction): Promise<BrowserActionResult> {
628 switch (action) {
629 case "launch":
630 // 1. Launch browser with fixed resolution
631 await this.browserSession.launchBrowser()
632 return await this.browserSession.navigateToUrl(url)
633
634 case "click":
635 // 2. Handle click actions with coordinates
636 return await this.browserSession.click(coordinate)
637
638 case "type":
639 // 3. Handle keyboard input
640 return await this.browserSession.type(text)
641
642 case "close":
643 // 4. Clean up resources
644 return await this.browserSession.closeBrowser()
645 }
646 }
647}
648```
649
650Key aspects:
6511. **Browser Control**
652 - Fixed 900x600 resolution window
653 - Single instance per task lifecycle
654 - Automatic cleanup on task completion
655 - Console log capture
656
6572. **Interaction Handling**
658 - Coordinate-based clicking
659 - Keyboard input simulation
660 - Screenshot capture
661 - Error recovery
662
663## MCP (Model Context Protocol) Integration
664
665### MCP Architecture
666
667The MCP system consists of:
668
6691. **McpHub Class**: Central manager in `src/services/mcp/McpHub.ts`
6702. **MCP Connections**: Manages connections to external MCP servers
6713. **MCP Settings**: Configuration stored in a JSON file
6724. **MCP Marketplace**: Online catalog of available MCP servers
6735. **MCP Tools & Resources**: Capabilities exposed by connected servers
674
675The McpHub class:
676- Manages the lifecycle of MCP server connections
677- Handles server configuration through a settings file
678- Provides methods for calling tools and accessing resources
679- Implements auto-approval settings for MCP tools
680- Monitors server health and handles reconnection
681
682### MCP Server Types
683
684Cline supports two types of MCP server connections:
685- **Stdio**: Command-line based servers that communicate via standard I/O
686- **SSE**: HTTP-based servers that communicate via Server-Sent Events
687
688### MCP Server Management
689
690The McpHub class provides methods for:
691- Discovering and connecting to MCP servers
692- Monitoring server health and status
693- Restarting servers when needed
694- Managing server configurations
695- Setting timeouts and auto-approval rules
696
697### MCP Tool Integration
698
699MCP tools are integrated into the Task execution system:
700- Tools are discovered and registered at connection time
701- The Task class can call MCP tools through the McpHub
702- Tool results are streamed back to the AI
703- Auto-approval settings can be configured per tool
704
705### MCP Marketplace
706
707The MCP Marketplace provides:
708- A catalog of available MCP servers
709- One-click installation
710- README previews
711- Server status monitoring
712
713The Controller class manages MCP servers through the McpHub service:
714
715```typescript
716class Controller {
717 mcpHub?: McpHub
718
719 constructor(context: vscode.ExtensionContext, webviewProvider: WebviewProvider) {
720 this.mcpHub = new McpHub(this)
721 }
722
723 async downloadMcp(mcpId: string) {
724 // Fetch server details from marketplace
725 const response = await axios.post<McpDownloadResponse>(
726 "https://api.cline.bot/v1/mcp/download",
727 { mcpId },
728 {
729 headers: { "Content-Type": "application/json" },
730 timeout: 10000,
731 }
732 )
733
734 // Create task with context from README
735 const task = `Set up the MCP server from ${mcpDetails.githubUrl}...`
736
737 // Initialize task and show chat view
738 await this.initClineWithTask(task)
739 }
740}
741```
742
743## Conclusion
744
745This guide provides a comprehensive overview of the Cline extension architecture, with special focus on state management, data persistence, and code organization. Following these patterns ensures robust feature implementation with proper state handling across the extension's components.
746
747Remember:
748- Always persist important state in the extension
749- The core extension follows a WebviewProvider -> Controller -> Task flow
750- Use proper typing for all state and messages
751- Handle errors and edge cases
752- Test state persistence across webview reloads
753- Follow the established patterns for consistency
754- Place new code in appropriate directories
755- Maintain clear separation of concerns
756- Install dependencies in correct package.json
757
758## Contributing
759
760Contributions to the Cline extension are welcome! Please follow these guidelines:
761
762When adding new tools or API providers, follow the existing patterns in the `src/integrations/` and `src/api/providers/` directories, respectively. Ensure that your code is well-documented and includes appropriate error handling.
763
764The `.clineignore` file allows users to specify files and directories that Cline should not access. When implementing new features, respect the `.clineignore` rules and ensure that your code does not attempt to read or modify ignored files.
765
@@ −1 +1 @@
1−# Debug Harness
1+# Cline Extension Architecture & Development Guide
22
3−HTTP-controlled debugger for the VSCode extension at `src/dev/debug-harness/server.ts`.
3+## Project Overview
44
5−## Quick start
5+Cline is a VSCode extension that provides AI assistance through a combination of a core extension backend and a React-based webview frontend. The extension is built with TypeScript and follows a modular architecture pattern.
66
7−```bash
8−# Build extension first if needed (protos + esbuild):
9−bun run protos && IS_DEV=true bun esbuild.mjs
7+## Architecture Overview
108
11−# Launch (skip-build if already built). Run with node, NOT bun — Playwright's
12−# Electron launch times out under bun:
13−node src/dev/debug-harness/server.ts --skip-build --auto-launch
9+```mermaid
10+graph TB
11+ subgraph VSCodeExtensionHost[VSCode Extension Host]
12+ subgraph CoreExtension[Core Extension]
13+ ExtensionEntry[Extension Entry<br/>src/extension.ts]
14+ WebviewProvider[WebviewProvider<br/>src/core/webview/index.ts]
15+ Controller[Controller<br/>src/core/controller/index.ts]
16+ Task[Task<br/>src/core/task/index.ts]
17+ GlobalState[VSCode Global State]
18+ SecretsStorage[VSCode Secrets Storage]
19+ McpHub[McpHub<br/>src/services/mcp/McpHub.ts]
20+ end
1421
15−# In another terminal:
16−curl localhost:19229/api -d '{"method":"status"}'
22+ subgraph WebviewUI[Webview UI]
23+ WebviewApp[React App<br/>webview-ui/src/App.tsx]
24+ ExtStateContext[ExtensionStateContext<br/>webview-ui/src/context/ExtensionStateContext.tsx]
25+ ReactComponents[React Components]
26+ end
27+
28+ subgraph Storage
29+ TaskStorage[Task Storage<br/>Per-Task Files & History]
30+ CheckpointSystem[Git-based Checkpoints]
31+ end
32+
33+ subgraph apiProviders[API Providers]
34+ AnthropicAPI[Anthropic]
35+ OpenRouterAPI[OpenRouter]
36+ BedrockAPI[AWS Bedrock]
37+ OtherAPIs[Other Providers]
38+ end
39+
40+ subgraph MCPServers[MCP Servers]
41+ ExternalMcpServers[External MCP Servers]
42+ end
43+ end
44+
45+ %% Core Extension Data Flow
46+ ExtensionEntry --> WebviewProvider
47+ WebviewProvider --> Controller
48+ Controller --> Task
49+ Controller --> McpHub
50+ Task --> GlobalState
51+ Task --> SecretsStorage
52+ Task --> TaskStorage
53+ Task --> CheckpointSystem
54+ Task --> |API Requests| apiProviders
55+ McpHub --> |Connects to| ExternalMcpServers
56+ Task --> |Uses| McpHub
57+
58+ %% Webview Data Flow
59+ WebviewApp --> ExtStateContext
60+ ExtStateContext --> ReactComponents
61+
62+ %% Bidirectional Communication
63+ WebviewProvider <-->|postMessage| ExtStateContext
64+
65+ style GlobalState fill:#f9f,stroke:#333,stroke-width:2px
66+ style SecretsStorage fill:#f9f,stroke:#333,stroke-width:2px
67+ style ExtStateContext fill:#bbf,stroke:#333,stroke-width:2px
68+ style WebviewProvider fill:#bfb,stroke:#333,stroke-width:2px
69+ style McpHub fill:#bfb,stroke:#333,stroke-width:2px
70+ style apiProviders fill:#fdb,stroke:#333,stroke-width:2px
1771 ```
1872
19−## Data Isolation
73+## Definitions
2074
21−The debugee runs with `CLINE_DIR=~/.cline2` by default, separate from your real `~/.cline`.
22−This prevents the debugee's logout from logging out the debugger, and vice versa.
23−Override with `--cline-dir /tmp/test-dir`. Check with `status()` → `clineDir`.
75+- **Core Extension**: Anything inside the src folder, organized into modular components
76+- **Core Extension State**: Managed by the Controller class in src/core/controller/index.ts, which serves as the single source of truth for the extension's state. It manages multiple types of persistent storage (global state, workspace state, and secrets), handles state distribution to both the core extension and webview components, and coordinates state across multiple extension instances. This includes managing API configurations, task history, settings, and MCP configurations.
77+- **Webview**: Anything inside the webview-ui. All the react or view's seen by the user and user interaction components
78+- **Webview State**: Managed by ExtensionStateContext in webview-ui/src/context/ExtensionStateContext.tsx, which provides React components with access to the extension's state through a context provider pattern. It maintains local state for UI components, handles real-time updates through message events, manages partial message updates, and provides methods for state modifications. The context includes extension version, messages, task history, theme, API configurations, MCP servers, marketplace catalog, and workspace file paths. It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to state through a custom hook (useExtensionState).
2479
25−## Browser Capture & OAuth
80+### Core Extension Architecture
2681
27−The debugee runs with `CLINE_CAPTURE_BROWSER=1`, which intercepts `openExternal()` in
28−`src/utils/env.ts`. URLs are captured instead of opening a real browser:
82+The core extension follows a clear hierarchical structure:
2983
30−- Logged to `$CLINE_DIR/data/debug-captured-urls.jsonl`
31−- POSTed in real-time to `/captured-url` on the harness server
32−- Queryable via `oauth.captured_urls`
84+1. **WebviewProvider** (src/core/webview/index.ts): Manages the webview lifecycle and communication
85+2. **Controller** (src/core/controller/index.ts): Handles webview messages and task management
86+3. **Task** (src/core/task/index.ts): Executes API requests and tool operations
3387
34−### OAuth API
88+This architecture provides clear separation of concerns:
89+- WebviewProvider focuses on VSCode webview integration
90+- Controller manages state and coordinates tasks
91+- Task handles the execution of AI requests and tool operations
3592
36−- **`oauth.captured_urls`** `{clear?}` — URLs the debugee tried to open
37−- **`oauth.read_stored_token`** — Check auth token presence in secrets.json
38−- **`oauth.simulate_callback`** `{path, code?, state?, provider?, token?}` — Build vscode:// callback URI
39−- **`oauth.read_captured_urls_file`** — Read on-disk JSONL of captured URLs
93+### WebviewProvider Implementation
4094
41−### OAuth testing flow
95+The WebviewProvider class in `src/core/webview/index.ts` is responsible for:
4296
43−For **Cline OAuth** (SDK local callback): The SDK starts a local HTTP server, the auth URL
44−is captured. To complete: open the captured URL in a real browser (it redirects back to the
45−SDK's callback server), OR extract the callback port and `curl http://127.0.0.1:PORT/callback?code=...`.
97+- Managing multiple active instances through a static set (`activeInstances`)
98+- Handling webview lifecycle events (creation, visibility changes, disposal)
99+- Implementing HTML content generation with proper CSP headers
100+- Supporting Hot Module Replacement (HMR) for development
101+- Setting up message listeners between the webview and extension
46102
47−For **MCP/Provider OAuth** (vscode:// URI): The redirect goes to a vscode:// URI.
48−`oauth.simulate_callback` only *builds* the URI — it does not deliver it, and the ESM
49−extension host can't `require()` the handler. To actually deliver the callback, call the
50−debug-only hook via `ext.evaluate` (with `awaitPromise: true`):
51−`globalThis.__clineHandleUri("vscode://saoudrizwan.claude-dev/...?code=...&state=...")`.
52−It runs the same `SharedUriHandler.handleUri` as VSCode's real URI handler and exists only
53−when `CLINE_CAPTURE_BROWSER` is set (the harness always sets it; never ships in prod).
54−For end-to-end MCP OAuth, get a real `code` from the local MCP OAuth test server
55−(`bun run dev:mcp-oauth-test-server`).
103+The WebviewProvider maintains a reference to the Controller and delegates message handling to it. It also handles the creation of both sidebar and tab panel webviews, allowing Cline to be used in different contexts within VSCode.
56104
57−## Navigating Views — Use Commands, Not Clicks
105+### Core Extension State
58106
59−Don't try to find/click small sidebar icons. Use VSCode commands via command palette.
60−Registered in `src/registry.ts`:
107+The `Controller` class manages multiple types of persistent storage:
61108
62−| Command | View |
63−|---------|------|
64−| `cline.accountButtonClicked` | Account / sign-in |
65−| `cline.historyButtonClicked` | Task history |
66−| `cline.settingsButtonClicked` | Settings |
67−| `cline.mcpButtonClicked` | MCP servers |
68−| `cline.plusButtonClicked` | New task (chat) |
69−| `cline.worktreesButtonClicked` | Worktrees |
109+- **Global State:** Stored across all VSCode instances. Used for settings and data that should persist globally.
110+- **Workspace State:** Specific to the current workspace. Used for task-specific data and settings.
111+- **Secrets:** Secure storage for sensitive information like API keys.
70112
71−```bash
72−curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
113+The `Controller` handles the distribution of state to both the core extension and webview components. It also coordinates state across multiple extension instances, ensuring consistency.
114+
115+State synchronization between instances is handled through:
116+- File-based storage for task history and conversation data
117+- VSCode's global state API for settings and configuration
118+- Secrets storage for sensitive information
119+- Event listeners for file changes and configuration updates
120+
121+The Controller implements methods for:
122+- Saving and loading task state
123+- Managing API configurations
124+- Handling user authentication
125+- Coordinating MCP server connections
126+- Managing task history and checkpoints
127+
128+### Webview State
129+
130+The `ExtensionStateContext` in `webview-ui/src/context/ExtensionStateContext.tsx` provides React components with access to the extension's state. It uses a context provider pattern and maintains local state for UI components. The context includes:
131+
132+- Extension version
133+- Messages
134+- Task history
135+- Theme
136+- API configurations
137+- MCP servers
138+- Marketplace catalog
139+- Workspace file paths
140+
141+It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to the state via a custom hook (`useExtensionState`).
142+
143+The ExtensionStateContext handles:
144+- Real-time updates through message events
145+- Partial message updates for streaming content
146+- State modifications through setter methods
147+- Type-safe access to state through a custom hook
148+
149+## API Provider System
150+
151+Cline supports multiple AI providers through a modular API provider system. Each provider is implemented as a separate module in the `src/api/providers/` directory and follows a common interface.
152+
153+### API Provider Architecture
154+
155+The API system consists of:
156+
157+1. **API Handlers**: Provider-specific implementations in `src/api/providers/`
158+2. **API Transformers**: Stream transformation utilities in `src/api/transform/`
159+3. **API Configuration**: User settings for API keys and endpoints
160+4. **API Factory**: Builder function to create the appropriate handler
161+
162+Key providers include:
163+- **Anthropic**: Direct integration with Claude models
164+- **OpenRouter**: Meta-provider supporting multiple model providers
165+- **AWS Bedrock**: Integration with Amazon's AI services
166+- **Gemini**: Google's AI models
167+- **Cerebras**: High-performance inference with Llama, Qwen, and DeepSeek models
168+- **Ollama**: Local model hosting
169+- **LM Studio**: Local model hosting
170+- **VSCode LM**: VSCode's built-in language models
171+
172+### API Configuration Management
173+
174+API configurations are stored securely:
175+- API keys are stored in VSCode's secrets storage
176+- Model selections and non-sensitive settings are stored in global state
177+- The Controller manages switching between providers and updating configurations
178+
179+The system supports:
180+- Secure storage of API keys
181+- Model selection and configuration
182+- Automatic retry and error handling
183+- Token usage tracking and cost calculation
184+- Context window management
185+
186+### Plan/Act Mode API Configuration
187+
188+Cline supports separate model configurations for Plan and Act modes:
189+- Different models can be used for planning vs. execution
190+- The system preserves model selections when switching modes
191+- The Controller handles the transition between modes and updates the API configuration accordingly
192+
193+## Task Execution System
194+
195+The Task class is responsible for executing AI requests and tool operations. Each task runs in its own instance of the Task class, ensuring isolation and proper state management.
196+
197+### Task Execution Loop
198+
199+The core task execution loop follows this pattern:
200+
201+```typescript
202+class Task {
203+ async initiateTaskLoop(userContent: UserContent, isNewTask: boolean) {
204+ while (!this.abort) {
205+ // 1. Make API request and stream response
206+ const stream = this.attemptApiRequest()
207+
208+ // 2. Parse and present content blocks
209+ for await (const chunk of stream) {
210+ switch (chunk.type) {
211+ case "text":
212+ // Parse into content blocks
213+ this.assistantMessageContent = parseAssistantMessageV2(chunk.text)
214+ // Present blocks to user
215+ await this.presentAssistantMessage()
216+ break
217+ }
218+ }
219+
220+ // 3. Wait for tool execution to complete
221+ await pWaitFor(() => this.userMessageContentReady)
222+
223+ // 4. Continue loop with tool result
224+ const recDidEndLoop = await this.recursivelyMakeClineRequests(
225+ this.userMessageContent
226+ )
227+ }
228+ }
229+}
73230 ```
74231
75−## Key commands
232+### Message Streaming System
76233
77−All via `POST localhost:19229/api` with `{"method":"...", "params":{...}}`:
234+The streaming system handles real-time updates and partial content:
78235
79−- **`launch`** / **`shutdown`** — lifecycle
80−- **`ui.screenshot`** — screenshot to `/tmp/cline-debug/`; returns `{path}` — **use `read_file` on the path to examine, do NOT `open` the file** (Preview.app covers the VSCode window)
81−- **`ui.open_sidebar`** — open the Cline sidebar
82−- **`ext.set_breakpoint`** `{file, line, condition?}` — breakpoint by source file (sourcemap-resolved)
83−- **`ext.evaluate`** `{expression, callFrameId?}` — eval in extension host
84−- **`ext.resume`** / **`ext.step_over`** / **`ext.step_into`** — stepping
85−- **`ext.call_stack`** — inspect when paused
86−- **`web.evaluate`** `{expression}` — eval in webview
87−- **`web.post_message`** `{message}` — send postMessage to extension host via exposed vsCodeApi
88−- **`wait_for_pause`** `{timeout?}` — block until breakpoint hit
89−- **`ui.locator`** `{role?, testId?, text?, frame?}` — Playwright locator (auto-retries on stale sidebar frame)
90−- **`ui.react_input`** `{text, selector?, clear?, submit?}` — set React textarea value via `execCommand('insertText')`; works reliably across multiple tasks
91−- **`ui.send_message`** `{text, images?, files?, responseType?}` — send chat message bypassing the textarea entirely (via gRPC postMessage)
92−- **`ui.command_palette`** `{command}` — run VSCode command
236+```typescript
237+class Task {
238+ async presentAssistantMessage() {
239+ // Handle streaming locks to prevent race conditions
240+ if (this.presentAssistantMessageLocked) {
241+ this.presentAssistantMessageHasPendingUpdates = true
242+ return
243+ }
244+ this.presentAssistantMessageLocked = true
93245
94−## Typical Session
246+ // Present current content block
247+ const block = this.assistantMessageContent[this.currentStreamingContentIndex]
248+
249+ // Handle different types of content
250+ switch (block.type) {
251+ case "text":
252+ await this.say("text", content, undefined, block.partial)
253+ break
254+ case "tool_use":
255+ // Handle tool execution
256+ break
257+ }
95258
96−```bash
97−# 1. Launch
98−curl localhost:19229/api -d '{"method":"launch","params":{"skipBuild":true}}'
259+ // Move to next block if complete
260+ if (!block.partial) {
261+ this.currentStreamingContentIndex++
262+ }
263+ }
264+}
265+```
99266
100−# 2. Open sidebar + dismiss overlays (ALWAYS do this first)
101−curl localhost:19229/api -d '{"method":"ui.open_sidebar"}'
102−curl localhost:19229/api -d '{"method":"web.evaluate","params":{"expression":"document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
267+### Tool Execution Flow
103268
104−# 3. Navigate to view
105−curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
269+Tools follow a strict execution pattern:
106270
107−# 4. Check captured OAuth URLs if testing auth
108−curl localhost:19229/api -d '{"method":"oauth.captured_urls"}'
271+```typescript
272+class Task {
273+ async executeToolWithApproval(block: ToolBlock) {
274+ // 1. Check auto-approval settings
275+ if (this.shouldAutoApproveTool(block.name)) {
276+ await this.say("tool", message)
277+ this.consecutiveAutoApprovedRequestsCount++
278+ } else {
279+ // 2. Request user approval
280+ const didApprove = await askApproval("tool", message)
281+ if (!didApprove) {
282+ this.didRejectTool = true
283+ return
284+ }
285+ }
109286
110−# 5. Verify
111−curl localhost:19229/api -d '{"method":"ui.screenshot"}'
287+ // 3. Execute tool
288+ const result = await this.executeTool(block)
289+
290+ // 4. Save checkpoint
291+ await this.saveCheckpoint()
292+
293+ // 5. Return result to API
294+ return result
295+ }
296+}
112297 ```
113298
114−## Caveats
299+### Error Handling & Recovery
115300
116−- **⚠️ Dismiss promotional overlays FIRST**: On fresh launches, full-screen promo overlays block the sidebar. **Dismiss immediately after `ui.open_sidebar`**, before any other interaction or screenshot. May need to run twice:
117− ```bash
118− curl localhost:19229/api -d '{"method": "ui.open_sidebar"}'
119− curl localhost:19229/api -d '{"method": "web.evaluate", "params": {"expression": "document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
120− ```
121−- **Screenshots — don't open the file**: `ui.screenshot` and `ui.sidebar_screenshot` save PNGs to `/tmp/cline-debug/` and return the `{path}`. Use `read_file` on that path to examine screenshots. Running `open <path>` launches Preview.app on macOS which covers the VSCode window.
122−- **Scripts count = 0 after launch**: CDP connects after extension host starts, so scripts parsed during startup aren't tracked. Breakpoints still work via sourcemap resolution.
123−- **Port 9230**: Extension host inspector. If another VSCode instance uses this port, the harness will fail to connect. Kill other debug instances first.
124−- **macOS only** for now (Playwright Electron launch behavior).
125−- **Webview CDP**: `connect_webview` may fail depending on Electron version. `web.evaluate` still works via Playwright's `frame.evaluate()` fallback.
126−- **Sourcemap paths**: esbuild outputs relative paths like `../src/extension.ts` in the sourcemap. The resolver handles this, but if a file isn't found, use `ext.source_files` to see exact paths.
127−- **OAuth with fake codes**: Browser capture intercepts the URL but doesn't provide a valid auth code. For real OAuth testing, open the captured URL in a browser. For unit testing, mock the token exchange.
301+The system includes robust error handling:
128302
129−See `src/dev/debug-harness/README.md` for full API reference.
303+```typescript
304+class Task {
305+ async handleError(action: string, error: Error) {
306+ // 1. Check if task was abandoned
307+ if (this.abandoned) return
308+
309+ // 2. Format error message
310+ const errorString = `Error ${action}: ${error.message}`
311+
312+ // 3. Present error to user
313+ await this.say("error", errorString)
314+
315+ // 4. Add error to tool results
316+ pushToolResult(formatResponse.toolError(errorString))
317+
318+ // 5. Cleanup resources
319+ await this.diffViewProvider.revertChanges()
320+ await this.browserSession.closeBrowser()
321+ }
322+}
323+```
324+
325+### API Request & Token Management
326+
327+The Task class handles API requests with built-in retry, streaming, and token management:
328+
329+```typescript
330+class Task {
331+ async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
332+ // 1. Wait for MCP servers to connect
333+ await pWaitFor(() => this.controllerRef.deref()?.mcpHub?.isConnecting !== true)
334+
335+ // 2. Manage context window
336+ const previousRequest = this.clineMessages[previousApiReqIndex]
337+ if (previousRequest?.text) {
338+ const { tokensIn, tokensOut } = JSON.parse(previousRequest.text || "{}")
339+ const totalTokens = (tokensIn || 0) + (tokensOut || 0)
340+
341+ // Truncate conversation if approaching context limit
342+ if (totalTokens >= maxAllowedSize) {
343+ this.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
344+ this.apiConversationHistory,
345+ this.conversationHistoryDeletedRange,
346+ totalTokens / 2 > maxAllowedSize ? "quarter" : "half"
347+ )
348+ }
349+ }
350+
351+ // 3. Handle streaming with automatic retry
352+ try {
353+ this.isWaitingForFirstChunk = true
354+ const firstChunk = await iterator.next()
355+ yield firstChunk.value
356+ this.isWaitingForFirstChunk = false
357+
358+ // Stream remaining chunks
359+ yield* iterator
360+ } catch (error) {
361+ // 4. Error handling with retry
362+ if (isOpenRouter && !this.didAutomaticallyRetryFailedApiRequest) {
363+ await setTimeoutPromise(1000)
364+ this.didAutomaticallyRetryFailedApiRequest = true
365+ yield* this.attemptApiRequest(previousApiReqIndex)
366+ return
367+ }
368+
369+ // 5. Ask user to retry if automatic retry failed
370+ const { response } = await this.ask(
371+ "api_req_failed",
372+ this.formatErrorWithStatusCode(error)
373+ )
374+ if (response === "yesButtonClicked") {
375+ await this.say("api_req_retried")
376+ yield* this.attemptApiRequest(previousApiReqIndex)
377+ return
378+ }
379+ }
380+ }
381+}
382+```
383+
384+Key features:
385+
386+1. **Context Window Management**
387+ - Tracks token usage across requests
388+ - Automatically truncates conversation when needed
389+ - Preserves important context while freeing space
390+ - Handles different model context sizes
391+
392+2. **Streaming Architecture**
393+ - Real-time chunk processing
394+ - Partial content handling
395+ - Race condition prevention
396+ - Error recovery during streaming
397+
398+3. **Error Handling**
399+ - Automatic retry for transient failures
400+ - User-prompted retry for persistent issues
401+ - Detailed error reporting
402+ - State cleanup on failure
403+
404+4. **Token Tracking**
405+ - Per-request token counting
406+ - Cumulative usage tracking
407+ - Cost calculation
408+ - Cache hit monitoring
409+
410+### Context Management System
411+
412+The Context Management System handles conversation history truncation to prevent context window overflow errors. Implemented in the `ContextManager` class, it ensures long-running conversations remain within model context limits while preserving critical context.
413+
414+Key features:
415+
416+1. **Model-Aware Sizing**: Dynamically adjusts based on different model context windows (64K for DeepSeek, 128K for most models, 200K for Claude).
417+
418+2. **Proactive Truncation**: Monitors token usage and preemptively truncates conversations when approaching limits, maintaining buffers of 27K-40K tokens depending on the model.
419+
420+3. **Intelligent Preservation**: Always preserves the original task message and maintains the user-assistant conversation structure when truncating.
421+
422+4. **Adaptive Strategies**: Uses different truncation strategies based on context pressure - removing half of the conversation for moderate pressure or three-quarters for severe pressure.
423+
424+5. **Error Recovery**: Includes specialized detection for context window errors from different providers with automatic retry and more aggressive truncation when needed.
425+
426+### Task State & Resumption
427+
428+The Task class provides robust task state management and resumption capabilities:
429+
430+```typescript
431+class Task {
432+ async resumeTaskFromHistory() {
433+ // 1. Load saved state
434+ this.clineMessages = await getSavedClineMessages(this.getContext(), this.taskId)
435+ this.apiConversationHistory = await getSavedApiConversationHistory(this.getContext(), this.taskId)
436+
437+ // 2. Handle interrupted tool executions
438+ const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
439+ if (lastMessage.role === "assistant") {
440+ const toolUseBlocks = content.filter(block => block.type === "tool_use")
441+ if (toolUseBlocks.length > 0) {
442+ // Add interrupted tool responses
443+ const toolResponses = toolUseBlocks.map(block => ({
444+ type: "tool_result",
445+ tool_use_id: block.id,
446+ content: "Task was interrupted before this tool call could be completed."
447+ }))
448+ modifiedOldUserContent = [...toolResponses]
449+ }
450+ }
451+
452+ // 3. Notify about interruption
453+ const agoText = this.getTimeAgoText(lastMessage?.ts)
454+ newUserContent.push({
455+ type: "text",
456+ text: `[TASK RESUMPTION] This task was interrupted ${agoText}. It may or may not be complete, so please reassess the task context.`
457+ })
458+
459+ // 4. Resume task execution
460+ await this.initiateTaskLoop(newUserContent, false)
461+ }
462+
463+ private async saveTaskState() {
464+ // Save conversation history
465+ await saveApiConversationHistory(this.getContext(), this.taskId, this.apiConversationHistory)
466+ await saveClineMessages(this.getContext(), this.taskId, this.clineMessages)
467+
468+ // Create checkpoint
469+ const commitHash = await this.checkpointTracker?.commit()
470+
471+ // Update task history
472+ await this.controllerRef.deref()?.updateTaskHistory({
473+ id: this.taskId,
474+ ts: lastMessage.ts,
475+ task: taskMessage.text,
476+ // ... other metadata
477+ })
478+ }
479+}
480+```
481+
482+Key aspects of task state management:
483+
484+1. **Task Persistence**
485+ - Each task has a unique ID and dedicated storage directory
486+ - Conversation history is saved after each message
487+ - File changes are tracked through Git-based checkpoints
488+ - Terminal output and browser state are preserved
489+
490+2. **State Recovery**
491+ - Tasks can be resumed from any point
492+ - Interrupted tool executions are handled gracefully
493+ - File changes can be restored from checkpoints
494+ - Context is preserved across VSCode sessions
495+
496+3. **Workspace Synchronization**
497+ - File changes are tracked through Git
498+ - Checkpoints are created after tool executions
499+ - State can be restored to any checkpoint
500+ - Changes can be compared between checkpoints
501+
502+4. **Error Recovery**
503+ - Failed API requests can be retried
504+ - Interrupted tool executions are marked
505+ - Resources are cleaned up properly
506+ - User is notified of state changes
507+
508+## Plan/Act Mode System
509+
510+Cline implements a dual-mode system that separates planning from execution:
511+
512+### Mode Architecture
513+
514+The Plan/Act mode system consists of:
515+
516+1. **Mode State**: Stored in `chatSettings.mode` in the Controller's state
517+2. **Mode Switching**: Handled by `togglePlanActModeWithChatSettings` in the Controller
518+3. **Mode-specific Models**: Optional configuration to use different models for each mode
519+4. **Mode-specific Prompting**: Different system prompts for planning vs. execution
520+
521+### Mode Switching Process
522+
523+When switching between modes:
524+
525+1. The current model configuration is saved to mode-specific state
526+2. The previous mode's model configuration is restored
527+3. The Task instance is updated with the new mode
528+4. The webview is notified of the mode change
529+5. Telemetry events are captured for analytics
530+
531+### Plan Mode
532+
533+Plan mode is designed for:
534+- Information gathering and context building
535+- Asking clarifying questions
536+- Creating detailed execution plans
537+- Discussing approaches with the user
538+
539+In Plan mode, the AI uses the `plan_mode_respond` tool to engage in conversational planning without executing actions.
540+
541+### Act Mode
542+
543+Act mode is designed for:
544+- Executing the planned actions
545+- Using tools to modify files, run commands, etc.
546+- Implementing the solution
547+- Providing results and completion feedback
548+
549+In Act mode, the AI has access to all tools except `plan_mode_respond` and focuses on implementation rather than discussion.
550+
551+## Data Flow & State Management
552+
553+### Core Extension Role
554+
555+The Controller acts as the single source of truth for all persistent state. It:
556+- Manages VSCode global state and secrets storage
557+- Coordinates state updates between components
558+- Ensures state consistency across webview reloads
559+- Handles task-specific state persistence
560+- Manages checkpoint creation and restoration
561+
562+### Terminal Management
563+
564+The Task class manages terminal instances and command execution:
565+
566+```typescript
567+class Task {
568+ async executeCommandTool(command: string): Promise<[boolean, ToolResponse]> {
569+ // 1. Get or create terminal
570+ const terminalInfo = await this.terminalManager.getOrCreateTerminal(cwd)
571+ terminalInfo.terminal.show()
572+
573+ // 2. Execute command with output streaming
574+ const process = this.terminalManager.runCommand(terminalInfo, command)
575+
576+ // 3. Handle real-time output
577+ let result = ""
578+ process.on("line", (line) => {
579+ result += line + "\n"
580+ if (!didContinue) {
581+ sendCommandOutput(line)
582+ } else {
583+ this.say("command_output", line)
584+ }
585+ })
586+
587+ // 4. Wait for completion or user feedback
588+ let completed = false
589+ process.once("completed", () => {
590+ completed = true
591+ })
592+
593+ await process
594+
595+ // 5. Return result
596+ if (completed) {
597+ return [false, `Command executed.\n${result}`]
598+ } else {
599+ return [
600+ false,
601+ `Command is still running in the user's terminal.\n${result}\n\nYou will be updated on the terminal status and new output in the future.`
602+ ]
603+ }
604+ }
605+}
606+```
607+
608+Key features:
609+1. **Terminal Instance Management**
610+ - Multiple terminal support
611+ - Terminal state tracking (busy/inactive)
612+ - Process cooldown monitoring
613+ - Output history per terminal
614+
615+2. **Command Execution**
616+ - Real-time output streaming
617+ - User feedback handling
618+ - Process state monitoring
619+ - Error recovery
620+
621+### Browser Session Management
622+
623+The Task class handles browser automation through Puppeteer:
624+
625+```typescript
626+class Task {
627+ async executeBrowserAction(action: BrowserAction): Promise<BrowserActionResult> {
628+ switch (action) {
629+ case "launch":
630+ // 1. Launch browser with fixed resolution
631+ await this.browserSession.launchBrowser()
632+ return await this.browserSession.navigateToUrl(url)
633+
634+ case "click":
635+ // 2. Handle click actions with coordinates
636+ return await this.browserSession.click(coordinate)
637+
638+ case "type":
639+ // 3. Handle keyboard input
640+ return await this.browserSession.type(text)
641+
642+ case "close":
643+ // 4. Clean up resources
644+ return await this.browserSession.closeBrowser()
645+ }
646+ }
647+}
648+```
649+
650+Key aspects:
651+1. **Browser Control**
652+ - Fixed 900x600 resolution window
653+ - Single instance per task lifecycle
654+ - Automatic cleanup on task completion
655+ - Console log capture
656+
657+2. **Interaction Handling**
658+ - Coordinate-based clicking
659+ - Keyboard input simulation
660+ - Screenshot capture
661+ - Error recovery
662+
663+## MCP (Model Context Protocol) Integration
664+
665+### MCP Architecture
666+
667+The MCP system consists of:
668+
669+1. **McpHub Class**: Central manager in `src/services/mcp/McpHub.ts`
670+2. **MCP Connections**: Manages connections to external MCP servers
671+3. **MCP Settings**: Configuration stored in a JSON file
672+4. **MCP Marketplace**: Online catalog of available MCP servers
673+5. **MCP Tools & Resources**: Capabilities exposed by connected servers
674+
675+The McpHub class:
676+- Manages the lifecycle of MCP server connections
677+- Handles server configuration through a settings file
678+- Provides methods for calling tools and accessing resources
679+- Implements auto-approval settings for MCP tools
680+- Monitors server health and handles reconnection
681+
682+### MCP Server Types
683+
684+Cline supports two types of MCP server connections:
685+- **Stdio**: Command-line based servers that communicate via standard I/O
686+- **SSE**: HTTP-based servers that communicate via Server-Sent Events
687+
688+### MCP Server Management
689+
690+The McpHub class provides methods for:
691+- Discovering and connecting to MCP servers
692+- Monitoring server health and status
693+- Restarting servers when needed
694+- Managing server configurations
695+- Setting timeouts and auto-approval rules
696+
697+### MCP Tool Integration
698+
699+MCP tools are integrated into the Task execution system:
700+- Tools are discovered and registered at connection time
701+- The Task class can call MCP tools through the McpHub
702+- Tool results are streamed back to the AI
703+- Auto-approval settings can be configured per tool
704+
705+### MCP Marketplace
706+
707+The MCP Marketplace provides:
708+- A catalog of available MCP servers
709+- One-click installation
710+- README previews
711+- Server status monitoring
712+
713+The Controller class manages MCP servers through the McpHub service:
714+
715+```typescript
716+class Controller {
717+ mcpHub?: McpHub
718+
719+ constructor(context: vscode.ExtensionContext, webviewProvider: WebviewProvider) {
720+ this.mcpHub = new McpHub(this)
721+ }
722+
723+ async downloadMcp(mcpId: string) {
724+ // Fetch server details from marketplace
725+ const response = await axios.post<McpDownloadResponse>(
726+ "https://api.cline.bot/v1/mcp/download",
727+ { mcpId },
728+ {
729+ headers: { "Content-Type": "application/json" },
730+ timeout: 10000,
731+ }
732+ )
733+
734+ // Create task with context from README
735+ const task = `Set up the MCP server from ${mcpDetails.githubUrl}...`
736+
737+ // Initialize task and show chat view
738+ await this.initClineWithTask(task)
739+ }
740+}
741+```
742+
743+## Conclusion
744+
745+This guide provides a comprehensive overview of the Cline extension architecture, with special focus on state management, data persistence, and code organization. Following these patterns ensures robust feature implementation with proper state handling across the extension's components.
746+
747+Remember:
748+- Always persist important state in the extension
749+- The core extension follows a WebviewProvider -> Controller -> Task flow
750+- Use proper typing for all state and messages
751+- Handle errors and edge cases
752+- Test state persistence across webview reloads
753+- Follow the established patterns for consistency
754+- Place new code in appropriate directories
755+- Maintain clear separation of concerns
756+- Install dependencies in correct package.json
757+
758+## Contributing
759+
760+Contributions to the Cline extension are welcome! Please follow these guidelines:
761+
762+When adding new tools or API providers, follow the existing patterns in the `src/integrations/` and `src/api/providers/` directories, respectively. Ensure that your code is well-documented and includes appropriate error handling.
763+
764+The `.clineignore` file allows users to specify files and directories that Cline should not access. When implementing new features, respect the `.clineignore` rules and ensure that your code does not attempt to read or modify ignored files.
130765
