Compare commits

..

4 Commits

Author SHA1 Message Date
celestial-vault a07554f191 rework the docker:shell script to reuse an existing container 2025-11-14 21:39:59 -08:00
celestial-vault 474c655240 update script documentation for next steps after docker build 2025-11-14 11:11:25 -08:00
celestial-vault b5157a2376 code comment 2025-11-14 11:02:53 -08:00
celestial-vault b14db72140 add docker setup for cli development 2025-11-13 21:31:54 -08:00
829 changed files with 22697 additions and 76425 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Wiring-up "conditionals" for Cline Rules files.
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Updated switch component to adhere to 3:1 contrast accessibility standard for both light and dark vscode themes
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Remove hooks feature setting and make it always enabled (except on Windows).
-1
View File
@@ -1 +0,0 @@
../../.clinerules/workflows/hotfix-release.md
-1
View File
@@ -1 +0,0 @@
../../.clinerules/workflows/release.md
@@ -1,51 +0,0 @@
#!/bin/bash
set -euo pipefail
# Only run in Claude Code remote environments
if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ]; then
exit 0
fi
cd "$CLAUDE_PROJECT_DIR"
echo "=== Claude Code for Web Setup ==="
echo ""
# Install latest gh CLI tool
echo "Installing GitHub CLI..."
GH_VERSION=$(curl -s https://api.github.com/repos/cli/cli/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/^v//')
curl -sL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz" -o /tmp/gh.tar.gz
tar -xzf /tmp/gh.tar.gz -C /tmp
sudo mv "/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh" /usr/local/bin/gh
rm -rf /tmp/gh.tar.gz /tmp/gh_${GH_VERSION}_linux_amd64
echo "Installed gh version: $(gh --version | head -1)"
echo ""
# Check if GITHUB_TOKEN is set and configure gh
if [ -n "${GITHUB_TOKEN:-}" ]; then
echo "GITHUB_TOKEN is configured - gh CLI is ready to use"
echo ""
echo "You can use gh commands directly, for example:"
echo " gh issue list --repo cline/cline --limit 5"
echo " gh pr list --repo cline/cline --state open"
echo " gh issue view 123 --repo cline/cline"
echo ""
else
echo "GITHUB_TOKEN is not set - gh CLI will have limited functionality"
echo ""
echo "To enable full GitHub API access:"
echo "1. Create a Fine-grained Personal Access Token at https://github.com/settings/tokens?type=beta"
echo "2. Add it as GITHUB_TOKEN in your Claude Code environment settings"
echo ""
fi
# Install project dependencies
echo "Installing dependencies..."
npm run install:all
# Generate gRPC/protobuf types (required for TypeScript)
echo "Generating proto types..."
npm run protos
echo ""
echo "Session setup complete!"
-14
View File
@@ -1,14 +0,0 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/claude-code-for-web-setup.sh"
}
]
}
]
}
}
-196
View File
@@ -1,196 +0,0 @@
---
name: create-pull-request
description: Create a GitHub pull request following project conventions. Use when the user asks to create a PR, submit changes for review, or open a pull request. Handles commit analysis, branch management, and PR creation using the gh CLI tool.
---
# Create Pull Request
This skill guides you through creating a well-structured GitHub pull request that follows project conventions and best practices.
## Prerequisites Check
Before proceeding, verify the following:
### 1. Check if `gh` CLI is installed
```bash
gh --version
```
If not installed, inform the user:
> The GitHub CLI (`gh`) is required but not installed. Please install it:
> - macOS: `brew install gh`
> - Other: https://cli.github.com/
### 2. Check if authenticated with GitHub
```bash
gh auth status
```
If not authenticated, guide the user to run `gh auth login`.
### 3. Verify clean working directory
```bash
git status
```
If there are uncommitted changes, ask the user whether to:
- Commit them as part of this PR
- Stash them temporarily
- Discard them (with caution)
## Gather Context
### 1. Identify the current branch
```bash
git branch --show-current
```
Ensure you're not on `main` or `master`. If so, ask the user to create or switch to a feature branch.
### 2. Find the base branch
```bash
git remote show origin | grep "HEAD branch"
```
This is typically `main` or `master`.
### 3. Analyze recent commits relevant to this PR
```bash
git log origin/main..HEAD --oneline --no-decorate
```
Review these commits to understand:
- What changes are being introduced
- The scope of the PR (single feature/fix or multiple changes)
- Whether commits should be squashed or reorganized
### 4. Review the diff
```bash
git diff origin/main..HEAD --stat
```
This shows which files changed and helps identify the type of change.
## Information Gathering
Before creating the PR, you need the following information. Check if it can be inferred from:
- Commit messages
- Branch name (e.g., `fix/issue-123`, `feature/new-login`)
- Changed files and their content
If any critical information is missing, use `ask_followup_question` to ask the user:
### Required Information
1. **Related Issue Number**: Look for patterns like `#123`, `fixes #123`, or `closes #123` in commit messages
2. **Description**: What problem does this solve? Why were these changes made?
3. **Type of Change**: Bug fix, new feature, breaking change, refactor, cosmetic, documentation, or workflow
4. **Test Procedure**: How was this tested? What could break?
### Example clarifying question
If the issue number is not found:
> I couldn't find a related issue number in the commit messages or branch name. What GitHub issue does this PR address? (Enter the issue number, e.g., "123" or "N/A" for small fixes)
## Git Best Practices
Before creating the PR, consider these best practices:
### Commit Hygiene
1. **Atomic commits**: Each commit should represent a single logical change
2. **Clear commit messages**: Follow conventional commit format when possible
3. **No merge commits**: Prefer rebasing over merging to keep history clean
### Branch Management
1. **Rebase on latest main** (if needed):
```bash
git fetch origin
git rebase origin/main
```
2. **Squash if appropriate**: If there are many small "WIP" commits, consider interactive rebase:
```bash
git rebase -i origin/main
```
Only suggest this if commits appear messy and the user is comfortable with rebasing.
### Push Changes
Ensure all commits are pushed:
```bash
git push origin HEAD
```
If the branch was rebased, you may need:
```bash
git push origin HEAD --force-with-lease
```
## Create the Pull Request
**IMPORTANT**: Read and use the PR template at `.github/pull_request_template.md`. The PR body format must **strictly match** the template structure. Do not deviate from the template format.
When filling out the template:
- Replace `#XXXX` with the actual issue number, or keep as `#XXXX` if no issue exists (for small fixes)
- Fill in all sections with relevant information gathered from commits and context
- Mark the appropriate "Type of Change" checkbox(es)
- Complete the "Pre-flight Checklist" items that apply
### Create PR with gh CLI
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main
```
Alternatively, create as draft if the user wants review before marking ready:
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main --draft
```
## Post-Creation
After creating the PR:
1. **Display the PR URL** so the user can review it
2. **Remind about CI checks**: Tests and linting will run automatically
3. **Suggest next steps**:
- Add reviewers if needed: `gh pr edit --add-reviewer USERNAME`
- Add labels if needed: `gh pr edit --add-label "bug"`
## Error Handling
### Common Issues
1. **No commits ahead of main**: The branch has no changes to submit
- Ask if the user meant to work on a different branch
2. **Branch not pushed**: Remote doesn't have the branch
- Push the branch first: `git push -u origin HEAD`
3. **PR already exists**: A PR for this branch already exists
- Show the existing PR: `gh pr view`
- Ask if they want to update it instead
4. **Merge conflicts**: Branch conflicts with base
- Guide user through resolving conflicts or rebasing
## Summary Checklist
Before finalizing, ensure:
- [ ] `gh` CLI is installed and authenticated
- [ ] Working directory is clean
- [ ] All commits are pushed
- [ ] Branch is up-to-date with base branch
- [ ] Related issue number is identified, or placeholder is used
- [ ] PR description follows the template exactly
- [ ] Appropriate type of change is selected
- [ ] Pre-flight checklist items are addressed
-194
View File
@@ -1,194 +0,0 @@
This file is the secret sauce for working effectively in this codebase. It captures tribal knowledge—the nuanced, non-obvious patterns that make the difference between a quick fix and hours of back-and-forth & human intervention.
**When to add to this file:**
- User had to intervene, correct, or hand-hold
- Multiple back-and-forth attempts were needed to get something working
- You discovered something that required reading many files to understand
- A change touched files you wouldn't have guessed
- Something worked differently than you expected
- User explicitly asks to "add this to CLAUDE.md"
**Proactively suggest additions** when any of the above happen—don't wait to be asked.
**What NOT to add:** Stuff you can figure out from reading a few files, obvious patterns, or standard practices. This file should be high-signal, not comprehensive.
## Miscellaneous
- This is a VS Code extension—check `package.json` for available scripts before trying to verify builds (e.g., `npm run compile`, not `npm run build`).
- When creating PRs, if the change is user-facing and significant enough to warrant a changelog entry, run `npm run changeset` and create a patch changeset. Never create minor or major version bumps. Skip changesets for trivial fixes, internal refactors, or minor UI tweaks that users wouldn't notice.
- When adding new feature flags, see this PR as a reference https://github.com/cline/cline/pull/7566
- Additional instructions about making requests: @.clinerules/network.md
## gRPC/Protobuf Communication
The extension and webview communicate via gRPC-like protocol over VS Code message passing.
**Proto files live in `proto/`** (e.g., `proto/cline/task.proto`, `proto/cline/ui.proto`)
- Each feature domain has its own `.proto` file
- For simple data, use shared types in `proto/cline/common.proto` (`StringRequest`, `Empty`, `Int64Request`)
- For complex data, define custom messages in the feature's `.proto` file
- Naming: Services `PascalCaseService`, RPCs `camelCase`, Messages `PascalCase`
- For streaming responses, use `stream` keyword (see `subscribeToAuthCallback` in `account.proto`)
**Run `npm run protos`** after any proto changes—generates types in:
- `src/shared/proto/` - Shared type definitions
- `src/generated/grpc-js/` - Service implementations
- `src/generated/nice-grpc/` - Promise-based clients
- `src/generated/hosts/` - Generated handlers
**Adding new enum values** (like a new `ClineSay` type) requires updating conversion mappings in `src/shared/proto-conversions/cline-message.ts`
**Adding new RPC methods** requires:
- Handler in `src/core/controller/<domain>/`
- Call from webview via generated client: `UiServiceClient.scrollToSettings(StringRequest.create({ value: "browser" }))`
**Example—the `explain-changes` feature touched:**
- `proto/cline/task.proto` - Added `ExplainChangesRequest` message and `explainChanges` RPC
- `proto/cline/ui.proto` - Added `GENERATE_EXPLANATION = 29` to `ClineSay` enum
- `src/shared/ExtensionMessage.ts` - Added `ClineSayGenerateExplanation` type
- `src/shared/proto-conversions/cline-message.ts` - Added mapping for new say type
- `src/core/controller/task/explainChanges.ts` - Handler implementation
- `webview-ui/src/components/chat/ChatRow.tsx` - UI rendering
## Adding a New API Provider
When adding a new provider (e.g., "openai-codex"), you must update the proto conversion layer in THREE places or the provider will silently reset to Anthropic:
1. `proto/cline/models.proto` - Add to the `ApiProvider` enum (e.g., `OPENAI_CODEX = 40;`)
2. `convertApiProviderToProto()` in `src/shared/proto-conversions/models/api-configuration-conversion.ts` - Add case mapping string to proto enum
3. `convertProtoToApiProvider()` in the same file - Add case mapping proto enum back to string
**Why this matters:** Without these, the provider string hits the `default` case and returns `ANTHROPIC`. The webview, provider list, and handler all work fine, but the state silently resets when it round-trips through proto serialization. No error is thrown.
**Other files to update when adding a provider:**
- `src/shared/api.ts` - Add to `ApiProvider` union type, define models
- `src/shared/providers/providers.json` - Add to provider list for dropdown
- `src/core/api/index.ts` - Register handler in `createHandlerForProvider()`
- `webview-ui/src/components/settings/utils/providerUtils.ts` - Add cases in `getModelsForProvider()` and `normalizeApiConfiguration()`
- `webview-ui/src/utils/validate.ts` - Add validation case
- `webview-ui/src/components/settings/ApiOptions.tsx` - Render provider component
## Responses API Providers (OpenAI Codex, OpenAI Native)
Providers using OpenAI's Responses API require native tool calling. XML tools don't work with the Responses API.
**Symptoms of broken native tool calling:**
- Tools get called multiple times (e.g., `ask_followup_question` asks the same question twice)
- Tool arguments get duplicated or malformed
- The model responds but tools aren't recognized
**Root causes to check:**
1. **Provider missing from `isNextGenModelProvider()`** in `src/utils/model-utils.ts`. The native variant matchers (e.g., `native-gpt-5/config.ts`) call this function. If your provider isn't in the list, the matcher returns false and falls back to XML tools.
2. **Model missing `apiFormat: ApiFormat.OPENAI_RESPONSES`** in its model info (`src/shared/api.ts`). This property signals that the model requires native tool calling. The task runner in `src/core/task/index.ts` checks this and forces `enableNativeToolCalls: true` regardless of user settings.
**When adding a new Responses API provider:**
1. Add provider to `isNextGenModelProvider()` list in `src/utils/model-utils.ts`
2. Set `apiFormat: ApiFormat.OPENAI_RESPONSES` on all models that use the Responses API
3. The variant matcher and task runner will handle the rest automatically
## Adding Tools to System Prompt
This is tricky—multiple prompt variants and configs. **Always search for existing similar tools first and follow their pattern.** Look at the full chain from prompt definition → variant configs → handler → UI before implementing.
1. **Add to `ClineDefaultTool` enum** in `src/shared/tools.ts`
2. **Tool definition** in `src/core/prompts/system-prompt/tools/` (create file like `generate_explanation.ts`)
- Define variants for each `ModelFamily` (generic, next-gen, xs, etc.)
- Export variants array (e.g., `export const my_tool_variants = [GENERIC, NATIVE_NEXT_GEN, XS]`)
- **Fallback behavior**: If a variant isn't defined for a model family, `ClineToolSet.getToolByNameWithFallback()` automatically falls back to GENERIC. So you only need to export `[GENERIC]` unless the tool needs model-specific behavior.
3. **Register in `src/core/prompts/system-prompt/tools/init.ts`** - Import and spread into `allToolVariants`
4. **Add to variant configs** - Each model family has its own config in `src/core/prompts/system-prompt/variants/*/config.ts`. Add your tool's enum to the `.tools()` list:
- `generic/config.ts`, `next-gen/config.ts`, `gpt-5/config.ts`, `native-gpt-5/config.ts`, `native-gpt-5-1/config.ts`, `native-next-gen/config.ts`, `gemini-3/config.ts`, `glm/config.ts`, `hermes/config.ts`, `xs/config.ts`
- **Important**: If you add to a variant's config, make sure the tool spec exports a variant for that ModelFamily (or relies on GENERIC fallback)
5. **Create handler** in `src/core/task/tools/handlers/`
6. **Wire up in `ToolExecutor.ts`** if needed for execution flow
7. **Add to tool parsing** in `src/core/assistant-message/index.ts` if needed
8. **If tool has UI feedback**: add `ClineSay` enum in proto, update `src/shared/ExtensionMessage.ts`, update `src/shared/proto-conversions/cline-message.ts`, update `webview-ui/src/components/chat/ChatRow.tsx`
## Modifying System Prompt
**Read these first:** `src/core/prompts/system-prompt/README.md`, `tools/README.md`, `__tests__/README.md`
System prompt is modular: **components** (reusable sections) + **variants** (model-specific configs) + **templates** (with `{{PLACEHOLDER}}` resolution).
**Key directories:**
- `components/` - Shared sections: `rules.ts`, `capabilities.ts`, `editing_files.ts`, etc.
- `variants/` - Model-specific: `generic/`, `next-gen/`, `xs/`, `gpt-5/`, `gemini-3/`, `hermes/`, `glm/`, etc.
- `templates/` - Template engine and placeholder definitions
**Variant tiers (ask user which to modify):**
- **Next-gen** (Claude 4, GPT-5, Gemini 2.5): `next-gen/`, `native-next-gen/`, `native-gpt-5/`, `native-gpt-5-1/`, `gemini-3/`, `gpt-5/`
- **Standard** (default fallback): `generic/`
- **Local/small models**: `xs/`, `hermes/`, `glm/`
**How overrides work:** Variants can override components via `componentOverrides` in their `config.ts`, or provide a custom template in `template.ts` (e.g., `next-gen/template.ts` exports `rules_template`). If no override, the shared component from `components/` is used.
**Example: Adding a rule to RULES section**
1. Check if variant overrides rules: look for `rules_template` in `variants/*/template.ts` or `componentOverrides.RULES` in `config.ts`
2. If shared: modify `components/rules.ts`
3. If overridden: modify that variant's template
4. XS variant is special—has heavily condensed inline content in `template.ts`
**After any changes, regenerate snapshots:**
```bash
UPDATE_SNAPSHOTS=true npm run test:unit
```
Snapshots live in `__tests__/__snapshots__/`. Tests validate across model families and context variations (browser, MCP, focus chain).
## Modifying Default Slash Commands
Three places need updates:
- `src/core/slash-commands/index.ts` - Command definitions
- `src/core/prompts/commands.ts` - System prompt integration
- `webview-ui/src/utils/slash-commands.ts` - Webview autocomplete
## Adding New Global State Keys
Adding a new key to global state requires updates in multiple places. Missing any step causes silent failures.
Required steps:
1. Type definition in `src/shared/storage/state-keys.ts` - Add to `GlobalState` or `Settings` interface
2. Read from globalState in `src/core/storage/utils/state-helpers.ts`:
- Add `const myKey = context.globalState.get<GlobalStateAndSettings["myKey"]>("myKey")` in `readGlobalStateFromDisk()`
- Add to the return object: `myKey: myKey ?? defaultValue,`
3. StateManager handles read/write via `setGlobalState()`/`getGlobalStateKey()` after initialization
Common mistake: Adding only the return value without the `context.globalState.get()` call. This compiles but the value is always `undefined` on load.
## StateManager Cache vs Direct globalState Access
StateManager uses an in-memory cache populated during `StateManager.initialize(context)` in `common.ts`. For most state, use `controller.stateManager.setGlobalState()`/`getGlobalStateKey()`.
Exception: State needed immediately at extension startup (before cache is ready)
When Window A sets state and immediately opens Window B, the new window's StateManager cache is populated from `context.globalState` during initialization. If you need to read state in Window B right at startup (e.g., in `common.ts` during `initialize()`), read directly from `context.globalState.get()` instead of StateManager's cache.
Example pattern (see `lastShownAnnouncementId` and `worktreeAutoOpenPath`):
```typescript
// Writing (normal pattern)
controller.stateManager.setGlobalState("myKey", value)
// Reading at startup in common.ts (bypass cache)
const value = context.globalState.get<string>("myKey")
```
This is only needed for cross-window state read during the brief startup window before StateManager cache is fully usable. Normal state access after initialization should use StateManager.
## ChatRow Cancelled/Interrupted States
When a ChatRow displays a loading/in-progress state (spinner), you must handle what happens when the task is cancelled. This is non-obvious because cancellation doesn't update the message content—you have to infer it from context.
**The pattern:**
1. A message has a `status` field (e.g., `"generating"`, `"complete"`, `"error"`) stored in `message.text` as JSON
2. When cancelled mid-operation, the status stays `"generating"` forever—no one updates it
3. To detect cancellation, check TWO conditions:
- `!isLast` — if this message is no longer the last message, something else happened after it (interrupted)
- `lastModifiedMessage?.ask === "resume_task" || "resume_completed_task"` — task was just cancelled and is waiting to resume
**Example from `generate_explanation`:**
```tsx
const wasCancelled =
explanationInfo.status === "generating" &&
(!isLast ||
lastModifiedMessage?.ask === "resume_task" ||
lastModifiedMessage?.ask === "resume_completed_task")
const isGenerating = explanationInfo.status === "generating" && !wasCancelled
```
**Why both checks?**
- `!isLast` catches: cancelled → resumed → did other stuff → this old message is stale
- `lastModifiedMessage?.ask === "resume_task"` catches: just cancelled, hasn't resumed yet, this message is still technically "last"
**See also:** `BrowserSessionRow.tsx` uses similar pattern with `isLastApiReqInterrupted` and `isLastMessageResume`.
**Backend side:** When streaming is cancelled, clean up properly (close tabs, clear comments, etc.) by checking `taskState.abort` after the streaming function returns.
-90
View File
@@ -1,90 +0,0 @@
# Networking & Proxy Support
To ensure Cline works correctly in all environments (VSCode, JetBrains, CLI) and with various network configurations (especially corporate proxies), strictly follow these guidelines for all network activity.
In extension code, do NOT use the global `fetch` or a default `axios` instance. (Note, `shared/net.ts` is exempt from these rules because it sets up the fetch wrappers.) In Webview code, you SHOULD use global `fetch`.
Global `fetch` and default `axios` do not automatically pick up proxy configurations in all environments (specifically JetBrains and CLI). You MUST use the provided utilities in `@/shared/net` which handle proxy agent configuration. In the webview, the browser/embedder handles proxies.
## Guidelines
### 1. Using `fetch`
Instead of `fetch(...)`, import the proxy-aware wrapper:
```typescript
import { fetch } from '@/shared/net'
// Usage is identical to global fetch
const response = await fetch('https://api.example.com/data')
```
### 2. Using `axios`
When using `axios`, you must apply the settings from `getAxiosSettings()`:
```typescript
import axios from 'axios'
import { getAxiosSettings } from '@/shared/net'
const response = await axios.get('https://api.example.com/data', {
headers: { 'Authorization': '...' },
...getAxiosSettings() // <--- CRITICAL: Injects the proxy agent if needed
})
```
### 3. Third-Party Clients (OpenAI, Ollama, etc.)
Most API client libraries allow you to customize the `fetch` implementation. You **MUST** pass the proxy-aware `fetch` to these clients.
**Example (OpenAI):**
```typescript
import OpenAI from "openai"
import { fetch } from "@/shared/net"
this.client = new OpenAI({
apiKey: '...',
fetch, // <--- CRITICAL: Pass our fetch wrapper
})
```
### 4. Tests
Use `mockFetchForTesting` to mock the underlying fetch implementation.
**Example (callback):**
```
import { mockFetchForTesting } from "@/shared/net"
...
let mockFetch = ...
mockFetchForTesting(mockFetch, () => {
// This calls mockFetch
fetch('https://foo.example').then(...)
})
// Original fetch is restored immediately when the call returns.
```
**Example (Promise):**
```
import { mockFetchForTesting } from "@/shared/net"
...
let mockFetch = ...
await mockFetchForTesting(mockFetch, async () => {
await ...
// This calls mockFetch
await fetch('https://foo.example')
...
})
// Original fetch is restored when the Promise from the callback settles
```
## Verification
If you are adding a new network call or integration:
1. Check `@/shared/net.ts` is imported.
2. Ensure `fetch` or `getAxiosSettings` is being used.
3. Verify that third-party clients are configured to use the custom fetch.
@@ -1,29 +0,0 @@
# Address PR Comments
Review and address all comments on the current branch's PR.
## Steps
1. Get the current branch name and find the associated PR:
```bash
gh pr view --json number,title,body
```
2. Understand the PR context:
- Get the full diff: `git diff origin/main...HEAD`
- Read the changed files to understand what the PR is doing
- Read related files if needed to understand the broader context
- Understand the intent and spirit of the changes, not just the code
3. Fetch all PR comments:
- Inline comments: `gh api repos/{owner}/{repo}/pulls/{pr_number}/comments`
- General comments: `gh pr view {pr_number} --json comments,reviews`
4. Present a summary of all comments with your recommendation for each (apply, skip, or respond). Ignore bot noise (changeset-bot, CI status, etc.).
5. **Wait for my approval** before proceeding.
6. After approval:
- Apply code changes and commit
- Reply to comments that were addressed or intentionally skipped
- Push commits
@@ -1,49 +0,0 @@
# Find Best Reviewers for Current Branch
Analyze my current branch to find the best people to review my PR based on **domain expertise** and git history.
## Steps
1. Get the current branch name and verify it's not `main`
2. Get the diff between the current branch and `origin/main`:
- Use `git diff origin/main...HEAD --name-only` to get changed files
- Use `git diff origin/main...HEAD` to understand the nature/spirit of the changes
3. **Identify the domain/feature area** being changed:
- Read the diff carefully to understand WHAT is being changed conceptually (e.g., "slash commands", "authentication", "API client", "UI components")
- This semantic understanding is crucial for finding the right reviewers
4. Find domain experts by searching for related files and their contributors:
- Identify all files related to the feature/domain (not just the ones changed)
- Example: if changing slash commands, find ALL slash-command related files across the codebase
- Use `git log --format="%an <%ae>" -- <related-files-pattern>` to find who has expertise in that domain
5. For additional context, also gather:
- `git blame -L <start>,<end> origin/main -- <file-path>` for exact lines changed
- Recent commit activity on related files
6. Score and rank contributors by:
- **Highest weight: Domain expertise** - who has the most commits to files in this feature area (even files not touched by this PR)
- **Medium weight: Direct file expertise** - commits to the specific files being changed
- **Lower weight: Line-level ownership** - authored the exact lines being modified
7. Exclude myself (check against my git config user.email)
8. Present the top 5 reviewers as an ordered list
## Output Format
Output an ordered list:
1. **Name** - Domain expert: 15 commits to slash-command related files, authored core parsing logic
2. **Name** - 8 commits to affected files, recently added the feature being modified
3. ...
## Commands Reference
```bash
git config user.email
git diff origin/main...HEAD --name-only
git diff origin/main...HEAD
# Find related files for a domain (adjust pattern based on what you learn from the diff)
find . -type f \( -name "*slash-command*" -o -name "*SlashCommand*" \) | head -20
# Get contributors for related files
find . -type f \( -name "*slash-command*" -o -name "*SlashCommand*" \) -print0 | xargs -0 git log --format="%an <%ae>" -- | sort | uniq -c | sort -rn
git log --format="%an <%ae>" -- <file> | sort | uniq -c | sort -rn
git blame -L 10,20 origin/main -- <file>
```
Do NOT ask questions - analyze the changes, identify the domain, and output the reviewer list.
-194
View File
@@ -1,194 +0,0 @@
# Hotfix Release
Create a hotfix release by cherry-picking specific commits from main onto the latest release tag.
## Overview
This workflow helps you:
1. Select specific commits from main to include in a hotfix
2. Create a release notes commit on main (changelog + version bump)
3. Cherry-pick everything onto the latest release tag
4. Tag and push the new release
## Step 1: Setup and Gather Information
First, ensure we're on main and up to date:
```bash
git checkout main && git pull origin main
```
Get the latest release tag:
```bash
git tag --sort=-v:refname | head -1
```
## Step 2: Present Commits Since Last Release
Show all commits on main since the last release tag:
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
git log ${LAST_TAG}..HEAD --oneline --format="%h %s (%an)"
```
Also get the commit messages already on the tag (to identify previously cherry-picked commits). Note: Run these as separate commands to avoid shell parsing issues with parentheses in author names:
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
PREV_TAG=$(git tag --sort=-v:refname | head -2 | tail -1)
```
```bash
git log $PREV_TAG..$LAST_TAG --oneline --format="%s"
```
**Present the list** to the user in a numbered format with commit hash, subject, and author. For any commits whose subject line already appears in the tag's history (previously cherry-picked in an earlier hotfix) or are "Release Notes" commits, add `(already in previous hotfix)` or `(release notes - skip)` after them so the user knows to skip those.
Ask which commits to include in the hotfix.
Use the ask_followup_question tool to let the user specify which commits they want (by number or hash).
## Step 3: Analyze Selected Commits
For each selected commit:
1. Get the full commit message: `git show --no-patch --format="%B" <hash>`
2. Get the diff to understand the change: `git show <hash> --stat`
3. Find the associated PR if any: `gh pr list --search "<hash>" --state merged --json number,title --jq '.[0]'`
Build a mental model of what these changes do for the changelog.
## Step 4: Determine New Version Number
Parse the current version from package.json and the last tag:
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
echo "Last release: $LAST_TAG"
cat package.json | grep '"version"'
```
Hotfixes always increment the patch version (e.g., 3.40.0 -> 3.40.1, or 3.40.1 -> 3.40.2).
**Ask the user to confirm the new version number.**
## Step 5: Create Release Notes Commit on Main
On the main branch, create a commit that updates:
1. **CHANGELOG.md** - Add a new section for the hotfix version at the top:
```markdown
## [3.40.1]
- Description of fix 1
- Description of fix 2
```
Write clear, user-friendly descriptions based on your analysis of the commits.
2. **package.json** - Update the version field to the new version
3. **Delete changesets** for the commits being included in the hotfix. This prevents the changeset bot from including duplicate entries in the next regular release.
Find and delete the changeset files associated with the selected commits:
```bash
ls .changeset/
```
Each changeset file in `.changeset/` corresponds to a PR. Read them to identify which ones belong to the commits you're hotfixing, then delete those files.
**Skip running `npm run install:all`** - the automation handles outdated lockfiles.
Commit with message format: `v{VERSION} Release Notes (hotfix)`
In the commit body, mention:
- This is for a hotfix release
- List the cherry-picked commits that will be included
```bash
git add CHANGELOG.md package.json .changeset/
git commit -m "v3.40.1 Release Notes (hotfix)
Hotfix release including:
- <commit1-hash>: <description>
- <commit2-hash>: <description>
"
```
Push to main:
```bash
git push origin main
```
## Step 6: Build the Hotfix on the Tag
Checkout the last release tag (detached HEAD):
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
git checkout $LAST_TAG
```
Cherry-pick the selected commits in order:
```bash
git cherry-pick <commit1-hash>
git cherry-pick <commit2-hash>
# ... etc
```
Finally, cherry-pick the release notes commit you just pushed to main:
```bash
# Get the hash of the release notes commit (should be HEAD of main)
RELEASE_NOTES_COMMIT=$(git rev-parse main)
git cherry-pick $RELEASE_NOTES_COMMIT
```
## Step 7: Tag and Push
After all cherry-picks are applied successfully:
```bash
# Tag the new release
git tag v{VERSION}
# Push the tag to remote
git push origin v{VERSION}
```
## Step 8: Return to Main and Summary
Return to main branch:
```bash
git checkout main
```
**Copy a Slack announcement message to clipboard** with the version and PR links for each included fix:
```
VS Code Hotfix v{VERSION} Published
- Description of fix 1 https://github.com/cline/cline/pull/{PR_NUMBER}
- Description of fix 2 https://github.com/cline/cline/pull/{PR_NUMBER}
```
Present a final summary:
- New version: v{VERSION}
- Tag pushed: yes
- Commits included: (list them)
- Slack message copied to clipboard: yes
Remind the user to:
1. Manually trigger the publish release GitHub Action at: https://github.com/cline/cline/actions/workflows/publish.yml (paste `v{VERSION}` as the tag)
2. Post the Slack message to announce the hotfix
## Important Notes
- This workflow does NOT create a release branch - only tags
- The release notes commit goes to main first, then gets cherry-picked to the tag
- This keeps main's history accurate while allowing hotfix releases from tags
- If cherry-pick conflicts occur, resolve them before continuing
-232
View File
@@ -1,232 +0,0 @@
# Release
Prepare and publish a release from the open changeset PR.
## Overview
This workflow helps you:
1. Find and checkout the open changeset PR
2. Clean up the changelog (fix version format, wordsmith entries)
3. Push changes back to the PR branch
4. Merge with proper commit message format
5. Tag and push the release (after verifying the commit)
6. Trigger the publish workflow
7. Update GitHub release notes
8. Provide final summary with Slack announcement
## Step 1: Find the Changeset PR
Look for the open changeset PR:
```bash
gh pr list --search "Changeset version bump" --state open --json number,title,headRefName,url
```
If no PR is found, inform the user there's no changeset PR ready. They may need to:
- Merge PRs with changesets to main first
- Manually trigger the Changeset Converter workflow at: https://github.com/cline/cline/actions/workflows/changeset-converter.yml
## Step 2: Gather PR Information
Get the PR details:
```bash
PR_NUMBER=<number from step 1>
gh pr view $PR_NUMBER --json body,files,headRefName
```
Checkout the PR branch:
```bash
git fetch origin changeset-release/main
git checkout changeset-release/main
```
If the branch has diverged from remote, reset to the remote version:
```bash
git reset --hard origin/changeset-release/main
```
## Step 3: Analyze the Changes
Read the current CHANGELOG.md to see what the automation generated:
```bash
head -50 CHANGELOG.md
```
Get the version from package.json:
```bash
cat package.json | grep '"version"'
```
**Present to the user:**
- The version number that will be released
- The raw changelog entries from the changeset PR
- Whether this is a patch, minor, or major release
## Step 4: Clean Up the Changelog
The changelog needs these fixes:
1. **Add brackets to version number**: Change `## 3.44.1` to `## [3.44.1]`
2. **No category headers**: Don't use `### Added`, `### Fixed`, etc. Just a flat list of bullet points.
3. **Order entries from most important to least important**:
- Lead with major new features or significant fixes users care about
- End with minor fixes or internal changes
4. **Write user-friendly descriptions**:
- This is for end users, not developers—explain what changed in plain language
- Remove commit hashes from the beginning of lines (the automation adds these)
- Look at the actual commit diffs (`git show <hash>`) and PRs to understand what changed
- Write colorful descriptions that explain the value and impact, not just technical details
- Consolidate related changes into single entries when appropriate
**Ask the user** to review the proposed changelog changes before applying them. Show them:
- Current (raw) changelog section
- Proposed (cleaned) changelog section
Once approved, apply the changes to CHANGELOG.md.
## Step 5: Commit and Push Changes
After making changelog edits:
```bash
git add CHANGELOG.md
git commit -m "Clean up changelog formatting"
git push origin changeset-release/main
```
## Step 6: Merge the PR
**Ask the user to confirm** they're ready to merge.
Merge the PR with the proper commit message format:
```bash
VERSION=<version from package.json>
gh pr merge $PR_NUMBER --squash --subject "v${VERSION} Release Notes" --body ""
```
**If merge is blocked by branch protection:**
- Users with admin privileges can add the `--admin` flag to bypass
- Users without admin privileges need to get the PR approved through normal review first before merging
## Step 7: Tag the Release
After the merge completes, checkout main and pull:
```bash
git checkout main
git pull origin main
```
**IMPORTANT: Verify the latest commit is the release commit before tagging:**
```bash
git log -1 --oneline
```
Confirm the commit message matches `v{VERSION} Release Notes` (e.g., `v3.44.1 Release Notes`). Do NOT blindly tag HEAD without verification.
Once verified, tag and push:
```bash
VERSION=<version>
git tag v${VERSION}
git push origin v${VERSION}
```
## Step 8: Trigger Publish Workflow
**Copy the tag to clipboard** so the user can easily paste it into the GitHub Actions workflow:
```bash
echo -n "v{VERSION}" | pbcopy
```
**Tell the user to trigger the publish workflow:**
1. Go to: https://github.com/cline/cline/actions/workflows/publish.yml
2. Select **"release"** for release-type
3. Paste **`v{VERSION}`** as the tag (already in clipboard)
**Wait for the user** to confirm the publish workflow has completed before proceeding.
## Step 9: Update GitHub Release Notes
Once the user confirms the publish workflow is done, fetch the auto-generated release content:
```bash
VERSION=<version>
gh release view v${VERSION} --json body --jq '.body'
```
The auto-generated release has:
- `## What's Changed` - PR list (we'll replace this with our changelog)
- `## New Contributors` - First-time contributors (keep this if present)
- `**Full Changelog**` - Comparison link (keep this)
Build the new release body:
1. Start with `## What's Changed` header
2. Add our changelog content (from CHANGELOG.md for this version)
3. Keep the `## New Contributors` section if it exists
4. Keep the `**Full Changelog**` link
Update the release:
```bash
gh release edit v${VERSION} --notes "<new body content>"
```
Verify the release was updated:
```bash
gh release view v${VERSION}
```
## Step 10: Final Summary
**Copy a Slack announcement message to clipboard** (include the full changelog, not just highlights):
```bash
echo "VS Code v{VERSION} Released
- Changelog entry 1
- Changelog entry 2
- Changelog entry 3" | pbcopy
```
**Present a final summary:**
- Version released: v{VERSION}
- PR merged: #{PR_NUMBER}
- Tag pushed: v{VERSION}
- Release: https://github.com/cline/cline/releases/tag/v{VERSION}
- Slack message copied to clipboard
**Final reminder:**
Post the Slack message to announce the release
## Handling Edge Cases
### No changesets found
If the changeset PR body shows no changes, inform the user they need to merge PRs with changesets first.
### Merge conflicts
If there are conflicts on the changeset branch, help the user resolve them:
```bash
git fetch origin main
git rebase origin/main
# resolve conflicts
git push origin changeset-release/main --force-with-lease
```
### User wants to add more changes
If the user wants to include additional PRs before releasing:
1. Ask them to merge those PRs to main first
2. The changeset automation will update the PR automatically
3. Re-run this workflow after the PR is updated
+3 -28
View File
@@ -72,12 +72,12 @@ POSTHOG_TELEMETRY_ENABLED=true # Enable PostHog telemetry (default: tru
# Example configurations:
#
# Console debugging (logs only):
# OTEL_TELEMETRY_ENABLED=true
# OTEL_TELEMETRY_ENABLED=1
# OTEL_LOGS_EXPORTER=console
# TEL_DEBUG_DIAGNOSTICS=true
#
# OTLP with gRPC (insecure, for local testing):
# OTEL_TELEMETRY_ENABLED=true
# OTEL_TELEMETRY_ENABLED=1
# OTEL_LOGS_EXPORTER=otlp
# OTEL_EXPORTER_OTLP_PROTOCOL=grpc
# OTEL_EXPORTER_OTLP_ENDPOINT=localhost:4317
@@ -85,37 +85,12 @@ POSTHOG_TELEMETRY_ENABLED=true # Enable PostHog telemetry (default: tru
# OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer your-token
#
# OTLP with HTTP/JSON (production):
# OTEL_TELEMETRY_ENABLED=true
# OTEL_TELEMETRY_ENABLED=1
# OTEL_LOGS_EXPORTER=otlp
# OTEL_EXPORTER_OTLP_PROTOCOL=http/json
# OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.example.com
# OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer your-token
# ============================================================================
# OBJECT STORE CONFIGURATION
# ============================================================================
# TO ENABLE S3 OR R2 STORAGE, UNCOMMENT AND FILL IN THE FOLLOWING:
# CLINE_STORAGE_ADAPTER="s3" # Options: "s3" or "r2"
# CLINE_STORAGE_BUCKET="cline"
# CLINE_STORAGE_ACCESS_KEY_ID="key"
# CLINE_STORAGE_SECRET_ACCESS_KEY="secrets"
#
# [OPTIONAL FIELDS FOR R2]
# CLINE_STORAGE_ACCOUNT_ID = "account-id"
# Default R2 endpoint (if not set): "https://<CLINE_STORAGE_ACCOUNT_ID>.r2.cloudflarestorage.com"
# CLINE_STORAGE_ENDPOINT = "http://localhost:8333"
#
# [OPTIONAL FIELDS FOR S3]
# CLINE_STORAGE_REGION = "us-west-1" # AWS Bucket Region (default: "us-east-1")
# Default S3 endpoint (if not set): "https://s3.<CLINE_STORAGE_REGION>.amazonaws.com"
# CLINE_STORAGE_ENDPOINT = "http://localhost:8333"
#
# [OPTIONAL FIELDS FOR ALL STORAGE TYPES]
# CLINE_STORAGE_SYNC_INTERVAL_MS = 30000 # Interval for sync worker in milliseconds
# CLINE_STORAGE_SYNC_MAX_RETRIES = 5 # Max retries for failed sync operations
# CLINE_STORAGE_SYNC_BATCH_SIZE = 10 # Number of files to sync in each batch
# CLINE_STORAGE_SYNC_BACKFILL_ENABLED = false # Enable backfill of existing data on startup
# ============================================================================
# OPTIONAL DEVELOPMENT SETTINGS
# ============================================================================
+1
View File
@@ -1,3 +1,4 @@
/docs/
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
/src/core/storage/ @celestial-vault
+1 -1
View File
@@ -58,7 +58,7 @@ jobs:
cache: "npm"
- name: Install Dependencies
run: npm ci
run: npm install changeset
# Check if there are any new changesets to process
- name: Check for changesets
-173
View File
@@ -1,173 +0,0 @@
name: Claude Issue Triage
on:
issues:
types: [opened]
# Manual trigger for backfilling existing issues. Run from terminal:
# gh workflow run claude-issue-triage.yml -f issue_number=1234
# Or batch process:
# gh issue list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run claude-issue-triage.yml -f issue_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
issue_number:
description: 'Issue number to triage'
required: true
type: string
jobs:
claude-issue-triage:
runs-on: ubuntu-latest
timeout-minutes: 120
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> Claude can read the codebase but CANNOT write/push any code
# - issues: write -> Claude can comment and add labels (the only write access needed)
# - pull-requests: read -> Claude can view PR context but CANNOT create PRs
# This ensures that even if a malicious user attempts prompt injection via issue content,
# Claude cannot modify repository code, create branches, or open PRs.
permissions:
contents: read
issues: write
pull-requests: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run Issue Response & Triage
id: triage
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
allowed_non_write_users: "*"
# Allow all tools - security is enforced by GitHub permissions above (contents: read, issues: write)
claude_args: --model claude-opus-4-5-20251101 --allowedTools "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch"
prompt: |
You're a GitHub issue first responder for the open source Cline repository.
**Issue:** #${{ github.event.issue.number || inputs.issue_number }}
**Title:** ${{ github.event.issue.title || 'See issue details below' }}
**Author:** @${{ github.event.issue.user.login || 'See issue details below' }}
## Your job
Investigate this issue thoroughly, then post a single helpful comment that helps the user and gives maintainers the context they need.
## Investigation
Start by reading the full issue:
gh issue view ${{ github.event.issue.number || inputs.issue_number }}
### Search for duplicates and related issues
Search thoroughly for existing issues that match this one:
gh issue list --search "<keywords from the issue>" --state all --limit 30
gh issue list --search "<error messages>" --state all --limit 20
gh issue list --search "<affected feature/component>" --state all --limit 20
For each relevant issue you find, read it including its comments:
gh issue view <number> --comments
You're looking for:
- **Duplicates**: Issues describing the same problem. Link to them and explain why you think they're duplicates. If closed, check how they were resolved - the solution might apply here.
- **Related issues**: Similar problems or context that could help. Pull useful information from their comments (workarounds others found, debugging steps that helped, maintainer explanations). Link to them and explain the connection.
If there are closed issues with solutions, surface those solutions prominently - this might immediately solve the user's problem.
### Analyze recent changes (ALWAYS DO THIS)
Many issues are regressions from recent releases. **Always** check what changed recently:
gh release list --limit 10
gh pr list --state merged --limit 50 --json number,title,mergedAt,author,body
Look for PRs merged in the last few weeks that might correlate with the issue. If you find a likely connection:
gh pr view <number>
gh pr diff <number>
git log --since="1 month ago" --oneline -- <relevant paths>
git show <commit>
**Always include your findings in your comment:**
- If you find a regression, call it out explicitly: which PR/commit likely caused it, who authored it, what changed, and suggest a fix direction if you can see one.
- If you don't find anything related, still mention it: "I analyzed recent PRs and releases but didn't find any changes that seem related to this issue."
### Search the codebase
Find the relevant code:
- Use grep/find to locate code related to the issue
- Key areas: `src/api/` (providers/models), `src/core/prompts/` (tools/prompts), platform-specific code for VS Code vs JetBrains
### Find documentation
Cline docs are at **https://docs.cline.bot/** and built with Mintlify from the `docs/` directory.
The URL structure maps directly to the file structure:
- `docs/getting-started/selecting-your-model.mdx` → https://docs.cline.bot/getting-started/selecting-your-model
- `docs/troubleshooting.mdx` → https://docs.cline.bot/troubleshooting
- Headings become anchors: `## Which Model` → `#which-model`
Search the `docs/` directory to find relevant documentation, then construct URLs to link users to:
```bash
ls docs/
grep -r "keyword" docs/ --include="*.mdx" -l
```
### Identify subject matter experts
For issues that clearly need engineering attention:
git log --since="6 months ago" --format="%an" -- <relevant paths> | sort | uniq -c | sort -rn | head -5
Cross-reference with GitHub usernames. Include in your response (@mention, do NOT assign):
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file |
## Weak model detection
Many issues are caused by users running small or non-frontier models that don't tool-call reliably. Signs include:
- Model failing to use tools correctly
- Nonsensical or malformed responses
- User is running a small/local model or older model version
If this looks like a weak model issue, kindly suggest they try reproducing with Claude Sonnet and report back if it persists. Link to https://docs.cline.bot/getting-started/selecting-your-model if helpful. Still label and triage normally.
## Your comment
Write a single comment as a helpful community member. Be conversational, not robotic. Include what's relevant:
- **Helpful response** - Answer their question, suggest a fix, provide a workaround. If you found solutions in related closed issues, surface those prominently.
- **Duplicates and related issues** - Link to any you found and explain why they're duplicates/related. Summarize useful context from their comments.
- **Regression analysis** - If this looks like a regression, explain what change likely caused it, link to the PR/commit, and tag the author.
- **Clarifying questions** - If you need more info, ask specific questions. Don't ask for things already provided.
- **SME table** - Include the table above if this needs engineering attention. Don't tag people for questions with obvious answers or weak-model issues.
- **Context for maintainers** - Relevant code paths, what you found. Keep it concise.
- **Docs links** - If there's relevant documentation, link to it naturally in your response as a recommendation (e.g., "For more details, check out [the Ollama setup guide](url)"). Do NOT add a "Sources" section at the end - integrate doc links into your response where they're helpful.
- **Possible Duplicates section** - ALWAYS include a "Possible Duplicates" section at the end of your comment listing issues that might be duplicates so maintainers can quickly close if appropriate. If none found, say "No obvious duplicates found."
## Labels
First, retrieve all available labels and read their descriptions to understand what each is for:
gh label list --json name,description --limit 100
Then apply the appropriate labels based on your analysis. Only use labels from the list above—do not create new labels.
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "label1,label2"
If your regression analysis found a likely culprit (a recent PR/commit that probably caused this issue), add the "Regression" label:
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "Regression"
IMPORTANT: After posting your comment, add the "Bot Responded" label to indicate this issue has received an automated response:
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "Bot Responded"
## Remember
- **This is a one-time automated response** - you will NOT see their reply or respond again. Never say things like "I can help you", "let me know", "once I have that info", or "I can give you more targeted help" - you won't be there to follow up. If you ask clarifying questions, frame them for the maintainers who will follow up, e.g., "If you can share X, that would help the maintainers diagnose this."
- Don't be formulaic. Respond to what the issue actually needs.
- Surface solutions from past issues - often the fastest path to helping.
- Connecting regressions to specific changes is extremely valuable.
- Link issues with #number so they're clickable.
-272
View File
@@ -1,272 +0,0 @@
name: Claude PR Review
on:
pull_request:
types: [opened, ready_for_review]
# Manual trigger for backfilling existing PRs. Run from terminal:
# gh workflow run claude-pr-review.yml -f pr_number=1234
# Or batch process open PRs:
# gh pr list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run claude-pr-review.yml -f pr_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: string
jobs:
claude-pr-review:
# Runs on PR opened/ready_for_review (skips drafts) or manual trigger for backfilling
if: |
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 120
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> Claude can read the codebase but CANNOT write/push any code
# - pull-requests: write -> Claude can post reviews and inline suggestions
# - issues: read -> Claude can search for related issues
# NOTE: Even with pull-requests: write, Claude CANNOT merge PRs because branch protection
# requires 1 approval from a Code Owner. The GITHUB_TOKEN cannot bypass this.
permissions:
contents: read
pull-requests: write
issues: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get PR number
id: pr
run: |
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
else
echo "number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
fi
- name: Run PR Review
id: review
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
allowed_non_write_users: "*"
claude_args: --model claude-opus-4-5-20251101 --allowedTools "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch"
prompt: |
You're a GitHub PR reviewer for the open source Cline repository. Your goal is to give the PR author helpful feedback and give maintainers the context they need to review efficiently.
PR: #${{ steps.pr.outputs.number }}
## Gather context
```bash
# Get full PR details
gh pr view ${{ steps.pr.outputs.number }} --json number,title,body,author,createdAt,updatedAt,isDraft,labels,commits,files,additions,deletions,changedFiles,baseRefName,headRefName,mergeable,reviewDecision
# Get the diff
gh pr diff ${{ steps.pr.outputs.number }}
# Check CI status
gh pr checks ${{ steps.pr.outputs.number }}
# Get existing review comments (to understand context and your previous feedback)
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/comments --jq '.[] | {user: .user.login, body: .body, path: .path, created_at: .created_at}'
# Get conversation comments
gh pr view ${{ steps.pr.outputs.number }} --comments
```
If this is a re-review (workflow_dispatch event):
Read your previous comments carefully. Understand what you asked for before.
Check if new commits or comments address your previous feedback.
## Check contributing guidelines
Flag (but don't block) if:
- Missing changeset - For user-facing changes, check if there's a `.changeset/` file:
```bash
gh pr diff ${{ steps.pr.outputs.number }} --name-only | grep '.changeset/' || echo "No changeset found"
```
If missing, ask them to run `npm run changeset`
- Missing tests - New features should have tests
## Find related issues and PRs
Search thoroughly for context that might help with the review:
```bash
# Find related issues for context
gh issue list --search "<keywords from the PR>" --state all --limit 30
gh issue list --search "<error messages or feature names>" --state all --limit 20
# Find similar PRs for reference
gh pr list --search "<keywords>" --state all --limit 30
```
For each relevant issue or PR you find, read it including comments:
```bash
gh issue view <number> --comments
gh pr view <number> --comments
```
Look for:
- Open issues this PR might fix that weren't linked in the description
- Similar PRs that went through review - what feedback did they get? What patterns did they follow?
- Context from maintainer discussions that could inform your review
## Find subject matter experts
For files changed in this PR, find who knows the code best:
```bash
# Get files changed
gh pr diff ${{ steps.pr.outputs.number }} --name-only
# For each relevant path, find contributors
git log --since="6 months ago" --format="%an" -- <path> | sort | uniq -c | sort -rn | head -5
```
Cross-reference git authors with GitHub usernames. Include an SME table in your response:
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file (15 commits in 6 months) |
| @username3 | Reviewed similar PR #Y with extensive feedback |
## Deep code review
This is the most important part. Don't just look for syntax issues - understand what the PR is trying to achieve and whether the implementation is the right approach.
Step 1: Understand the intent
Read the PR description and understand what the author is trying to accomplish. What problem are they solving? What feature are they adding?
Step 2: Form your own opinion first
Before analyzing their code, think about how YOU would implement this feature or fix. What files would you touch? What patterns would you follow? What edge cases would you handle?
Step 3: Compare approaches
Now look at their implementation. How does it compare to what you would have done?
- Is their approach better in some ways? Note what they did well.
- Is their approach missing something? Be specific about what and why.
- Are there edge cases they haven't considered?
- Does it follow the patterns established in similar parts of the codebase?
Step 4: Look at the bigger picture
- What other files or systems does this change interact with?
- Could this break anything else?
- Is there additional work needed beyond this PR to complete the feature?
- Does this fit well with the overall architecture?
Step 5: Find reference implementations
Look for similar changes in the codebase:
```bash
git log --oneline --all --grep="<relevant keywords>" | head -20
git log --oneline -- <similar files> | head -20
```
If this is adding a new API provider, look at how other providers are implemented.
If this is adding a new feature, look at how similar features were added.
Note where their implementation aligns with or diverges from established patterns.
Step 6: Standard code review checks
- DRY: Is there duplicated code that could be extracted?
- Error handling: Are errors handled appropriately?
- Security: Any injection risks, credential exposure, unsafe dependencies?
- Performance: Any obvious inefficiencies, memory leaks, N+1 patterns?
- Types: Is TypeScript used correctly? Any unsafe type assertions?
- Naming: Are variables and functions named clearly?
- Comments: Is complex logic explained? Are there outdated comments?
## Inline code suggestions
For specific code improvements, use GitHub's suggestion syntax via `gh api`.
This creates suggestions the author can commit with one click.
Single-line suggestion:
```bash
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews \
-X POST \
-f commit_id="$(gh pr view ${{ steps.pr.outputs.number }} --json headRefOid -q .headRefOid)" \
-f event="COMMENT" \
-f body="" \
-F comments='[
{
"path": "src/example.ts",
"line": 42,
"body": "Consider simplifying:\n\n```suggestion\nconst result = items.filter(Boolean);\n```"
}
]'
```
Multi-line suggestion (replacing lines 40-45):
```bash
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews \
-X POST \
-f commit_id="$(gh pr view ${{ steps.pr.outputs.number }} --json headRefOid -q .headRefOid)" \
-f event="COMMENT" \
-f body="" \
-F comments='[
{
"path": "src/example.ts",
"start_line": 40,
"line": 45,
"body": "This can be simplified:\n\n```suggestion\nconst simplified = doThing();\n```"
}
]'
```
Use inline suggestions for concrete improvements. Use regular comments for questions or broader feedback.
## Post your review
After your investigation, post a single helpful comment that helps the author and gives maintainers context.
Start with a warm thank you for their contribution. Be conversational, not robotic.
Include what's relevant:
- In-depth explanation of what the PR does - Be comprehensive. A maintainer should be able to read this section and fully understand the author's intent, why they made the changes, how they implemented it, and what files/systems are affected. Don't just summarize - explain.
- Related issues/PRs you found that provide useful context (link to them)
- Your review findings (issues to address, suggestions, etc.)
- Clear next steps for the author
Include a "For Maintainers" section with:
- Anything else useful to help the maintainer resolve this PR
- Related issues/PRs with context on why they're relevant
- Open issues this PR might fix that weren't linked in the description
- Your recommendation: merge as-is, needs changes, needs discussion, close, etc.
- SME table - who should review this and why
For the SME table:
| SME | Reason |
|-----|--------|
| @username | Primary contributor to affected files |
## Update labels
Add appropriate labels based on your analysis:
```bash
gh label list --json name,description --limit 100
gh pr edit ${{ steps.pr.outputs.number }} --add-label "label1,label2"
```
When done, add the reviewed label:
```bash
gh pr edit ${{ steps.pr.outputs.number }} --add-label "Bot Reviewed"
```
## Remember
- This is a one-time automated response - you will NOT see their reply or respond again. Never say things like "let me know if you have questions", "I can help you with", or "feel free to ask" - you won't be there to follow up. Frame any questions for the maintainers who will follow up.
- Be helpful and welcoming - Many contributors are new to the project
- Be specific - Point to exact lines and suggest fixes, don't give vague feedback
- Think deeply - Don't just surface-level review, understand the intent and evaluate the approach
- Use inline suggestions - Make it easy for authors to accept changes
- You're a first-pass reviewer - A human maintainer will do final approval
-312
View File
@@ -1,312 +0,0 @@
name: Cline PR Code Review
on:
pull_request:
types:
[opened, ready_for_review]
# Manual trigger for backfilling existing PRs. Run from terminal:
# gh workflow run cline-pr-review.yml -f pr_number=1234
# Or batch process open PRs:
# gh pr list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run cline-pr-review.yml -f pr_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
pr_number:
description: "PR number to review"
required: true
type: string
concurrency:
group: pr-review-${{ github.event.pull_request.number || inputs.pr_number }}
cancel-in-progress: true
jobs:
cline-pr-review:
# Runs on PR opened/ready_for_review (skips drafts) or manual trigger for backfilling
if: |
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 60
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> cline can read the codebase but CANNOT write/push any code
# - pull-requests: write -> cline can post reviews and inline suggestions
# - issues: read -> cline can search for related issues
# NOTE: Even with pull-requests: write, cline CANNOT merge PRs because branch protection
# requires 1 approval from a Code Owner. The GITHUB_TOKEN cannot bypass this.
permissions:
contents: read
pull-requests: write
issues: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: "npm"
- name: Install and Verify Cline CLI
run: |
npx cline version # verify installation
- name: Configure Cline with Anthropic
run: |
npx cline auth --provider anthropic \
--apikey "${{ secrets.ANTHROPIC_API_KEY }}" \
--modelid claude-opus-4-5-20251101
- name: Get PR number
id: pr
run: |
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
else
echo "number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
fi
- name: Review PR with Cline
env:
PR_NUMBER: ${{ steps.pr.outputs.number }}
GITHUB_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
CLINE_COMMAND_PERMISSIONS: |
{
"allow": [
"gh pr diff *",
"gh pr view *",
"gh pr checks *",
"gh pr list *",
"gh label list *",
"gh issue list *",
"gh issue view *",
"git log *",
"gh pr comment ${{ steps.pr.outputs.number }} *",
"gh pr edit ${{ steps.pr.outputs.number }} *",
"gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/comments *",
"gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews *"
]
}
run: |
npx cline --yolo 'You'\''re a GitHub PR reviewer for the open source Cline repository. Your goal is to give the PR author helpful feedback and give maintainers the context they need to review efficiently.
PR: #'"${PR_NUMBER}"'
## Gather context
```bash
# Get full PR details
gh pr view '"${PR_NUMBER}"' --json number,title,body,author,createdAt,updatedAt,isDraft,labels,commits,files,additions,deletions,changedFiles,baseRefName,headRefName,mergeable,reviewDecision
# Get the diff
gh pr diff '"${PR_NUMBER}"'
# Check CI status
gh pr checks '"${PR_NUMBER}"'
# Get existing review comments (to understand context and your previous feedback)
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/comments --jq '\''.[] | {user: .user.login, body: .body, path: .path, created_at: .created_at}'\''
# Get conversation comments
gh pr view '"${PR_NUMBER}"' --comments
```
If this is a re-review (workflow_dispatch event):
Read your previous comments carefully. Understand what you asked for before.
Check if new commits or comments address your previous feedback.
## Check contributing guidelines
Flag (but don'\''t block) if:
- Missing changeset - For user-facing changes, check if there'\''s a `.changeset/` file:
```bash
gh pr diff '"${PR_NUMBER}"' --name-only | grep '\''.changeset/'\'' || echo '\''No changeset found'\''
```
If missing, ask them to run `npm run changeset`
- Missing tests - New features should have tests
## Find related issues and PRs
Search thoroughly for context that might help with the review:
```bash
# Find related issues for context
gh issue list --search '\''<keywords from the PR>'\'' --state all --limit 30
gh issue list --search '\''<error messages or feature names>'\'' --state all --limit 20
# Find similar PRs for reference
gh pr list --search '\''<keywords>'\'' --state all --limit 30
```
For each relevant issue or PR you find, read it including comments:
```bash
gh issue view <number> --comments
gh pr view <number> --comments
```
Look for:
- Open issues this PR might fix that weren'\''t linked in the description
- Similar PRs that went through review - what feedback did they get? What patterns did they follow?
- Context from maintainer discussions that could inform your review
## Find subject matter experts
For files changed in this PR, find who knows the code best:
```bash
# Get files changed
gh pr diff '"${PR_NUMBER}"' --name-only
# For each relevant path, find contributors
git log --since='\''6 months ago'\'' --format='\''%an'\'' -- <path> | sort | uniq -c | sort -rn | head -5
```
Cross-reference git authors with GitHub usernames. Include an SME table in your response:
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file (15 commits in 6 months) |
| @username3 | Reviewed similar PR #Y with extensive feedback |
## Bash command usage
Don'\''t use operators like `|`, `&&`, or `;` - run each command separately and analyze the output.
When referencing command outputs, quote them properly to avoid formatting issues.
## Deep code review
This is the most important part. Don'\''t just look for syntax issues - understand what the PR is trying to achieve and whether the implementation is the right approach.
Step 1: Understand the intent
Read the PR description and understand what the author is trying to accomplish. What problem are they solving? What feature are they adding?
Step 2: Form your own opinion first
Before analyzing their code, think about how YOU would implement this feature or fix. What files would you touch? What patterns would you follow? What edge cases would you handle?
Step 3: Compare approaches
Now look at their implementation. How does it compare to what you would have done?
- Is their approach better in some ways? Note what they did well.
- Is their approach missing something? Be specific about what and why.
- Are there edge cases they haven'\''t considered?
- Does it follow the patterns established in similar parts of the codebase?
Step 4: Look at the bigger picture
- What other files or systems does this change interact with?
- Could this break anything else?
- Is there additional work needed beyond this PR to complete the feature?
- Does this fit well with the overall architecture?
Step 5: Find reference implementations
Look for similar changes in the codebase:
```bash
git log --oneline --all --grep='\''<relevant keywords>'\'' | head -20
git log --oneline -- <similar files> | head -20
```
If this is adding a new API provider, look at how other providers are implemented.
If this is adding a new feature, look at how similar features were added.
Note where their implementation aligns with or diverges from established patterns.
Step 6: Standard code review checks
- DRY: Is there duplicated code that could be extracted?
- Error handling: Are errors handled appropriately?
- Security: Any injection risks, credential exposure, unsafe dependencies?
- Performance: Any obvious inefficiencies, memory leaks, N+1 patterns?
- Types: Is TypeScript used correctly? Any unsafe type assertions?
- Naming: Are variables and functions named clearly?
- Comments: Is complex logic explained? Are there outdated comments?
## Inline code suggestions
For specific code improvements, use GitHub'\''s suggestion syntax via `gh api`.
This creates suggestions the author can commit with one click.
Single-line suggestion:
```bash
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/reviews \
-X POST \
-f commit_id="$(gh pr view '"${PR_NUMBER}"' --json headRefOid -q .headRefOid)" \
-f event='\''COMMENT'\'' \
-f body='\'''\'' \
-F comments='\''[
{
"path": "src/example.ts",
"line": 42,
"body": "Consider simplifying:\n\n```suggestion\nconst result = items.filter(Boolean);\n```"
}
]'\''
```
Multi-line suggestion (replacing lines 40-45):
```bash
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/reviews \
-X POST \
-f commit_id="$(gh pr view '"${PR_NUMBER}"' --json headRefOid -q .headRefOid)" \
-f event='\''COMMENT'\'' \
-f body='\'''\'' \
-F comments='\''[
{
"path": "src/example.ts",
"start_line": 40,
"line": 45,
"body": "This can be simplified:\n\n```suggestion\nconst simplified = doThing();\n```"
}
]'\''
```
Use inline suggestions for concrete improvements. Use regular comments for questions or broader feedback.
## Post your review
After your investigation, post a single helpful comment that helps the author and gives maintainers context.
Start with a warm thank you for their contribution. Be conversational, not robotic.
Include what'\''s relevant:
- In-depth explanation of what the PR does - Be comprehensive. A maintainer should be able to read this section and fully understand the author'\''s intent, why they made the changes, how they implemented it, and what files/systems are affected. Don'\''t just summarize - explain.
- Related issues/PRs you found that provide useful context (link to them)
- Your review findings (issues to address, suggestions, etc.)
- Clear next steps for the author
Include a '\''For Maintainers'\'' section with:
- Anything else useful to help the maintainer resolve this PR
- Related issues/PRs with context on why they'\''re relevant
- Open issues this PR might fix that weren'\''t linked in the description
- Your recommendation: merge as-is, needs changes, needs discussion, close, etc.
- SME table - who should review this and why
For the SME table:
| SME | Reason |
|-----|--------|
| @username | Primary contributor to affected files |
## Update labels
Add appropriate labels based on your analysis:
```bash
gh label list --json name,description --limit 100
gh pr edit '"${PR_NUMBER}"' --add-label '\''label1,label2'\''
```
When done, add the reviewed label:
```bash
gh pr edit '"${PR_NUMBER}"' --add-label '\''Bot Reviewed'\''
```
## Remember
- This is a one-time automated response - you will NOT see their reply or respond again. Never say things like '\''let me know if you have questions'\'', '\''I can help you with'\'', or '\''feel free to ask'\'' - you won'\''t be there to follow up. Frame any questions for the maintainers who will follow up.
- Be helpful and welcoming - Many contributors are new to the project
- Be specific - Point to exact lines and suggest fixes, don'\''t give vague feedback
- Think deeply - Don'\''t just surface-level review, understand the intent and evaluate the approach
- Use inline suggestions - Make it easy for authors to accept changes
- You'\''re a first-pass reviewer - A human maintainer will do final approval'
-130
View File
@@ -1,130 +0,0 @@
name: Publish NPM Release
on:
workflow_dispatch:
inputs:
confirm_publish:
description: 'Type "publish" to confirm you want to publish to NPM'
required: true
type: string
permissions:
contents: read
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
jobs:
test:
uses: ./.github/workflows/test.yml
publish-npm-release:
needs: test
name: Publish Cline CLI to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main' && github.event.inputs.confirm_publish == 'publish'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Read release version
id: version
run: |
# Read version from cli/package.json (stable version)
VERSION=$(node -p "require('./cli/package.json').version")
echo "Release version: $VERSION"
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Download ripgrep binaries
run: npm run download-ripgrep
- name: Clean previous builds
run: rm -rf dist-standalone
- name: Generate Protos (First Pass)
run: npm run protos && npm run protos-go
- name: Compile CLI
run: npm run compile-cli
- name: Compile CLI for all platforms
run: npm run compile-cli-all-platforms
- name: Build standalone NPM package
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
OTEL_TELEMETRY_ENABLED: "1"
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
POSTHOG_TELEMETRY_ENABLED: "true"
run: npm run compile-standalone-npm
- name: Generate Protos (Second Pass - Bug Workaround)
run: npm run protos && npm run protos-go
- name: Verify build output
run: |
echo "Checking dist-standalone directory..."
ls -la dist-standalone/
echo "Verifying CLI binaries..."
ls -lh cli/bin/cline-* || echo "Warning: CLI binaries not found"
echo "Checking package.json in dist-standalone..."
cat dist-standalone/package.json | grep version
- name: Publish to NPM with latest tag
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}
run: |
echo "Publishing version ${{ steps.version.outputs.version }} to NPM with tag 'latest'..."
cd dist-standalone
npm publish --tag latest --access public
- name: Summary
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'latest'"
echo ""
echo "📦 Install with: npm install -g cline"
echo "🔗 NPM: https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}"
-175
View File
@@ -1,175 +0,0 @@
name: Publish NPM Nightly
on:
schedule:
- cron: '0 12 * * *' # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: read
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
jobs:
test:
uses: ./.github/workflows/test.yml
publish-npm-nightly:
needs: test
name: Publish Cline CLI (Nightly) to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for recent commits
id: check_commits
run: |
if [ $(git rev-list --count HEAD --since="24 hours ago") -eq 0 ]; then
echo "No commits in last 24 hours, skipping publish"
echo "skip=true" >> $GITHUB_OUTPUT
else
echo "Found recent commits, proceeding with publish"
echo "skip=false" >> $GITHUB_OUTPUT
fi
- name: Setup Node.js
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Setup Go
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
if: steps.check_commits.outputs.skip != 'true'
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
if: steps.check_commits.outputs.skip != 'true'
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.check_commits.outputs.skip != 'true' && steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.check_commits.outputs.skip != 'true' && steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Generate nightly version with timestamp
if: steps.check_commits.outputs.skip != 'true'
id: version
run: |
# Read base version from cli/package.json (e.g., "1.0.9")
BASE_VERSION=$(node -p "require('./cli/package.json').version")
# Generate timestamp (Unix epoch seconds)
TIMESTAMP=$(date +%s)
# Create unique nightly version: 1.0.9-nightly.1736365200
VERSION="${BASE_VERSION}-nightly.${TIMESTAMP}"
echo "Base version: $BASE_VERSION"
echo "Generated nightly version: $VERSION"
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Update cli/package.json with nightly version
if: steps.check_commits.outputs.skip != 'true'
run: |
# Update version with timestamp-based nightly version
node -e "
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('cli/package.json', 'utf8'));
pkg.version = '${{ steps.version.outputs.version }}';
fs.writeFileSync('cli/package.json', JSON.stringify(pkg, null, '\t'));
"
echo "Using version ${{ steps.version.outputs.version }} for build"
cat cli/package.json | grep '"version"'
- name: Download ripgrep binaries
if: steps.check_commits.outputs.skip != 'true'
run: npm run download-ripgrep
- name: Clean previous builds
if: steps.check_commits.outputs.skip != 'true'
run: rm -rf dist-standalone
- name: Generate Protos (First Pass)
if: steps.check_commits.outputs.skip != 'true'
run: npm run protos && npm run protos-go
- name: Compile CLI
if: steps.check_commits.outputs.skip != 'true'
run: npm run compile-cli
- name: Compile CLI for all platforms
if: steps.check_commits.outputs.skip != 'true'
run: npm run compile-cli-all-platforms
- name: Build standalone NPM package
if: steps.check_commits.outputs.skip != 'true'
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
OTEL_TELEMETRY_ENABLED: "1"
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
POSTHOG_TELEMETRY_ENABLED: "true"
run: npm run compile-standalone-npm
- name: Generate Protos (Second Pass - Bug Workaround)
if: steps.check_commits.outputs.skip != 'true'
run: npm run protos && npm run protos-go
- name: Verify build output
if: steps.check_commits.outputs.skip != 'true'
run: |
echo "Checking dist-standalone directory..."
ls -la dist-standalone/
echo "Verifying CLI binaries..."
ls -lh cli/bin/cline-* || echo "Warning: CLI binaries not found"
echo "Checking package.json in dist-standalone..."
cat dist-standalone/package.json | grep version
- name: Publish to NPM with nightly tag
if: steps.check_commits.outputs.skip != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}
run: |
echo "Publishing version ${{ steps.version.outputs.version }} to NPM with tag 'nightly'..."
cd dist-standalone
npm publish --tag nightly --access public
- name: Summary
if: steps.check_commits.outputs.skip != 'true'
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'nightly'"
echo ""
echo "📦 Install with: npm install -g cline@nightly"
echo "🔗 NPM: https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}"
+2 -2
View File
@@ -74,8 +74,8 @@ jobs:
CLINE_ENVIRONMENT: production
# OpenTelemetry production defaults (can be overridden at runtime)
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: console,otlp
OTEL_METRICS_EXPORTER: console,otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
+14 -25
View File
@@ -36,8 +36,6 @@ jobs:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.tag }}
fetch-depth: 0
fetch-tags: true
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -62,11 +60,11 @@ jobs:
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm install --include=optional
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm install --include=optional
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
@@ -101,8 +99,8 @@ jobs:
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
# OpenTelemetry production defaults (can be overridden at runtime)
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: console,otlp
OTEL_METRICS_EXPORTER: console,otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
@@ -118,31 +116,22 @@ jobs:
echo "Successfully published release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
fi
- name: Get Previous Tag
id: prev_tag
run: |
CURRENT_TAG="${{ steps.validate_tag.outputs.tag }}"
PREV_TAG=$(git describe --tags --abbrev=0 "$CURRENT_TAG^" 2>/dev/null || echo "")
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Get Changelog Entry
id: changelog
run: |
# Get content between first ## [ and second ## [
CONTENT=$(awk '/^## \[/{if(found) exit; found=1; next} found{print}' CHANGELOG.md)
echo "content<<EOF" >> $GITHUB_OUTPUT
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# - name: Get Changelog Entry
# id: changelog
# uses: mindsers/changelog-reader-action@v2
# with:
# # This expects a standard Keep a Changelog format
# # "latest" means it will read whichever is the most recent version
# # set in "## [1.2.3] - 2025-01-28" style
# version: latest
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.validate_tag.outputs.tag }}
files: "*.vsix"
body: |
${{ steps.changelog.outputs.content }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.validate_tag.outputs.tag }}
# body: ${{ steps.changelog.outputs.content }}
generate_release_notes: true
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+12 -3
View File
@@ -187,11 +187,20 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
- name: Build CLI binaries
run: npm run compile-cli-all-platforms
- name: Download ripgrep binaries
run: npm run download-ripgrep
- name: Compile Standalone
run: npm run compile-standalone
- name: Compile NPM package
run: npm run compile-standalone-npm
- name: Install testing platform dependencies
if: steps.testing-platform-cache.outputs.cache-hit != 'true'
@@ -204,7 +213,7 @@ jobs:
# This prevents the job from showing as failed and avoids distracting developers
# until the integration tests are ready to be enforced.
run: |
npm run test:tp-orchestrator -- tests/specs/ --count=1 --coverage
npm run test:tp-orchestrator -- tests/specs/ --count=1 --coverage || true
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
+11 -55
View File
@@ -1,26 +1,17 @@
name: Trigger Jetbrains Plugin <-> Cline Tests
on:
pull_request_target:
types: [opened, reopened]
issue_comment:
types: [created]
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
pull-requests: read
concurrency:
group: jetbrains-trigger-${{ github.event.pull_request.number || github.event.issue.number }}
group: jetbrains-trigger-${{ github.event.number }}
cancel-in-progress: true
jobs:
trigger-integration-test:
name: Run Tests
runs-on: ubuntu-latest
# Run on PR open/reopen, or when someone comments /test-jetbrains on a PR
if: |
github.event_name == 'pull_request_target' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '/test-jetbrains'))
steps:
- name: Generate GitHub App Token
id: app-token
@@ -31,39 +22,7 @@ jobs:
owner: cline
repositories: intellij-plugin
- name: Get PR details (for issue_comment trigger)
id: pr-details
if: github.event_name == 'issue_comment'
env:
GH_TOKEN: ${{ github.token }}
run: |
PR_DATA=$(gh api repos/${{ github.repository }}/pulls/${{ github.event.issue.number }})
echo "head_ref=$(echo "$PR_DATA" | jq -r '.head.ref')" >> $GITHUB_OUTPUT
echo "head_sha=$(echo "$PR_DATA" | jq -r '.head.sha')" >> $GITHUB_OUTPUT
echo "title=$(echo "$PR_DATA" | jq -r '.title')" >> $GITHUB_OUTPUT
echo "html_url=$(echo "$PR_DATA" | jq -r '.html_url')" >> $GITHUB_OUTPUT
- name: Sanitize untrusted inputs
id: sanitize
env:
RAW_BRANCH_NAME: ${{ github.event_name == 'pull_request_target' && github.head_ref || steps.pr-details.outputs.head_ref }}
RAW_PR_TITLE: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.title || steps.pr-details.outputs.title }}
run: |
# Sanitize branch name for JSON
BRANCH_NAME_JSON=$(jq -n --arg b "$RAW_BRANCH_NAME" '$b')
echo "branch_name=$BRANCH_NAME_JSON" >> $GITHUB_OUTPUT
# Sanitize PR title for JSON
PR_TITLE_JSON=$(jq -n --arg t "$RAW_PR_TITLE" '$t')
echo "pr_title=$PR_TITLE_JSON" >> $GITHUB_OUTPUT
- name: Trigger IntelliJ Plugin Integration Test
env:
BRANCH_NAME: ${{ steps.sanitize.outputs.branch_name }}
PR_TITLE: ${{ steps.sanitize.outputs.pr_title }}
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
PR_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || steps.pr-details.outputs.head_sha }}
PR_URL: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.html_url || steps.pr-details.outputs.html_url }}
run: |
curl -X POST \
-H "Authorization: Bearer ${{ steps.app-token.outputs.token }}" \
@@ -75,23 +34,20 @@ jobs:
{
"event_type": "cline-pr-check",
"client_payload": {
"pr_number": "$PR_NUMBER",
"branch_name": $BRANCH_NAME,
"pr_number": "${{ github.event.number }}",
"branch_name": "${{ github.head_ref }}",
"action": "${{ github.event.action }}",
"sha": "$PR_SHA",
"pr_title": $PR_TITLE,
"pr_url": "$PR_URL"
"sha": "${{ github.event.pull_request.head.sha }}",
"pr_title": ${{ toJSON(github.event.pull_request.title) }},
"pr_url": "${{ github.event.pull_request.html_url }}"
}
}
EOF
- name: Log trigger details
env:
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
PR_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || steps.pr-details.outputs.head_sha }}
run: |
echo "Triggered IntelliJ Plugin integration test for:"
echo " PR #$PR_NUMBER"
echo " Trigger: ${{ github.event_name }}"
echo " PR #${{ github.event.number }}: ${{ github.event.pull_request.title }}"
echo " Branch: ${{ github.head_ref }}"
echo " Action: ${{ github.event.action }}"
echo " SHA: $PR_SHA"
echo " SHA: ${{ github.event.pull_request.head.sha }}"
-11
View File
@@ -8,14 +8,12 @@ tmp
.DS_Store
.idea
.husky/_/
pnpm-lock.yaml
.clineignore
.venv
.actrc
CLAUDE.local.md
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
@@ -29,10 +27,6 @@ coverage-unit
*evals.env
.env
.secrets
.github/act/.secrets
.worktrees
## Generated files ##
src/generated/
@@ -41,8 +35,3 @@ webview-ui/src/services/grpc-client.ts
# E2E Tests
test-results
/.github/act
/pkg
.secrets
+4 -37
View File
@@ -12,10 +12,7 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
@@ -36,10 +33,7 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
@@ -60,10 +54,7 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
@@ -86,10 +77,7 @@
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync=off",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--disable-extensions", // Avoid conflicts with installed extensions
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
@@ -177,27 +165,6 @@
},
"console": "integratedTerminal",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "Open Storybook",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"storybook"
],
"cwd": "${workspaceFolder}/webview-ui",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"serverReadyAction": {
"pattern": "Local:.*http://localhost:([0-9]+)",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
},
"env": {
"IS_DEV": "true"
}
}
]
}
+1 -3
View File
@@ -27,7 +27,5 @@
"source.removeUnused.biome": "always",
"source.removeUnusedImports": "always",
"source.organizeImports.biome": "always"
},
// Disable auto-forwarding ports to prevent Simple Browser from opening the Vite dev server
"remote.autoForwardPorts": false
}
}
-20
View File
@@ -263,26 +263,6 @@
"watch"
],
"command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user"
},
{
"type": "npm",
"script": "storybook",
"group": "build",
"problemMatcher": [],
"isBackground": false,
"label": "npm: storybook",
"dependsOn": [
"npm: protos",
"npm: build:webview"
],
"presentation": {
"reveal": "always"
},
"options": {
"env": {
"IS_DEV": "true"
}
}
}
],
"inputs": [
+3 -2
View File
@@ -1,8 +1,6 @@
# Default
.vscode/**
.vscode-test/**
.worktrees/**
CLAUDE.local.md
out/
dist-standalone/
node_modules/
@@ -42,6 +40,9 @@ buf.yaml
.changeset/
.clinerules/
# Include specific file needed for Background Exec mode
!standalone/runtime-files/vscode/enhanced-terminal.js
# Ignore all webview-ui files except the build directory (https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/frameworks/hello-world-react-cra/.vscodeignore)
webview-ui/src/**
webview-ui/public/**
-1
View File
@@ -1 +0,0 @@
.gitignore
+6 -293
View File
@@ -1,301 +1,14 @@
# Changelog
## [3.52.0]
## 3.37.1
### Added
- Users with ChatGPT Plus or Pro subscriptions can now use GPT-5 models directly through Cline without needing an API key. Authentication is handled via OAuth through OpenAI's authentication system.
- Grok models are now moving out of free tier and into paid plans.
- Introduces comprehensive Jupyter Notebook support for Cline, enabling AI-assisted editing of `.ipynb` files with full cell-level context awareness.
### Fixed
- Bugs in DiffViewProvider for file editing
- Ollama's recommended models to use correct identifiers
## [3.51.0]
### Added
- Adding OpenAI gpt-5.2-codex model to the model picker
## [3.50.0]
### Added
- Add gpt-5.2-codex OpenAI model support
- Add create-pull-request skill
### Fixed
- Fix the selection of remotely configured providers
- Fix act_mode_respond to prevent consecutive calls
- Fix invalid tool call IDs when switching between model formats
## [3.49.1]
### Added
- Add telemetry to track usage of skills feature
- Add version headers to Cline backend requests
- Phase in Responses API usage instead of defaulting for every supported model
### Fixed
- Fix workflow slash command search to be case-insensitive
- Fix model display in ModelPickerModal when using LiteLLM
- Fix LiteLLM model fetching with default base URL
- Fix crash when OpenAI-compatible APIs send usage chunks with empty or null choices arrays at end of streaming
- Fix model ID for Kat Coder Pro Free model
## [3.49.0]
- Enable configuring an OTEL collector at runtime
- Removing Minimax-2.1 from free model list as the free trial has ended
- Improved image display in MCP responses
- Auto-sync remote MCP servers from remote config to local settings
## [3.48.0]
### Added
- Add Skills system for reusable, on-demand agent instructions
- Add new websearch tooling in Cline provider
- Add zai-glm-4.7 to Cerebras model list
- Add model refresh and improve reasoning support for Vercel AI Gateway
### Fixed
- Revert #8341 due to regressions in diff view/document truncation (see #8423, #8429)
- Fixed extension crash when using context menu selector
## [3.47.0]
### Added
- Added experimental support for Background Edits (allows editing files in background without opening the diff view)
- Updated free model to MiniMax M2.1 (replacing MiniMax M2)
- Added support for Azure based identity authentication in OpenAI Compatible provider and Azure OpenAI
- Add `supportsReasoning` property to Baseten models
### Fixed
- Prevent expired token usage in authenticated requests
- Exclude binary files without extensions from diffs
- Preserve file endings and trailing newlines
- Fix Cerebras rate limiting
- Fix Auto Compact for Claude Code provider
- Make Workspace and Favorites history filters independent
- Fix remote MCP server connection failures (404 response handling)
- Disable native tool calling for Deepseek 3.2 speciale
- Show notification instead of opening sidebar on update
- Fix Baseten model selector
### Refactored
- Modify prompts for parallel tool usage in Claude and Gemini 3 models
## [3.46.1]
### Fixed
- Remove GLM 4.6 from free models
## [3.46.0]
### Added
- Added GLM 4.7 model
- Enhanced background terminal execution with command tracking, log file output, zombie process prevention (10-minute timeout), and clickable log paths in UI
- Apply Patch tool for GPT-5+ models (replacing current diff edit tools)
### Fixed
- Duplicate error messages during streaming for Diff Edit tool when Parallel Tool Calling is not enabled
- Banner carousel styling and dismiss functionality
- Typos in Gemini system prompt overrides
- Model picker favorites ordering, star toggle, and keyboard navigation for OpenRouter and Vercel AI Gateway providers
- Fetch remote config values from the cache
### Refactored
- Anthropic handler to use metadata for reasoning support
- Bedrock provider to use metadata for reasoning support
## [3.45.1]
- Fixed MCP settings race condition where toggling auto-approve or changing timeout settings would cause the UI to flash and revert
## [3.45.0]
- Added Gemini 3 Flash Preview model
## [3.44.2]
- Polished the model picker UI with checkmarks for selected models, tooltips on Plan/Act tabs, and consistent arrow pointers across all popup modals
- Improved WhatsNew modal responsiveness and cleaned up redundant UI elements
- Fixed GLM models outputting garbled text in thinking tags—reasoning is now properly disabled for these models
## [3.44.1]
- Fixed a critical bug where local MCP servers stopped connecting after v3.42.0—all user-configured stdio-based MCP servers should now work again
- Fixed remotely configured API keys not being extracted correctly for enterprise users
- Added support for dynamic tool instructions that adapt based on runtime context, laying groundwork for future context-aware features
## [3.44.0]
## Added
- Updating minor version to show a proper banner for the release
## [3.43.1]
### Patch Changes
- Fix GLM-4.6 Model reference id
## [3.43.0]
### Added
- GLM-4.6
- kat-coder-pro
- Add parsing of env variable patterns to the mcpconfig.json
### Fixed
- TLS Proxy support issues for VSCode
- Add supportsReasoning flag to OpenAI reasoning models
- Fix thinking not available for some models in the OpenAI provider
- Fix invalid signature field issues when switching between Gemini and Anthropic providers
- Extract OpenRouter model filtering into reusable utility and use it in different model pickers
- Fix a11y for auto approve checkbox
- Improve ModelPickerModal provider list layout
### Refactored
- Migrate WhatsNewModal to new shared dialogue component
## [3.42.0]
### Added
- Expose `getAvailableSlashCommands` rpc endpoint to UI clients
- Made slash command menu and context menu accessible and screenreader-friendly
- Made expanding/collapsing UI components accessible
### Fixed
- Devstral OpenRouter model ID and routing issues
- Incorrect pricing display for Devstral model in the extension
## [3.41.0]
### Added
- OpenAI GPT-5.2
- Devstral-2512 (formerly stealth model "Microwave")
- Improvements to chat modal model picker
- Amazon Nova 2 Lite
- DeepSeek 3.2 to native tool calling allow list
- Responses API support for Codex models in OpenAI provider (requires native tool calling)
- Xmas Special Santa Cline
- Welcome screen UI enhancements
### Fixed
- Initial checkpoint commit now non-blocking for improved responsiveness in large repositories
- Gemini Vertex models erroring when thinking parameters are not supported
- Restrictive file permissions for secrets.json
- Ollama streaming requests not aborting when task is cancelled
### Refactored
- OpenAI provider to centralize temperature configuration and include missing GPT-5 model settings
- OpenAI native handler to use metadata for model capabilities
- Vertex provider to use metadata for model capabilities
## [3.40.2]
- Fix logout on network errors during token refresh (e.g., opening laptop while offline)
## [3.40.1]
- Fix cost calculation display for Anthropic API requests
## [3.40.0]
- Fix highlighted text flashing when task header is collapsed
- Add X-Cerebras-3rd-Party-Integration header to Cerebras API requests
- Add microwave family system prompt configuration
- Remove tooltips from auto approve menu
- Fix Standalone, ensure cwd is the install dir to find resources reliably
- Fix a bug where terminal commands with double quotes are broken when "Terminal Execution Mode" is set to "Background Exec"
- Add support for slash commands anywhere in a message, not just at the beginning. This matches the behavior of @ mentions for a more flexible input experience.
- Add bottom padding to the last message to fix last response text getting cut off by auto approve settings bar.
- Add default thinking level for Gemini 3 Pro models in Gemini provider
## [3.39.2]
- Fix for microwave model and thinking settings
## [3.39.1]
- Fix Openrouter and Cline Provider model info
## [3.39.0]
- Add Explain Changes feature
- Add microwave Stealth model
- Add Tabbed Model Picker with Recommended and Free tabs
- Add support to View remote rules and workflows in the editor
- Enable NTC (Native Tool Calling) by default
- Bug fixes and improvements for LiteLLM provider
## [3.38.3]
- Task export feature now opens the task directory, allowing easy access to the full task files
- Add Grok 4.1 and Grok Code to XAI provider
- Enabled native tool calling for Baseten and Kimi K2 models
- Add thinking level to Gemini 3.0 Pro preview
- Expanded Hooks functionality
- Removed Task Timeline from Task Header
- Bug fix for slash commands
- Bug fixes for Vertex provider
- Bug fixes for thinking/reasoning issues across multiple providers when using native tool calling
- Bug fixes for terminal usage on Windows devices
## [3.38.2]
- Add Claude Opus 4.5
## [3.38.1]
### Fixed
- Fixed handling of 'signature' field in sanitizeAnthropicContentBlock to properly preserve it when thinking is enabled, as required by Anthropic's API.
## [3.38.0]
### Added
- Gemini 3 Pro Preview model
- AquaVoice Avalon model for voice-to-text dictation
### Fixed
- Automatic context truncation when AWS Bedrock token usage rate limits are exceeded
- Removed new_task tool from system prompts, updated slash command prompts, and added helper function for native tool calling validation
## [3.37.1]
- Comprehensive changes to better support GPT 5.1 - System prompt, tools, deep-planning, focus chain, etc.
- Add AGENTS.md support
- feat(models): Add free minimax/mimax-m2 model to the model picker
- cf8dd1c: Comprehensive changes to better support GPT 5.1 - System prompt, tools, deep-planning, focus chain, etc.
- 02abbcf: Add AGENTS.md support
- 855db7d: feat(models): Add free minimax/mimax-m2 model to the model picker
## [3.37.0]
### Added
## Added
- GPT-5.1 with model-specific prompting: tailored system prompts, tool usage, focus chain, and deep-planning optimizations
- Nous Research provider with Hermes 4 model family and custom system prompts
@@ -305,7 +18,7 @@
- Expanded HTTP proxy support throughout the codebase
- Improved focus chain prompting for frontier models (Anthropic, OpenAI, Gemini, xAI)
### Fixed
## Fixed
- Duplicate tool results prevention through existence checking
- XML entity escaping in model content processor
-2
View File
@@ -1,2 +0,0 @@
@.clinerules/general.md
@.clinerules/network.md
-5
View File
@@ -141,11 +141,6 @@ For example, when working with a local web server, you can use 'Restore Workspac
To contribute to the project, start with our [Contributing Guide](CONTRIBUTING.md) to learn the basics. You can also join our [Discord](https://discord.gg/cline) to chat with other contributors in the `#contributors` channel. If you're looking for full-time work, check out our open positions on our [careers page](https://cline.bot/join-us)!
## Enterprise
Get the same Cline experience with enterprise-grade controls: SSO (SAML/OIDC), global policies and configuration, observability with audit trails, private networking (VPC/private link), and self-hosted or on-prem deployments, and enterprise support. Learn more at our [enterprise page](https://cline.bot/enterprise) or [talk to us](https://cline.bot/contact-sales).
## License
[Apache 2.0 © 2025 Cline Bot Inc.](./LICENSE)
-30
View File
@@ -1,30 +0,0 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
<svg xmlns="http://www.w3.org/2000/svg">
<metadata>
<json>
<![CDATA[
{
"fontFamily": "cline-bot",
"majorVersion": 1,
"minorVersion": 0,
"fontURL": "https://cline.bot",
"designerURL": "https://cline.bot",
"licenseURL": "https://cline.bot",
"version": "Version 1.0",
"fontId": "cline-bot",
"psName": "cline-bot",
"subFamily": "Regular",
"fullName": "cline-bot",
"description": "Font generated by IcoMoon."
}
]]>
</json>
</metadata>
<defs>
<font id="cline-bot" horiz-adv-x="1024">
<font-face units-per-em="1024" ascent="960" descent="-64" />
<missing-glyph horiz-adv-x="1024" />
<glyph unicode="&#x20;" horiz-adv-x="512" d="" />
<glyph unicode="&#xe900;" glyph-name="cline" data-tags="cline" horiz-adv-x="977" d="M964.553 383.11l-60.285 121.406v69.495c0 115.545-92.939 209.321-207.647 209.321h-102.986c7.536 15.071 11.722 32.654 11.722 51.074 0 64.471-51.912 116.383-115.545 116.383s-115.545-51.912-115.545-116.383 4.186-35.166 11.722-51.074h-102.986c-114.708 0-207.647-93.776-207.647-209.321v-69.495l-61.959-121.406c-5.861-11.722-5.861-26.793 0-38.515l61.959-119.732v-69.495c0-115.545 92.939-209.321 207.647-209.321h415.294c114.708 0 207.647 93.776 207.647 209.321v69.495l60.285 119.732c5.861 11.722 5.861 25.956 0 38.515v0zM426.178 284.311c0-52.749-42.702-95.451-94.613-95.451s-94.613 42.702-94.613 95.451v169.132c0 52.749 42.702 95.451 94.613 95.451s94.613-42.702 94.613-95.451v-169.132zM731.787 284.311c0-52.749-42.702-95.451-94.613-95.451s-94.613 42.702-94.613 95.451v169.132c0 52.749 42.702 95.451 94.613 95.451s94.613-42.702 94.613-95.451v-169.132z" />
</font></defs></svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.
-1
View File
@@ -70,4 +70,3 @@ Apache-2.0 - see [LICENSE](https://github.com/cline/cline/blob/main/LICENSE) for
- Report issues: [GitHub Issues](https://github.com/cline/cline/issues)
- Community: [GitHub Discussions](https://github.com/cline/cline/discussions)
- Documentation: [docs.cline.bot](https://docs.cline.bot)
- Cline CLI Architecture: [architecture.md](./architecture.md)
-292
View File
@@ -1,292 +0,0 @@
# Cline CLI Architecture
The CLI is a **standalone terminal interface** for the Cline AI coding assistant, written in Go. It provides the same autonomous coding capabilities as the VS Code extension but runs entirely in the terminal.
## High-Level Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
│ User Terminal │
└─────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ cline (Go binary) │
│ cmd/cline/main.go │
│ • Cobra CLI commands (task, auth, config, instance, etc.) │
│ • Interactive input via Bubble Tea │
│ • Streaming output with markdown rendering │
└─────────────────────────────────────────────────────────────────────────┘
│ gRPC (50052) │ starts subprocess
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐
│ cline-core │◄────────────────►│ cline-host │
│ (Node.js) │ gRPC (51052) │ (Go binary) │
│ │ │ cmd/cline-host/main.go│
│ • AI/LLM orchestration │ │ │
│ • Tool execution │ │ • Workspace paths │
│ • Task state mgmt │ │ • File diff editing │
│ • Message handling │ │ • Clipboard access │
└─────────────────────────┘ │ • Environment info │
│ └─────────────────────────┘
│ SQLite (self-registration)
┌─────────────────────────────────────────────────────────────────────────┐
│ ~/.cline/data/locks/locks.db │
│ (Instance registry - core self-registers on startup) │
└─────────────────────────────────────────────────────────────────────────┘
```
## Entry Points (`cmd/`)
### `cmd/cline/main.go` - Main CLI
Cobra-based CLI with commands:
- **Root**: `cline [prompt]` - Start a task directly
- **task**: Create, send, view, list, pause, restore tasks
- **auth**: Authentication setup and provider configuration
- **config**: Read/write settings
- **instance**: Manage running Cline instances
- **logs**: View and clean log files
- **doctor**: System health check
### `cmd/cline-host/main.go` - Host Bridge Service
Separate gRPC server providing host environment operations to cline-core:
- Workspace paths
- File diff editing
- Clipboard access
- Shutdown coordination
---
## `pkg/cli/` Subsystems
### 1. `auth/` - Authentication System
Handles authentication with Cline service and BYO (Bring Your Own) API providers.
| File | Purpose |
| ------------------------- | ------------------------------------------------------------------------ |
| `auth_cline_provider.go` | OAuth login flow - opens browser, subscribes to auth callback stream |
| `auth_menu.go` | Interactive menu showing auth options based on current state |
| `auth_subscription.go` | gRPC stream subscription for auth status updates |
| `wizard_byo.go` | Interactive wizard for configuring BYO providers |
| `wizard_byo_bedrock.go` | AWS Bedrock-specific credential setup |
| `wizard_byo_oca.go` | Oracle Code Assist setup |
| `providers_list.go` | Retrieves configured providers from core state |
| `providers_byo.go` | Provider selection UI and field configuration |
| `models_*.go` | Model listing (static lists + dynamic fetch from OpenRouter/OpenAI/Ollama) |
**Flow**: User runs `cline auth` → Menu shows options → For BYO: wizard guides through provider/key/model selection → Config saved via gRPC to core.
---
### 2. `clerror/` - Error Handling
Parses and classifies API errors from the Cline service.
**Error Types:**
- `ErrorTypeAuth` - 401, bad API key
- `ErrorTypeBalance` - Insufficient credits
- `ErrorTypeRateLimit` - 429, quota exceeded
- `ErrorTypeNetwork` - Connection issues
- `ErrorTypeUnknown` - Catch-all
Extracts billing details (balance, spent, buy credits URL) from error responses.
---
### 3. `config/` - Configuration Management
| File | Purpose |
| --------------------- | -------------------------------------------------------------------------- |
| `manager.go` | gRPC interface for reading/writing settings via `UpdateSettingsCli` RPC |
| `settings_renderer.go`| Pretty-prints config values, censors sensitive fields (keys, secrets) |
Supports dot-notation paths: `cline config get auto-approval-settings.actions.read-files`
---
### 4. `display/` - Terminal Display System
The most complex subsystem - handles all visual output.
| File | Purpose |
| ----------------------- | -------------------------------------------------------------------- |
| `renderer.go` | Central coordinator with lipgloss styles, color methods, markdown delegation |
| `streaming.go` | Real-time streaming display with deduplication |
| `segment_streamer.go` | Streaming segments (header + body) with context-aware headers |
| `typewriter.go` | Character-by-character animation with variable delays |
| `markdown_renderer.go` | Glamour wrapper for terminal markdown rendering |
| `tool_renderer.go` | Tool operation formatting ("Cline is editing `file.ts`") |
| `tool_result_parser.go` | Parses structured tool results (file lists, search results) |
| `banner.go` | Session startup banner with version/model/workspace |
| `deduplicator.go` | MD5-based deduplication with 2-second window |
| `system_renderer.go` | Rich error/warning boxes for balance errors, auth failures |
| `ansi.go` | TTY detection, line clearing with escape codes |
---
### 5. `global/` - Global State Management
| File | Purpose |
| ------------------ | -------------------------------------------------------------------------- |
| `global.go` | Global config (paths, verbosity, output format), initialization |
| `registry.go` | Instance discovery via SQLite, health checking, default instance management|
| `cline-clients.go` | Starts cline-core + cline-host processes, port allocation, cleanup |
**Instance lifecycle:**
1. Find available port pair
2. Start `cline-host` on port+1000
3. Start `cline-core` on port
4. Wait for core to self-register in SQLite
5. Set as default if first instance
---
### 6. `handlers/` - Message Handlers
Routes incoming messages from cline-core to appropriate renderers.
| File | Purpose |
| ------------------ | --------------------------------------------------------------------- |
| `handler.go` | Handler registry with priority-based routing |
| `ask_handlers.go` | Approval requests: tool, command, followup, api_req_failed, etc. |
| `say_handlers.go` | Status messages: text, reasoning, command_output, tool, checkpoint, etc. |
Uses `DisplayContext` providing renderer access, state, and context flags (isLast, isPartial, isStreamingMode).
---
### 7. `output/` - Output Coordination
| File | Purpose |
| --------------------- | ----------------------------------------------------------------------- |
| `coordinator.go` | Coordinates streaming output with interactive input (saves/restores input state) |
| `input_model.go` | Bubble Tea model for rich input (message, approval, feedback types) |
| `slash_completion.go` | Autocomplete dropdown for slash commands |
**Key pattern:** When output needs to print while input is visible, the coordinator saves input state, clears the form, prints, then restores input.
---
### 8. `slash/` - Slash Command Registry
Central registry for commands like `/plan`, `/act`, `/cancel`:
- **CLI-local commands**: Handled directly by CLI
- **Backend commands**: Fetched from core via gRPC, filtered by `CliCompatible` flag
---
### 9. `sqlite/` - Instance Locking
Manages the distributed locking system:
- **Instance locks**: Track running Cline instances by address
- **File locks**: Coordinate file access across instances
- SQLite database created by cline-core, CLI reads/writes for discovery
---
### 10. `task/` - Task Management
| File | Purpose |
| ----------------------- | -------------------------------------------------------------------- |
| `manager.go` | Core orchestrator: create, cancel, resume, restore tasks; stream handling |
| `stream_coordinator.go` | Deduplication and turn management for dual streams |
| `input_handler.go` | Interactive input during follow mode (polling, approval detection) |
| `history_handler.go` | Direct disk access to `taskHistory.json` |
| `settings_parser.go` | Parse settings from CLI flags |
| `follow_options.go` | Configuration for follow behavior |
**Streaming:** Task manager subscribes to two gRPC streams:
1. `SubscribeToState` - Full state updates
2. `SubscribeToPartialMessage` - Streaming AI responses
---
### 11. `terminal/` - Terminal Handling
Enhanced keyboard protocol support and terminal configuration:
- Enables modifyOtherKeys and Kitty keyboard protocol
- Detects terminal type (VS Code, iTerm, Ghostty, Kitty, etc.)
- Auto-configures shift+enter keybindings for various terminals
---
### 12. `types/` - Type Definitions
| File | Purpose |
| -------------- | ----------------------------------------------------------------- |
| `messages.go` | `ClineMessage`, `AskType`, `SayType`, `ToolType` enums, proto conversion |
| `state.go` | `ConversationState` with thread-safe message access |
| `history.go` | `HistoryItem` matching taskHistory.json format |
---
### 13. `updater/` - Auto-Update
Background auto-update checking:
- 24-hour check interval (cached)
- Queries npm registry for newer versions
- Supports `latest` and `nightly` channels
- Runs `npm install -g cline` to update
---
## `pkg/common/` - Shared Types
| File | Purpose |
| --------------- | ------------------------------------------------------------ |
| `constants.go` | `SETTINGS_SUBFOLDER`, `DEFAULT_CLINE_CORE_PORT` |
| `schema.go` | SQL queries for instance/file locks |
| `types.go` | `CoreInstanceInfo`, `LockRow`, `DefaultCoreInstance` |
| `utils.go` | Port checking, health checks, address normalization, retry logic |
---
## `pkg/generated/` - Auto-Generated
| File | Purpose |
| --------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `providers.go` | Provider definitions (Anthropic, OpenAI, Bedrock, etc.) with field metadata and model specs - generated from TypeScript sources |
| `field_overrides.go` | Manual overrides for field filtering |
---
## `pkg/hostbridge/` - CLI-to-Core Bridge
This is the **reverse bridge** allowing cline-core to request host environment operations:
| File | Purpose |
| ----------------------- | ---------------------------------------------------- |
| `grpc_server.go` | Main server registering all services |
| `simple_workspace.go` | Workspace service: returns CWD as workspace path |
| `diff.go` | In-memory file diff editing with line-based operations |
| `env.go` | Clipboard access, version info, shutdown coordination |
| `window.go` | UI stubs (no-ops or console output) |
**Why this exists:** The same cline-core logic runs in VS Code and CLI. In VS Code, the "host" is the extension with editor APIs. In CLI, hostbridge emulates these capabilities with terminal-appropriate implementations.
---
## Key Design Decisions
1. **Two-process model:** `cline` CLI manages instances; `cline-core` is the actual AI engine (Node.js). This allows reusing the same core as the VS Code extension.
2. **Self-registration via SQLite:** `cline-core` registers itself in a SQLite database on startup. The CLI discovers instances by reading this database, enabling multi-instance support.
3. **Host bridge abstraction:** The `cline-host` process provides platform-specific operations (clipboard, workspace paths) via gRPC, allowing `cline-core` to remain host-agnostic.
4. **Streaming-first UI:** The CLI uses gRPC streaming to display AI responses in real-time with typewriter-style rendering.
5. **Dual stream handling:** Task manager subscribes to both state updates and partial messages, using deduplication to prevent duplicate rendering.
+3 -5
View File
@@ -14,9 +14,8 @@ import (
)
var (
port int
verbose bool
workspaces []string
port int
verbose bool
)
func main() {
@@ -29,7 +28,6 @@ func main() {
rootCmd.Flags().IntVarP(&port, "port", "p", 51052, "port to listen on")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "verbose logging")
rootCmd.Flags().StringSliceVar(&workspaces, "workspace", nil, "workspace paths")
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
@@ -41,7 +39,7 @@ func runServer(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Create gRPC hostbridge service
service := hostbridge.NewGrpcServer(port, verbose, workspaces)
service := hostbridge.NewGrpcServer(port, verbose)
// Handle graceful shutdown
ctx, cancel := context.WithCancel(ctx)
+105 -142
View File
@@ -6,16 +6,14 @@ import (
"fmt"
"io"
"os"
"slices"
"strings"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli"
"github.com/cline/cli/pkg/cli/auth"
"github.com/cline/cli/pkg/cli/display"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/slash"
"github.com/cline/cli/pkg/common"
"github.com/cline/grpc-go/cline"
"github.com/spf13/cobra"
@@ -27,20 +25,18 @@ var (
outputFormat string
// Task creation flags (for root command)
images []string
files []string
mode string
settings []string
yolo bool
oneshot bool
workspaces []string
images []string
files []string
mode string
settings []string
yolo bool
oneshot bool
)
func main() {
rootCmd := &cobra.Command{
Use: "cline [prompt]",
Short: "Cline CLI - AI-powered coding assistant",
Version: global.CliVersion,
Use: "cline [prompt]",
Short: "Cline CLI - AI-powered coding assistant",
Long: `A command-line interface for interacting with Cline AI coding assistant.
Start a new task by providing a prompt:
@@ -72,29 +68,20 @@ see the manual page: man cline`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Validate workspace paths exist
if err := common.ValidateDirsExist(workspaces); err != nil {
return err
}
// Build the full workspace list: cwd first, then additional workspaces
allWorkspaces, err := buildWorkspaceList(workspaces)
if err != nil {
return fmt.Errorf("failed to build workspace list: %w", err)
}
var instanceAddress string
// If --address flag not provided, start instance BEFORE getting prompt
if !cmd.Flags().Changed("address") {
if global.Config.Verbose {
fmt.Println("Starting new Cline instance...")
}
instance, err := global.Instances.StartNewInstance(ctx, allWorkspaces...)
instance, err := global.Clients.StartNewInstance(ctx)
if err != nil {
return fmt.Errorf("failed to start new instance: %w", err)
}
global.Config.CoreAddress = instance.CoreAddress
instanceAddress = instance.Address
if global.Config.Verbose {
fmt.Printf("Started instance at %s\n\n", global.Config.CoreAddress)
fmt.Printf("Started instance at %s\n\n", instanceAddress)
}
// Set up cleanup on exit
@@ -102,35 +89,38 @@ see the manual page: man cline`,
if global.Config.Verbose {
fmt.Println("\nCleaning up instance...")
}
registry := global.Instances.GetRegistry()
if err := global.KillInstanceByAddress(context.Background(), registry, global.Config.CoreAddress); err != nil {
registry := global.Clients.GetRegistry()
if err := global.KillInstanceByAddress(context.Background(), registry, instanceAddress); err != nil {
if global.Config.Verbose {
fmt.Printf("Warning: Failed to clean up instance: %v\n", err)
}
}
}()
}
// Check if user has credentials configured
if !isUserReadyToUse(ctx) {
// Create renderer for welcome messages
renderer := display.NewRenderer(global.Config.OutputFormat)
fmt.Printf("\n%s\n\n", renderer.Dim("Hey there! Looks like you're new here. Let's get you set up"))
// Check if user has credentials configured
if !isUserReadyToUse(ctx, instanceAddress) {
// Create renderer for welcome messages
renderer := display.NewRenderer(global.Config.OutputFormat)
fmt.Printf("\n%s\n\n", renderer.Dim("Hey there! Looks like you're new here. Let's get you set up"))
if err := auth.HandleAuthMenuNoArgs(ctx); err != nil {
// Check if user cancelled - exit cleanly
if err == huh.ErrUserAborted {
return nil
if err := auth.HandleAuthMenuNoArgs(ctx); err != nil {
// Check if user cancelled - exit cleanly
if err == huh.ErrUserAborted {
return nil
}
return fmt.Errorf("auth setup failed: %w", err)
}
return fmt.Errorf("auth setup failed: %w", err)
}
// Re-check after auth wizard
if !isUserReadyToUse(ctx) {
return fmt.Errorf("credentials still not configured - please run 'cline auth' to complete setup")
}
// Re-check after auth wizard
if !isUserReadyToUse(ctx, instanceAddress) {
return fmt.Errorf("credentials still not configured - please run 'cline auth' to complete setup")
}
fmt.Printf("\n%s\n\n", renderer.Dim("✓ Setup complete, you can now use the Cline CLI"))
fmt.Printf("\n%s\n\n", renderer.Dim("✓ Setup complete, you can now use the Cline CLI"))
}
} else {
// User specified --address flag, use that
instanceAddress = coreAddress
}
// Get content from both args and stdin
@@ -139,13 +129,10 @@ see the manual page: man cline`,
return fmt.Errorf("failed to read prompt: %w", err)
}
// If no prompt (or just a mode switch with no message), show interactive input
// Loop to allow mode switches without a message
bannerShown := false
for prompt == "" {
// Pass the mode flag and workspaces to banner so it shows correct info
prompt, err = promptForInitialTask(ctx, mode, allWorkspaces, !bannerShown)
bannerShown = true
// If no prompt from args or stdin, show interactive input
if prompt == "" {
// Pass the mode flag to banner so it shows correct mode
prompt, err = promptForInitialTask(ctx, instanceAddress, mode)
if err != nil {
// Check if user cancelled - exit cleanly without error
if err == huh.ErrUserAborted {
@@ -153,23 +140,6 @@ see the manual page: man cline`,
}
return err
}
// Check if user entered a mode switch command
if newMode, remaining, isModeSwitch := slash.ParseModeSwitch(prompt); isModeSwitch {
mode = newMode
prompt = remaining
// If just a mode switch with no message, continue loop to re-prompt
if prompt == "" {
renderer := display.NewRenderer(global.Config.OutputFormat)
if mode == "act" {
fmt.Printf("\n%s\n\n", renderer.Success("Switched to act mode"))
} else {
fmt.Printf("\n%s\n\n", renderer.Success("Switched to plan mode"))
}
continue
}
}
if prompt == "" {
return fmt.Errorf("prompt required")
}
@@ -182,20 +152,17 @@ see the manual page: man cline`,
}
return cli.CreateAndFollowTask(ctx, prompt, cli.TaskOptions{
Images: images,
Files: files,
Mode: mode,
Settings: settings,
Yolo: yolo,
Address: global.Config.CoreAddress,
Verbose: verbose,
Workspaces: allWorkspaces,
Images: images,
Files: files,
Mode: mode,
Settings: settings,
Yolo: yolo,
Address: instanceAddress,
Verbose: verbose,
})
},
}
rootCmd.SetVersionTemplate(cli.VersionString())
rootCmd.PersistentFlags().StringVar(&coreAddress, "address", fmt.Sprintf("localhost:%d", common.DEFAULT_CLINE_CORE_PORT), "Cline Core gRPC address")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "F", "rich", "output format (rich|json|plain)")
@@ -208,7 +175,6 @@ see the manual page: man cline`,
rootCmd.Flags().BoolVarP(&yolo, "yolo", "y", false, "enable yolo mode (non-interactive)")
rootCmd.Flags().BoolVar(&yolo, "no-interactive", false, "enable yolo mode (non-interactive)")
rootCmd.Flags().BoolVarP(&oneshot, "oneshot", "o", false, "full autonomous mode")
rootCmd.Flags().StringSliceVarP(&workspaces, "workspace", "w", nil, "additional workspace paths (can be specified multiple times)")
rootCmd.AddCommand(cli.NewTaskCommand())
rootCmd.AddCommand(cli.NewInstanceCommand())
@@ -223,30 +189,51 @@ see the manual page: man cline`,
}
}
func promptForInitialTask(ctx context.Context, modeFlag string, workspaces []string, showBanner bool) (string, error) {
// Show session banner before the initial input (only on first prompt)
if showBanner {
showSessionBanner(ctx, modeFlag, workspaces)
func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string) (string, error) {
// Show session banner before the initial input
showSessionBanner(ctx, instanceAddress, modeFlag)
var prompt string
// Create custom theme with mode-colored cursor and title
theme := huh.ThemeCharm()
// Set cursor and title color based on mode
modeColor := lipgloss.Color("3") // Yellow for plan
if modeFlag == "act" {
modeColor = lipgloss.Color("39") // Blue for act
}
prompt, err := output.PromptForInitialTask(
"Start a new Cline task",
"/plan or /act to switch modes\ntab to autocomplete commands\nctrl+e to open editor\nctrl+c to exit",
modeFlag,
slash.NewRegistry(ctx),
)
theme.Focused.TextInput.Cursor = theme.Focused.TextInput.Cursor.Foreground(modeColor)
theme.Focused.Title = theme.Focused.Title.Foreground(modeColor)
form := huh.NewForm(
huh.NewGroup(
huh.NewText().
Title("Start a new Cline task").
Description("What would you like Cline to help you with?").
Placeholder("e.g., Create a REST API with authentication...").
Lines(5).
Value(&prompt),
),
).WithWidth(48).WithTheme(theme)
err := form.Run()
if err != nil {
if err == output.ErrUserAborted {
// Check if user cancelled with Control-C
if err == huh.ErrUserAborted {
// Return a special error that indicates clean cancellation
// This allows deferred cleanup to run
return "", huh.ErrUserAborted
}
return "", err
}
return prompt, nil
return strings.TrimSpace(prompt), nil
}
// showSessionBanner displays session info before initial prompt
func showSessionBanner(ctx context.Context, modeFlag string, workspaces []string) {
func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string) {
bannerInfo := display.BannerInfo{
Version: global.CliVersion,
Mode: modeFlag, // Use the mode from command flag, not state
@@ -257,21 +244,27 @@ func showSessionBanner(ctx context.Context, modeFlag string, workspaces []string
bannerInfo.Mode = "plan"
}
bannerInfo.Workdirs = workspaces
// Get current working directory (this is what Cline will use)
if cwd, err := os.Getwd(); err == nil {
bannerInfo.Workdir = cwd
}
// Get provider/model using auth functions (same logic as auth menu)
if providerList, err := auth.GetProviderConfigurations(ctx); err == nil {
// Show provider/model for the mode we'll be using
var providerDisplay *auth.ProviderDisplay
if bannerInfo.Mode == "plan" && providerList.PlanProvider != nil {
providerDisplay = providerList.PlanProvider
} else if bannerInfo.Mode == "act" && providerList.ActProvider != nil {
providerDisplay = providerList.ActProvider
}
manager, err := cli.NewTaskManagerForAddress(ctx, instanceAddress)
if err == nil {
if providerList, err := auth.GetProviderConfigurations(ctx, manager); err == nil {
// Show provider/model for the mode we'll be using
var providerDisplay *auth.ProviderDisplay
if bannerInfo.Mode == "plan" && providerList.PlanProvider != nil {
providerDisplay = providerList.PlanProvider
} else if bannerInfo.Mode == "act" && providerList.ActProvider != nil {
providerDisplay = providerList.ActProvider
}
if providerDisplay != nil {
bannerInfo.Provider = auth.GetProviderIDForEnum(providerDisplay.Provider)
bannerInfo.ModelID = providerDisplay.ModelID
if providerDisplay != nil {
bannerInfo.Provider = auth.GetProviderIDForEnum(providerDisplay.Provider)
bannerInfo.ModelID = providerDisplay.ModelID
}
}
}
@@ -284,22 +277,25 @@ func showSessionBanner(ctx context.Context, modeFlag string, workspaces []string
// isUserReadyToUse checks if the user has completed initial setup
// Returns true if welcomeViewCompleted flag is set OR user is authenticated
// Matches extension logic: welcomeViewCompleted = Boolean(globalState.welcomeViewCompleted || user?.uid)
func isUserReadyToUse(ctx context.Context) bool {
grpcClient, err := global.GetClientForAddress(ctx, global.Config.CoreAddress)
func isUserReadyToUse(ctx context.Context, instanceAddress string) bool {
manager, err := cli.NewTaskManagerForAddress(ctx, instanceAddress)
if err != nil {
return false
}
state, err := grpcClient.State.GetLatestState(ctx, &cline.EmptyRequest{})
// Get state
state, err := manager.GetClient().State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return false
}
// Parse state JSON
stateMap := make(map[string]interface{})
if err := json.Unmarshal([]byte(state.StateJson), &stateMap); err != nil {
return false
}
// Check 1: welcomeViewCompleted flag
if welcomeCompleted, ok := stateMap["welcomeViewCompleted"].(bool); ok && welcomeCompleted {
return true
}
@@ -349,37 +345,4 @@ func getContentFromStdinAndArgs(args []string) (string, error) {
}
return content.String(), nil
}
// buildWorkspaceList builds the full workspace list with cwd as the first entry
func buildWorkspaceList(additionalWorkspaces []string) ([]string, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("failed to get current working directory: %w", err)
}
// Start with cwd
workspaces := []string{cwd}
// Add additional workspaces, avoiding duplicates
for _, ws := range additionalWorkspaces {
// Normalize the path
absPath, err := common.AbsPath(ws)
if err != nil {
return nil, fmt.Errorf("failed to resolve workspace path %s: %w", ws, err)
}
// Skip if it's the same as cwd
if absPath == cwd {
continue
}
// Check for duplicates
isDuplicate := slices.Contains(workspaces, absPath)
if !isDuplicate {
workspaces = append(workspaces, absPath)
}
}
return workspaces, nil
}
}
+10 -10
View File
@@ -23,7 +23,7 @@ func TestMultiInstanceDefaultUnchanged(t *testing.T) {
if len(out1.CoreInstances) != 1 {
t.Fatalf("expected 1 instance, got %d", len(out1.CoreInstances))
}
firstAddr := out1.CoreInstances[0].CoreAddress
firstAddr := out1.CoreInstances[0].Address
waitForAddressHealthy(t, firstAddr, defaultTimeout)
// Start second instance
@@ -56,29 +56,29 @@ func TestDefaultJsonUpdateAfterRemoval(t *testing.T) {
// Choose second as new default
target := out.CoreInstances[1]
waitForAddressHealthy(t, target.CoreAddress, defaultTimeout)
waitForAddressHealthy(t, target.Address, defaultTimeout)
// Set as default
_ = mustRunCLI(ctx, t, "instance", "use", target.CoreAddress)
_ = mustRunCLI(ctx, t, "instance", "use", target.Address)
// Verify default switched
out = listInstancesJSON(ctx, t)
if out.DefaultInstance != target.CoreAddress {
t.Fatalf("default_instance not updated to %s (got %s)", target.CoreAddress, out.DefaultInstance)
if out.DefaultInstance != target.Address {
t.Fatalf("default_instance not updated to %s (got %s)", target.Address, out.DefaultInstance)
}
// Kill the default instance using runtime PID discovery
corePID := getCorePID(t, target.CoreAddress)
corePID := getCorePID(t, target.Address)
if corePID <= 0 {
t.Fatalf("could not find PID for core process at %s", target.CoreAddress)
t.Fatalf("could not find PID for core process at %s", target.Address)
}
t.Logf("Killing cline-core process PID %d for instance %s", corePID, target.CoreAddress)
t.Logf("Killing cline-core process PID %d for instance %s", corePID, target.Address)
if err := syscall.Kill(corePID, syscall.SIGKILL); err != nil {
t.Fatalf("kill pid %d: %v", corePID, err)
}
// Wait for removal
waitForAddressRemoved(t, target.CoreAddress, longTimeout)
waitForAddressRemoved(t, target.Address, longTimeout)
// Clean up dangling host process (SIGKILL leaves these behind by design)
t.Logf("Cleaning up dangling host process on port %d", target.HostPort())
@@ -91,7 +91,7 @@ func TestDefaultJsonUpdateAfterRemoval(t *testing.T) {
if len(out.CoreInstances) > 0 {
found := false
for _, it := range out.CoreInstances {
if out.DefaultInstance == it.CoreAddress {
if out.DefaultInstance == it.Address {
found = true
break
}
+3 -3
View File
@@ -117,7 +117,7 @@ func listInstancesJSON(ctx context.Context, t *testing.T) common.InstancesOutput
func hasAddress(in common.InstancesOutput, addr string) bool {
for _, it := range in.CoreInstances {
if it.CoreAddress == addr {
if it.Address == addr {
return true
}
}
@@ -126,7 +126,7 @@ func hasAddress(in common.InstancesOutput, addr string) bool {
func getByAddress(in common.InstancesOutput, addr string) (common.CoreInstanceInfo, bool) {
for _, it := range in.CoreInstances {
if it.CoreAddress == addr {
if it.Address == addr {
return it, true
}
}
@@ -313,7 +313,7 @@ func getCorePIDViaRPC(t *testing.T, address string) int {
defer cancel()
// Get client for the address
client, err := global.Instances.GetRegistry().GetClient(ctx, address)
client, err := global.Clients.GetRegistry().GetClient(ctx, address)
if err != nil {
t.Logf("Warning: failed to get client for %s, falling back to lsof: %v", address, err)
return getCorePIDViaLsof(t, address)
+10 -10
View File
@@ -26,7 +26,7 @@ func TestMixedLocalhostVs127Coexist(t *testing.T) {
t.Fatalf("expected at least 1 instance")
}
inst := out.CoreInstances[0]
waitForAddressHealthy(t, inst.CoreAddress, defaultTimeout)
waitForAddressHealthy(t, inst.Address, defaultTimeout)
// Manually add a SQLite entry for the same port but 127.0.0.1 host
addr127 := fmt.Sprintf("127.0.0.1:%d", inst.CorePort())
@@ -37,12 +37,12 @@ func TestMixedLocalhostVs127Coexist(t *testing.T) {
}
// Verify both addresses appear and are healthy
waitForAddressHealthy(t, inst.CoreAddress, defaultTimeout)
waitForAddressHealthy(t, inst.Address, defaultTimeout)
waitForAddressHealthy(t, addr127, defaultTimeout)
out = listInstancesJSON(ctx, t)
if !hasAddress(out, inst.CoreAddress) || !hasAddress(out, addr127) {
t.Fatalf("expected both %s and %s present", inst.CoreAddress, addr127)
if !hasAddress(out, inst.Address) || !hasAddress(out, addr127) {
t.Fatalf("expected both %s and %s present", inst.Address, addr127)
}
}
@@ -58,7 +58,7 @@ func TestStartStopStress(t *testing.T) {
before := listInstancesJSON(ctx, t)
beforeSet := map[string]struct{}{}
for _, it := range before.CoreInstances {
beforeSet[it.CoreAddress] = struct{}{}
beforeSet[it.Address] = struct{}{}
}
// Start a new instance
@@ -69,8 +69,8 @@ func TestStartStopStress(t *testing.T) {
waitFor(t, defaultTimeout, func() (bool, string) {
after := listInstancesJSON(ctx, t)
for _, it := range after.CoreInstances {
if _, ok := beforeSet[it.CoreAddress]; !ok {
newAddr = it.CoreAddress
if _, ok := beforeSet[it.Address]; !ok {
newAddr = it.Address
return true, ""
}
}
@@ -88,12 +88,12 @@ func TestStartStopStress(t *testing.T) {
}
// Get PID using runtime discovery
corePID := getCorePID(t, info.CoreAddress)
corePID := getCorePID(t, info.Address)
if corePID <= 0 {
t.Fatalf("could not find PID for new instance at %s", info.CoreAddress)
t.Fatalf("could not find PID for new instance at %s", info.Address)
}
t.Logf("Killing new instance %s (PID %d) for iteration %d", info.CoreAddress, corePID, i)
t.Logf("Killing new instance %s (PID %d) for iteration %d", info.Address, corePID, i)
if err := syscall.Kill(corePID, syscall.SIGKILL); err != nil {
t.Fatalf("kill pid %d: %v", corePID, err)
}
+1 -1
View File
@@ -55,7 +55,7 @@ func readInstancesFromSQLite(t *testing.T, clineDir string) []common.CoreInstanc
// Create InstanceInfo
info := common.CoreInstanceInfo{
CoreAddress: heldBy,
Address: heldBy,
HostServiceAddress: lockTarget,
Status: grpc_health_v1.HealthCheckResponse_UNKNOWN, // Will be updated by health check
LastSeen: time.Unix(lockedAt/1000, 0), // Convert from milliseconds
+14 -14
View File
@@ -29,7 +29,7 @@ func TestStartAndList(t *testing.T) {
t.Fatalf("expected 1 instance, got %d", len(out.CoreInstances))
}
addr := out.CoreInstances[0].CoreAddress
addr := out.CoreInstances[0].Address
t.Logf("Instance address: %s, status: %s", addr, out.CoreInstances[0].Status)
t.Logf("Waiting for address %s to become healthy...", addr)
@@ -44,8 +44,8 @@ func TestStartAndList(t *testing.T) {
if out.DefaultInstance == "" {
t.Fatalf("default_instance not set")
}
if out.DefaultInstance != out.CoreInstances[0].CoreAddress {
t.Fatalf("expected default_instance=%s, got %s", out.CoreInstances[0].CoreAddress, out.DefaultInstance)
if out.DefaultInstance != out.CoreInstances[0].Address {
t.Fatalf("expected default_instance=%s, got %s", out.CoreInstances[0].Address, out.DefaultInstance)
}
t.Logf("TestStartAndList completed successfully")
@@ -64,7 +64,7 @@ func TestTaskNewDefault(t *testing.T) {
if len(out.CoreInstances) != 1 {
t.Fatalf("expected 1 instance, got %d", len(out.CoreInstances))
}
addr := out.CoreInstances[0].CoreAddress
addr := out.CoreInstances[0].Address
waitForAddressHealthy(t, addr, defaultTimeout)
// Create a new task at default (success is sufficient)
@@ -108,21 +108,21 @@ func TestCrashCleanup(t *testing.T) {
// Test 1: Graceful shutdown (SIGTERM) - should clean up both processes
gracefulTarget := out.CoreInstances[0]
waitForAddressHealthy(t, gracefulTarget.CoreAddress, defaultTimeout)
waitForAddressHealthy(t, gracefulTarget.Address, defaultTimeout)
// Get PID using runtime discovery
gracefulPID := getCorePID(t, gracefulTarget.CoreAddress)
gracefulPID := getCorePID(t, gracefulTarget.Address)
if gracefulPID <= 0 {
t.Fatalf("could not find PID for graceful target at %s", gracefulTarget.CoreAddress)
t.Fatalf("could not find PID for graceful target at %s", gracefulTarget.Address)
}
t.Logf("Testing graceful shutdown (SIGTERM) for instance %s (PID %d)", gracefulTarget.CoreAddress, gracefulPID)
t.Logf("Testing graceful shutdown (SIGTERM) for instance %s (PID %d)", gracefulTarget.Address, gracefulPID)
if err := syscall.Kill(gracefulPID, syscall.SIGTERM); err != nil {
t.Fatalf("kill SIGTERM pid %d: %v", gracefulPID, err)
}
// Wait for registry cleanup
waitForAddressRemoved(t, gracefulTarget.CoreAddress, longTimeout)
waitForAddressRemoved(t, gracefulTarget.Address, longTimeout)
// Verify both core and host ports are freed (no dangling processes)
waitForPortsClosed(t, gracefulTarget.CorePort(), gracefulTarget.HostPort(), defaultTimeout)
@@ -132,21 +132,21 @@ func TestCrashCleanup(t *testing.T) {
// Test 2: Crash cleanup (SIGKILL) - creates dangling host process that we must clean up
crashTarget := out.CoreInstances[1]
waitForAddressHealthy(t, crashTarget.CoreAddress, defaultTimeout)
waitForAddressHealthy(t, crashTarget.Address, defaultTimeout)
// Get PID using runtime discovery
crashPID := getCorePID(t, crashTarget.CoreAddress)
crashPID := getCorePID(t, crashTarget.Address)
if crashPID <= 0 {
t.Fatalf("could not find PID for crash target at %s", crashTarget.CoreAddress)
t.Fatalf("could not find PID for crash target at %s", crashTarget.Address)
}
t.Logf("Testing crash cleanup (SIGKILL) for instance %s (PID %d)", crashTarget.CoreAddress, crashPID)
t.Logf("Testing crash cleanup (SIGKILL) for instance %s (PID %d)", crashTarget.Address, crashPID)
if err := syscall.Kill(crashPID, syscall.SIGKILL); err != nil {
t.Fatalf("kill SIGKILL pid %d: %v", crashPID, err)
}
// Wait for registry cleanup
waitForAddressRemoved(t, crashTarget.CoreAddress, longTimeout)
waitForAddressRemoved(t, crashTarget.Address, longTimeout)
// Verify the instance is removed from SQLite (no file to check anymore)
// The waitForAddressRemoved already confirms the instance is gone from the registry
+1 -1
View File
@@ -1,6 +1,6 @@
module github.com/cline/cli
go 1.24.0
go 1.23.0
require (
github.com/atotto/clipboard v0.1.4
-26
View File
@@ -70,10 +70,6 @@ When using the instant task syntax **cline "prompt"** the following options are
: Starting mode. Options: **act** (default), **plan**
**-w**, **\--workspace** *path*
: Additional workspace paths. Can be specified multiple times to include multiple directories. The current working directory is always included as the first workspace. Example: cline -w /path/to/other/project "refactor shared code"
# GLOBAL OPTIONS
These options apply to all subcommands:
@@ -82,28 +78,6 @@ These options apply to all subcommands:
: Output format. Options: **rich** (default), **json**, **plain**
When you use **-F json**, the CLI prints each client message as JSON.
Each message is a **ClineMessage** object.
Required fields:
- **type**: "ask" or "say"
- **text**: message text
- **ts**: Unix epoch timestamp in milliseconds
Optional fields (omitted when empty):
- **reasoning**: reasoning text
- **say**: say subtype (present when type is "say")
- **ask**: ask subtype (present when type is "ask")
- **partial**: streaming flag
- **images**: list of image URIs
- **files**: list of file paths
- **lastCheckpointHash**: git checkpoint hash
- **isCheckpointCheckedOut**: checkpoint checkout flag
- **isOperationOutsideWorkspace**: workspace safety flag
**-h**, **\--help**
: Display help information for the command.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cline",
"version": "1.0.10",
"version": "1.0.3",
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
"main": "cline-core.js",
"bin": {
+10 -8
View File
@@ -46,21 +46,21 @@ const (
// It spawns a fresh instance for auth operations and cleans it up when done
func RunAuthFlow(ctx context.Context, args []string) error {
// Spawn a fresh instance for auth operations
instanceInfo, err := global.Instances.StartNewInstance(ctx)
instanceInfo, err := global.Clients.StartNewInstance(ctx)
if err != nil {
return fmt.Errorf("failed to start auth instance: %w", err)
}
// Cleanup when done (success, error, or panic)
defer func() {
verboseLog("Shutting down auth instance at %s", instanceInfo.CoreAddress)
if err := global.KillInstanceByAddress(context.Background(), global.Instances.GetRegistry(), instanceInfo.CoreAddress); err != nil {
verboseLog("Shutting down auth instance at %s", instanceInfo.Address)
if err := global.KillInstanceByAddress(context.Background(), global.Clients.GetRegistry(), instanceInfo.Address); err != nil {
verboseLog("Warning: Failed to kill auth instance: %v", err)
}
}()
// Store instance address in context for all auth handlers to use
authCtx := context.WithValue(ctx, authInstanceAddressKey, instanceInfo.CoreAddress)
authCtx := context.WithValue(ctx, authInstanceAddressKey, instanceInfo.Address)
// Route to existing auth flow
return HandleAuthCommand(authCtx, args)
@@ -108,10 +108,12 @@ func HandleAuthMenuNoArgs(ctx context.Context) error {
// Get current provider config for display
var currentProvider string
var currentModel string
if providerList, err := GetProviderConfigurations(ctx); err == nil {
if providerList.ActProvider != nil {
currentProvider = GetProviderDisplayName(providerList.ActProvider.Provider)
currentModel = providerList.ActProvider.ModelID
if manager, err := createTaskManager(ctx); err == nil {
if providerList, err := GetProviderConfigurations(ctx, manager); err == nil {
if providerList.ActProvider != nil {
currentProvider = GetProviderDisplayName(providerList.ActProvider.Provider)
currentModel = providerList.ActProvider.ModelID
}
}
}
+40 -50
View File
@@ -29,17 +29,13 @@ type ProviderListResult struct {
}
// GetProviderConfigurations retrieves and parses provider configurations from Cline Core state
func GetProviderConfigurations(ctx context.Context) (*ProviderListResult, error) {
func GetProviderConfigurations(ctx context.Context, manager *task.Manager) (*ProviderListResult, error) {
if global.Config.Verbose {
fmt.Println("[DEBUG] Retrieving provider configurations from Cline Core")
}
// Get latest state from Cline Core
grpcClient, err := global.GetDefaultClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get provider configs due to unable to get gRPC client: %w", err)
}
state, err := grpcClient.State.GetLatestState(ctx, &cline.EmptyRequest{})
state, err := manager.GetClient().State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return nil, fmt.Errorf("failed to get state: %w", err)
}
@@ -51,7 +47,7 @@ func GetProviderConfigurations(ctx context.Context) (*ProviderListResult, error)
}
// Parse state_json as map[string]interface{}
var stateData map[string]any
var stateData map[string]interface{}
if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
@@ -61,7 +57,7 @@ func GetProviderConfigurations(ctx context.Context) (*ProviderListResult, error)
}
// Extract apiConfiguration object from state
apiConfig, ok := stateData["apiConfiguration"].(map[string]any)
apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{})
if !ok {
if global.Config.Verbose {
fmt.Println("[DEBUG] No apiConfiguration found in state")
@@ -132,11 +128,11 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
modelID := getProviderSpecificModelID(r.apiConfig, "plan", provider)
// Determine if credentials exist
hasCreds := checkCredentialsExists(r.apiConfig, provider)
hasCreds := checkAPIKeyExists(r.apiConfig, provider)
// Determine readiness: OCA uses auth state presence; others need creds and model
if provider == cline.ApiProvider_OCA {
state, _ := GetLatestOCAState(context.Background(), 2*time.Second)
state, _ := GetLatestOCAState(context.Background(), 2 *time.Second)
if state == nil || state.User == nil {
continue
}
@@ -160,7 +156,7 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
Mode: "Ready",
Provider: provider,
ModelID: modelID,
HasAPIKey: checkCredentialsExists(r.apiConfig, provider),
HasAPIKey: checkAPIKeyExists(r.apiConfig, provider),
BaseURL: baseURL,
})
seenProviders[provider] = true
@@ -196,7 +192,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
modelID := getProviderSpecificModelID(stateData, mode, provider)
// Check if API key exists
hasCredentials := checkCredentialsExists(stateData, provider)
hasAPIKey := checkAPIKeyExists(stateData, provider)
// Get base URL for Ollama (can be shown publicly)
baseURL := ""
@@ -210,7 +206,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
Mode: capitalizeMode(mode),
Provider: provider,
ModelID: modelID,
HasAPIKey: hasCredentials,
HasAPIKey: hasAPIKey,
BaseURL: baseURL,
}
}
@@ -219,7 +215,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
// Returns (provider, ok) where ok is false if the provider is unknown
func mapProviderStringToEnum(providerStr string) (cline.ApiProvider, bool) {
normalizedStr := strings.ToLower(providerStr)
// Map string values to enum values
switch normalizedStr {
case "anthropic":
@@ -307,23 +303,19 @@ func getProviderSpecificModelID(stateData map[string]interface{}, mode string, p
return modelID
}
// checkCredentialsExists checks if API key field exists in state (never retrieve actual key)
func checkCredentialsExists(stateData map[string]interface{}, provider cline.ApiProvider) bool {
// checkAPIKeyExists checks if API key field exists in state (never retrieve actual key)
func checkAPIKeyExists(stateData map[string]interface{}, provider cline.ApiProvider) bool {
// Get field mapping from centralized function
fields, err := GetProviderFields(provider)
if err != nil {
return false
}
// Check if the key exists and is not empty
if value, ok := stateData[fields.APIKeyField]; ok {
if str, ok := value.(string); ok && str != "" {
return true
}
}
keyField := fields.APIKeyField
if value, ok := stateData[fields.UseProfileField]; ok {
if hasProfileField, ok := value.(bool); ok && hasProfileField {
// Check if the key exists and is not empty
if value, ok := stateData[keyField]; ok {
if str, ok := value.(string); ok && str != "" {
return true
}
}
@@ -446,13 +438,13 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
stateJSON := state.StateJson
// Parse state_json as map[string]interface{}
var stateData map[string]any
var stateData map[string]interface{}
if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
// Extract apiConfiguration object from state
apiConfig, ok := stateData["apiConfiguration"].(map[string]any)
apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{})
if !ok {
verboseLog("[DEBUG] No apiConfiguration found in state")
verboseLog("[DEBUG] Available keys in stateData: %v", getMapKeys(stateData))
@@ -477,38 +469,36 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
// Check each BYO provider for API key presence
providersToCheck := []struct {
provider cline.ApiProvider
keyFields []string
provider cline.ApiProvider
keyField string
}{
{cline.ApiProvider_ANTHROPIC, []string{"apiKey"}},
{cline.ApiProvider_OPENAI, []string{"openAiApiKey"}},
{cline.ApiProvider_OPENAI_NATIVE, []string{"openAiNativeApiKey"}},
{cline.ApiProvider_OPENROUTER, []string{"openRouterApiKey"}},
{cline.ApiProvider_XAI, []string{"xaiApiKey"}},
{cline.ApiProvider_BEDROCK, []string{"awsAccessKey", "awsUseProfile"}},
{cline.ApiProvider_GEMINI, []string{"geminiApiKey"}},
{cline.ApiProvider_OLLAMA, []string{"ollamaBaseUrl"}}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, []string{"cerebrasApiKey"}},
{cline.ApiProvider_HICAP, []string{"hicapApiKey"}},
{cline.ApiProvider_NOUSRESEARCH, []string{"nousResearchApiKey"}},
{cline.ApiProvider_ANTHROPIC, "apiKey"},
{cline.ApiProvider_OPENAI, "openAiApiKey"},
{cline.ApiProvider_OPENAI_NATIVE, "openAiNativeApiKey"},
{cline.ApiProvider_OPENROUTER, "openRouterApiKey"},
{cline.ApiProvider_XAI, "xaiApiKey"},
{cline.ApiProvider_BEDROCK, "awsAccessKey"},
{cline.ApiProvider_GEMINI, "geminiApiKey"},
{cline.ApiProvider_OLLAMA, "ollamaBaseUrl"}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, "cerebrasApiKey"},
{cline.ApiProvider_HICAP, "hicapApiKey"},
{cline.ApiProvider_NOUSRESEARCH, "nousResearchApiKey"},
}
for _, providerCheck := range providersToCheck {
verboseLog("[DEBUG] Checking for %s key: %s", GetProviderDisplayName(providerCheck.provider), providerCheck.keyFields)
for _, keyField := range providerCheck.keyFields {
if value, ok := apiConfig[keyField]; ok {
verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "")
if str, ok := value.(string); ok && str != "" {
configuredProviders = append(configuredProviders, providerCheck.provider)
verboseLog("[DEBUG] ✓ Provider %s is configured", GetProviderDisplayName(providerCheck.provider))
break
}
} else {
verboseLog("[DEBUG] Key %s not found", keyField)
verboseLog("[DEBUG] Checking for %s key: %s", GetProviderDisplayName(providerCheck.provider), providerCheck.keyField)
if value, ok := apiConfig[providerCheck.keyField]; ok {
verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "")
if str, ok := value.(string); ok && str != "" {
configuredProviders = append(configuredProviders, providerCheck.provider)
verboseLog("[DEBUG] ✓ Provider %s is configured", GetProviderDisplayName(providerCheck.provider))
}
} else {
verboseLog("[DEBUG] Key %s not found", providerCheck.keyField)
}
}
verboseLog("[DEBUG] Total configured providers: %d", len(configuredProviders))
for _, p := range configuredProviders {
verboseLog("[DEBUG] - %s", GetProviderDisplayName(p))
@@ -54,7 +54,6 @@ type ProviderFields struct {
// Provider-specific additional model ID fields
PlanModeProviderSpecificModelIDField string // e.g., "planModeOpenRouterModelId"
ActModeProviderSpecificModelIDField string // e.g., "actModeOpenRouterModelId"
UseProfileField string // e.g., "awsUseProfile" (for bedrock) (optional, empty if not applicable)
}
// GetProviderFields returns the field mapping for a given provider
@@ -97,7 +96,6 @@ func GetProviderFields(provider cline.ApiProvider) (ProviderFields, error) {
case cline.ApiProvider_BEDROCK:
return ProviderFields{
UseProfileField: "awsUseProfile",
APIKeyField: "awsAccessKey",
PlanModeModelIDField: "planModeApiModelId",
ActModeModelIDField: "actModeApiModelId",
@@ -358,9 +356,6 @@ func AddProviderPartial(ctx context.Context, manager *task.Manager, provider cli
if openRouterInfo, ok := modelInfo.(*cline.OpenRouterModelInfo); ok {
apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo
apiConfig.ActModeOpenRouterModelInfo = openRouterInfo
} else if ocaInfo, ok := modelInfo.(*cline.OcaModelInfo); ok {
apiConfig.PlanModeOcaModelInfo = ocaInfo
apiConfig.ActModeOcaModelInfo = ocaInfo
}
}
@@ -429,9 +424,6 @@ func UpdateProviderPartial(ctx context.Context, manager *task.Manager, provider
if openRouterInfo, ok := updates.ModelInfo.(*cline.OpenRouterModelInfo); ok {
apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo
apiConfig.ActModeOpenRouterModelInfo = openRouterInfo
} else if ocaInfo, ok := updates.ModelInfo.(*cline.OcaModelInfo); ok {
apiConfig.PlanModeOcaModelInfo = ocaInfo
apiConfig.ActModeOcaModelInfo = ocaInfo
}
}
+9 -8
View File
@@ -190,7 +190,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
}
// Step 3: Select model
modelID, modelInfo, err := pw.selectModel(cline.ApiProvider_OCA, "")
modelID, _, err := pw.selectModel(cline.ApiProvider_OCA, "")
if err != nil {
return fmt.Errorf("model selection failed: %w", err)
}
@@ -198,7 +198,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
// Step 4: Apply the OCA model configuration and set as active
updates := ProviderUpdatesPartial{
ModelID: &modelID,
ModelInfo: modelInfo,
ModelInfo: nil,
}
if err := UpdateProviderPartial(pw.ctx, pw.manager, cline.ApiProvider_OCA, updates, true); err != nil {
@@ -215,7 +215,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
// handleListProviders retrieves and displays configured providers
func (pw *ProviderWizard) handleListProviders() error {
result, err := GetProviderConfigurations(pw.ctx)
result, err := GetProviderConfigurations(pw.ctx, pw.manager)
if err != nil {
return fmt.Errorf("failed to retrieve provider configurations: %w", err)
}
@@ -413,7 +413,7 @@ func (pw *ProviderWizard) manualModelEntry(provider cline.ApiProvider) (string,
// handleChangeModel allows changing the model for any configured provider
func (pw *ProviderWizard) handleChangeModel() error {
// Step 1: Get current provider configurations
result, err := GetProviderConfigurations(pw.ctx)
result, err := GetProviderConfigurations(pw.ctx, pw.manager)
if err != nil {
return fmt.Errorf("failed to retrieve provider configurations: %w", err)
}
@@ -517,7 +517,7 @@ func (pw *ProviderWizard) applyModelChange(provider cline.ApiProvider, modelID s
ModelInfo: modelInfo,
}
return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, true)
return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, false)
}
// SwitchToBYOProvider switches to a BYO provider that's already configured.
@@ -585,11 +585,11 @@ func getProviderModelIDFromState(stateData map[string]interface{}, provider clin
return ""
}
// getProviderAPIKeyFromState retrieves the API key for a specific provider from state
// getProviderAPIKeyFromState retrieves the API key for a specific provider from state
func getProviderAPIKeyFromState(stateData map[string]interface{}, provider cline.ApiProvider) string {
// OCA uses account authentication, not API keys. Consider it "present" if authenticated.
if provider == cline.ApiProvider_OCA {
if state, _ := GetLatestOCAState(context.TODO(), 2*time.Second); state != nil && state.User != nil {
if state, _ := GetLatestOCAState(context.TODO(), 2 * time.Second); state != nil && state.User != nil {
// Return a sentinel non-empty string so upstream checks pass.
return "OCA_AUTH_VERIFIED"
}
@@ -648,7 +648,7 @@ func convertMapToOpenRouterModelInfo(data map[string]interface{}) *cline.OpenRou
// handleRemoveProvider allows removing a configured provider by clearing its API key
func (pw *ProviderWizard) handleRemoveProvider() error {
// Step 1: Get current provider configurations
result, err := GetProviderConfigurations(pw.ctx)
result, err := GetProviderConfigurations(pw.ctx, pw.manager)
if err != nil {
return fmt.Errorf("failed to retrieve provider configurations: %w", err)
}
@@ -748,6 +748,7 @@ func (pw *ProviderWizard) clearProviderAPIKey(provider cline.ApiProvider) error
return RemoveProviderPartial(pw.ctx, pw.manager, provider)
}
func signOutOca(ctx context.Context) error {
client, err := global.GetDefaultClient(ctx)
if err != nil {
+15 -22
View File
@@ -15,23 +15,23 @@ import (
// BedrockConfig holds all AWS Bedrock-specific configuration fields
type BedrockConfig struct {
// Profile authentication fields
UseProfile bool // Always true for successful config
Profile string // Optional: AWS profile name (empty = default)
Region string // Required: AWS region
Endpoint string // Optional: Custom VPC endpoint URL
UseProfile bool // Always true for successful config
Profile string // Optional: AWS profile name (empty = default)
Region string // Required: AWS region
Endpoint string // Optional: Custom VPC endpoint URL
// Optional features
UseCrossRegionInference bool // Optional: Enable cross-region inference
UseGlobalInference bool // Optional: Use global inference endpoint
UsePromptCache bool // Optional: Enable prompt caching
UseCrossRegionInference bool // Optional: Enable cross-region inference
UseGlobalInference bool // Optional: Use global inference endpoint
UsePromptCache bool // Optional: Enable prompt caching
// Authentication method (always "profile")
Authentication string // Always set to "profile"
Authentication string // Always set to "profile"
// Legacy fields (no longer used in profile-only flow)
AccessKey string // No longer used
SecretKey string // No longer used
SessionToken string // No longer used
AccessKey string // No longer used
SecretKey string // No longer used
SessionToken string // No longer used
}
// PromptForBedrockConfig displays a profile-first authentication form for Bedrock configuration
@@ -130,12 +130,7 @@ func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *Bedr
// Build the API configuration with all Bedrock fields
apiConfig := &cline.ModelsApiConfiguration{}
// Set provider for both Plan and Act modes
bedrockProvider := cline.ApiProvider_BEDROCK
apiConfig.PlanModeApiProvider = &bedrockProvider
apiConfig.ActModeApiProvider = &bedrockProvider
// Set model ID field - this is the primary model ID used by Cline Core
// Set model ID fields
apiConfig.PlanModeApiModelId = proto.String(modelID)
apiConfig.ActModeApiModelId = proto.String(modelID)
apiConfig.PlanModeAwsBedrockCustomModelBaseId = proto.String(modelID)
@@ -171,8 +166,6 @@ func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *Bedr
// Build field mask including all fields we're setting (excluding access keys)
fieldPaths := []string{
"planModeApiProvider",
"actModeApiProvider",
"planModeApiModelId",
"actModeApiModelId",
"planModeAwsBedrockCustomModelBaseId",
+3 -3
View File
@@ -40,7 +40,7 @@ func ensureConfigManager(ctx context.Context, address string) error {
}
// Always set the instance we're using as the default
registry := global.Instances.GetRegistry()
registry := global.Clients.GetRegistry()
if err := registry.SetDefaultInstance(instanceAddress); err != nil {
// Log warning but don't fail - this is not critical
fmt.Printf("Warning: failed to set default instance: %v\n", err)
@@ -123,11 +123,11 @@ func setCommand() *cobra.Command {
Use: "set <key=value> [key=value...]",
Aliases: []string{"s"},
Short: "Set configuration variables",
Long: `Set one or more global configuration variables using key=value format.
Long: `Set one or more global configuration variables using key=value format.
This command merges the provided settings with existing values, preserving
unspecified fields. Only the fields you explicitly set will be updated.`,
Args: cobra.MinimumNArgs(1),
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
+3 -2
View File
@@ -32,8 +32,8 @@ func NewManager(ctx context.Context, address string) (*Manager, error) {
// Get the actual address being used
clientAddress := address
if address == "" && global.Instances != nil {
clientAddress = global.Instances.GetRegistry().GetDefaultInstance()
if address == "" && global.Clients != nil {
clientAddress = global.Clients.GetRegistry().GetDefaultInstance()
}
return &Manager{
@@ -92,6 +92,7 @@ func (m *Manager) ListSettings(ctx context.Context) error {
"telemetrySetting",
"planActSeparateModelsSetting",
"enableCheckpointsSetting",
"mcpMarketplaceEnabled",
"shellIntegrationTimeout",
"terminalReuseEnabled",
"mcpResponsesCollapsed",
+2 -1
View File
@@ -77,7 +77,8 @@ func RenderField(key string, value interface{}, censor bool) error {
case "mode", "telemetrySetting", "preferredLanguage", "customPrompt",
"defaultTerminalProfile", "mcpDisplayMode", "openaiReasoningEffort",
"planActSeparateModelsSetting", "enableCheckpointsSetting",
"terminalReuseEnabled", "mcpResponsesCollapsed", "strictPlanModeEnabled",
"mcpMarketplaceEnabled", "terminalReuseEnabled",
"mcpResponsesCollapsed", "strictPlanModeEnabled",
"useAutoCondense", "yoloModeToggled", "shellIntegrationTimeout",
"terminalOutputLineLimit", "autoCondenseThreshold":
fmt.Printf("%s: %s\n", camelToKebab(key), formatValue(value, key, censor))
+130 -18
View File
@@ -1,19 +1,22 @@
package display
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/common"
)
// BannerInfo contains information to display in the session banner
type BannerInfo struct {
Version string
Provider string
ModelID string
Workdirs []string // workspace directories
Mode string
Version string
Provider string
ModelID string
Workdir string
Mode string
}
// RenderSessionBanner renders a nice banner showing version, model, and workspace info
@@ -78,22 +81,131 @@ func RenderSessionBanner(info BannerInfo) string {
// Model line - dim gray
if info.Provider != "" && info.ModelID != "" {
lines = append(lines, dimStyle.Render(info.Provider+"/"+common.ShortenPath(info.ModelID, 30)))
lines = append(lines, dimStyle.Render(info.Provider+"/"+shortenPath(info.ModelID, 30)))
}
for _, wd := range info.Workdirs {
lines = append(lines, dimStyle.Render(common.ShortenPath(wd, 45)))
}
// Checkpoint warning for multi-root workspaces
if len(info.Workdirs) > 1 {
warningStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("3")). // Yellow warning color
Italic(true)
lines = append(lines, "")
lines = append(lines, warningStyle.Render("⚠ Checkpoints disabled for multi-root workspaces"))
// Workspace line - dim gray
if info.Workdir != "" {
lines = append(lines, dimStyle.Render(shortenPath(info.Workdir, 45)))
}
content := lipgloss.JoinVertical(lipgloss.Left, lines...)
return boxStyle.Render(content)
}
// shortenPath shortens a filesystem path to fit within maxLen
func shortenPath(path string, maxLen int) string {
// Try to replace home directory with ~ (cross-platform)
if homeDir, err := os.UserHomeDir(); err == nil {
if strings.HasPrefix(path, homeDir) {
shortened := "~" + path[len(homeDir):]
// Always use ~ version if we can
path = shortened
}
}
if len(path) <= maxLen {
return path
}
// If still too long, show last few path components
if len(path) > maxLen {
parts := strings.Split(path, string(filepath.Separator))
if len(parts) > 2 {
// Show last 2-3 components
lastParts := parts[len(parts)-2:]
shortened := "..." + string(filepath.Separator) + strings.Join(lastParts, string(filepath.Separator))
if len(shortened) <= maxLen {
return shortened
}
}
}
// Last resort: truncate with ellipsis
if len(path) > maxLen {
return "..." + path[len(path)-maxLen+3:]
}
return path
}
// ExtractBannerInfoFromState extracts banner info from state JSON
func ExtractBannerInfoFromState(stateJSON, version string) (BannerInfo, error) {
var state map[string]interface{}
if err := json.Unmarshal([]byte(stateJSON), &state); err != nil {
return BannerInfo{}, fmt.Errorf("failed to parse state JSON: %w", err)
}
info := BannerInfo{
Version: version,
}
// Extract mode
if mode, ok := state["mode"].(string); ok {
info.Mode = mode
}
// Extract workspace roots
if workspaceRoots, ok := state["workspaceRoots"].([]interface{}); ok && len(workspaceRoots) > 0 {
if root, ok := workspaceRoots[0].(map[string]interface{}); ok {
if path, ok := root["path"].(string); ok {
info.Workdir = path
}
}
}
// Extract API configuration to get provider/model
if apiConfig, ok := state["apiConfiguration"].(map[string]interface{}); ok {
// Try common keys for provider and model (both camelCase and lowercase variants)
providerKeys := []string{"apiProvider", "api_provider"}
modelKeys := []string{"apiModelId", "api_model_id"}
// Try to extract provider
for _, key := range providerKeys {
if provider, ok := apiConfig[key].(string); ok && provider != "" {
info.Provider = provider
break
}
}
// Try to extract model ID
for _, key := range modelKeys {
if modelID, ok := apiConfig[key].(string); ok && modelID != "" {
info.ModelID = shortenModelID(modelID)
break
}
}
}
return info, nil
}
// shortenModelID shortens long model IDs for display
func shortenModelID(modelID string) string {
// Remove date suffixes only if they're at the end (e.g., -20241022)
// Check if the model ID ends with -YYYYMMDD pattern
if len(modelID) > 9 {
suffix := modelID[len(modelID)-9:] // Last 9 chars: -20241022
if suffix[0] == '-' &&
(strings.HasPrefix(suffix[1:], "202") || strings.HasPrefix(suffix[1:], "201")) {
// Verify all remaining chars are digits
allDigits := true
for _, c := range suffix[1:] {
if c < '0' || c > '9' {
allDigits = false
break
}
}
if allDigits {
return modelID[:len(modelID)-9]
}
}
}
// If still too long, show first 40 chars
if len(modelID) > 40 {
return modelID[:37] + "..."
}
return modelID
}
-144
View File
@@ -1,144 +0,0 @@
package display
import (
"fmt"
"strings"
"github.com/cline/cli/pkg/cli/types"
)
// HookRenderer renders hook status messages in a CLI-native style.
//
// Goals:
// - Match ToolRenderers markdown look
// - Keep executions ungrouped
// - Render status + high-signal metadata (script paths, error summary)
//
// Note: hook stdout/stderr currently arrives as separate `hook_output_stream` messages.
// The CLI suppresses those by default and prints them only in --verbose mode.
// Future work could group streamed output under the corresponding hook block.
//
// It returns markdown (or rendered markdown when enabled); callers should print the
// returned string.
type HookRenderer struct {
mdRenderer *MarkdownRenderer
outputFormat string
}
func NewHookRenderer(mdRenderer *MarkdownRenderer, outputFormat string) *HookRenderer {
return &HookRenderer{mdRenderer: mdRenderer, outputFormat: outputFormat}
}
func (hr *HookRenderer) RenderHookStatus(h types.HookMessage) string {
statusText := strings.TrimSpace(h.Status)
if statusText == "" {
statusText = "unknown"
}
// Header: aligned with ToolRenderers phrasing so transcripts scan consistently.
// Example: "### Cline hook completed: PreToolUse (tool: read_file) (exit 0)"
var headerBuilder strings.Builder
headerBuilder.WriteString(fmt.Sprintf("### Cline hook %s: %s", statusText, h.HookName))
if h.ToolName != "" {
headerBuilder.WriteString(" ")
headerBuilder.WriteString(fmt.Sprintf("(tool: %s)", h.ToolName))
}
if statusText == "failed" && h.ExitCode != 0 {
headerBuilder.WriteString(" ")
headerBuilder.WriteString(fmt.Sprintf("(exit %d)", h.ExitCode))
}
header := headerBuilder.String()
var lines []string
lines = append(lines, header)
// Pending tool info (PreToolUse): show one high-signal line directly under the header.
if h.PendingToolInfo != nil {
if pending := hr.formatPendingToolInfo(h.PendingToolInfo); pending != "" {
lines = append(lines, fmt.Sprintf("- Pending: %s", pending))
}
}
// Script paths: one per line.
paths := make([]string, 0, len(h.ScriptPaths))
for _, p := range h.ScriptPaths {
p = strings.TrimSpace(p)
if p != "" {
paths = append(paths, p)
}
}
if len(paths) == 0 {
// Fallback when no script paths are provided.
lines = append(lines, "- *(no hook scripts found)*")
} else {
for _, p := range paths {
lines = append(lines, fmt.Sprintf("- Running hook: `%s`", p))
}
}
// On failure, show a minimal summary (full stderr reserved for verbose).
if statusText == "failed" && h.Error != nil {
if msg := strings.TrimSpace(h.Error.Message); msg != "" {
lines = append(lines, fmt.Sprintf("- Error: %s", msg))
}
// If we have a specific script path, include it as a hint.
if sp := strings.TrimSpace(h.Error.ScriptPath); sp != "" {
lines = append(lines, fmt.Sprintf("- Script: `%s`", sp))
}
}
markdown := strings.Join(lines, "\n")
return hr.renderMarkdown(markdown)
}
func (hr *HookRenderer) formatPendingToolInfo(info *types.ToolInfo) string {
if info == nil {
return ""
}
tool := strings.TrimSpace(info.Tool)
if tool == "" {
return ""
}
// Keep this intentionally compact and readable.
// Format: "<tool> <identifier>" where identifier is the most relevant param.
var ident string
switch {
case strings.TrimSpace(info.Path) != "":
ident = strings.TrimSpace(info.Path)
case strings.TrimSpace(info.Command) != "":
ident = strings.TrimSpace(info.Command)
case strings.TrimSpace(info.Url) != "":
ident = strings.TrimSpace(info.Url)
case strings.TrimSpace(info.McpTool) != "" && strings.TrimSpace(info.McpServer) != "":
ident = fmt.Sprintf("%s %s", strings.TrimSpace(info.McpServer), strings.TrimSpace(info.McpTool))
case strings.TrimSpace(info.ResourceUri) != "":
ident = strings.TrimSpace(info.ResourceUri)
case strings.TrimSpace(info.Regex) != "":
ident = strings.TrimSpace(info.Regex)
default:
ident = ""
}
if ident != "" {
return fmt.Sprintf("%s %s", tool, ident)
}
return tool
}
func (hr *HookRenderer) renderMarkdown(markdown string) string {
// Align with ToolRenderer: in plain mode or non-TTY, return markdown as-is.
if hr.outputFormat == "plain" || !isTTY() {
return markdown
}
if hr.mdRenderer == nil {
return markdown
}
rendered, err := hr.mdRenderer.Render(markdown)
if err != nil {
return markdown
}
return rendered
}
-69
View File
@@ -1,69 +0,0 @@
package display
import (
"strings"
"testing"
"github.com/cline/cli/pkg/cli/types"
)
func TestHookRenderer_RenderHookStatus_FailedShowsErrorAndScript(t *testing.T) {
hr := NewHookRenderer(nil, "plain")
msg := hr.RenderHookStatus(types.HookMessage{
HookName: "PreToolUse",
ToolName: "execute_command",
Status: "failed",
ExitCode: 2,
ScriptPaths: []string{"repo/.clinerules/hooks/PreToolUse"},
Error: &types.HookError{
Message: "boom",
ScriptPath: "repo/.clinerules/hooks/PreToolUse",
},
})
if !strings.Contains(msg, "### Cline hook failed: PreToolUse") {
t.Fatalf("expected header in rendered output, got: %q", msg)
}
if !strings.Contains(msg, "- Error: boom") {
t.Fatalf("expected error line in rendered output, got: %q", msg)
}
if !strings.Contains(msg, "- Script: `repo/.clinerules/hooks/PreToolUse`") {
t.Fatalf("expected script line in rendered output, got: %q", msg)
}
}
func TestHookRenderer_RenderHookStatus_PendingToolInfoAppearsDirectlyUnderHeader(t *testing.T) {
hr := NewHookRenderer(nil, "plain")
msg := hr.RenderHookStatus(types.HookMessage{
HookName: "PreToolUse",
ToolName: "write_to_file",
Status: "running",
PendingToolInfo: &types.ToolInfo{
Tool: "write_to_file",
Path: "src/foo.ts",
},
ScriptPaths: []string{"repo/.clinerules/hooks/PreToolUse"},
})
header := "### Cline hook running: PreToolUse"
pending := "- Pending: write_to_file src/foo.ts"
runningHook := "- Running hook: `repo/.clinerules/hooks/PreToolUse`"
headerIdx := strings.Index(msg, header)
if headerIdx == -1 {
t.Fatalf("expected header %q in output, got: %q", header, msg)
}
pendingIdx := strings.Index(msg, pending)
if pendingIdx == -1 {
t.Fatalf("expected pending line %q in output, got: %q", pending, msg)
}
runningIdx := strings.Index(msg, runningHook)
if runningIdx == -1 {
t.Fatalf("expected running hook line %q in output, got: %q", runningHook, msg)
}
if !(headerIdx < pendingIdx && pendingIdx < runningIdx) {
t.Fatalf("expected header < pending < runningHook ordering, got indexes header=%d pending=%d running=%d\nfull=%q", headerIdx, pendingIdx, runningIdx, msg)
}
}
+3 -13
View File
@@ -39,12 +39,9 @@ func NewStreamingSegment(sayType, prefix string, mdRenderer *MarkdownRenderer, s
// Render rich header immediately when creating segment (if in rich mode and TTY)
if shouldMarkdown && outputFormat != "plain" && isTTY() {
header := ss.generateRichHeader()
// Skip empty headers.
if strings.TrimSpace(header) != "" {
rendered, _ := mdRenderer.Render(header)
output.Println("")
output.Print(rendered)
}
rendered, _ := mdRenderer.Render(header)
output.Println("")
output.Print(rendered)
}
return ss
@@ -113,9 +110,6 @@ func (ss *StreamingSegment) renderFinal(currentBuffer string) {
if err := json.Unmarshal([]byte(currentBuffer), &tool); err == nil {
bodyContent = ss.toolRenderer.GenerateToolContentBody(&tool)
}
} else if ss.sayType == string(types.SayTypeHookStatus) {
// Hooks are rendered via the state stream; nothing to render here.
bodyContent = ""
} else if ss.sayType == string(types.SayTypeCommand) {
// Command output
bodyContent = "```shell\n" + currentBuffer + "\n```"
@@ -166,10 +160,6 @@ func (ss *StreamingSegment) generateRichHeader() string {
case string(types.SayTypeTool):
return ss.generateToolHeader()
case string(types.SayTypeHookStatus):
// Hooks are rendered from the state stream; dont emit a partial-stream header.
return ""
case "ask":
// Check the specific ask type
@@ -1,20 +0,0 @@
package display
import (
"testing"
"github.com/cline/cli/pkg/cli/types"
)
func TestStreamingSegment_generateRichHeader_HookIsEmpty(t *testing.T) {
ss := &StreamingSegment{
sayType: string(types.SayTypeHookStatus),
prefix: "HOOK",
msg: &types.ClineMessage{},
}
header := ss.generateRichHeader()
if header != "" {
t.Fatalf("expected empty header for hook segments to avoid double-render, got: %q", header)
}
}
+1 -19
View File
@@ -38,18 +38,6 @@ func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
s.mu.Lock()
defer s.mu.Unlock()
// Render hooks from the state stream only (not partial stream) to avoid duplicates.
//
// Rationale: hook status messages are often updated/reordered by the backend (e.g. PreToolUse
// hooks are moved above the corresponding tool message). The state stream represents the
// authoritative, “final” message ordering, while the partial stream is best-effort for
// incremental display.
//
// Only suppress *partial* hook messages; complete ones still flow through dedupe.
if msg.Partial && msg.Say == string(types.SayTypeHookStatus) {
return nil
}
// Check for deduplication
if s.dedupe.IsDuplicate(msg) {
return nil
@@ -103,11 +91,7 @@ func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
func (s *StreamingDisplay) shouldRenderMarkdown(sayType string) bool {
switch sayType {
case string(types.SayTypeReasoning),
string(types.SayTypeText),
string(types.SayTypeCompletionResult),
string(types.SayTypeTool),
"ask":
case string(types.SayTypeReasoning), string(types.SayTypeText), string(types.SayTypeCompletionResult), string(types.SayTypeTool), "ask":
return true
default:
return false
@@ -126,8 +110,6 @@ func (s *StreamingDisplay) getPrefix(sayType string) string {
return "ASK"
case string(types.SayTypeCommand):
return "TERMINAL"
case string(types.SayTypeHookStatus):
return "HOOK"
default:
return strings.ToUpper(sayType)
}
+1 -1
View File
@@ -264,6 +264,6 @@ func (sr *SystemMessageRenderer) RenderInfo(title, message string) error {
func (sr *SystemMessageRenderer) RenderCheckpoint(timestamp string, id int64) error {
markdown := fmt.Sprintf("## [%s] Checkpoint created `%d`", timestamp, id)
rendered := sr.renderer.RenderMarkdown(markdown)
fmt.Print(rendered)
fmt.Printf(rendered)
return nil
}
+3 -19
View File
@@ -161,14 +161,6 @@ func (tr *ToolRenderer) generateToolHeader(tool *types.ToolMessage, verbTense st
}
return fmt.Sprintf("### Cline %s `%s`", action, tool.Path)
case string(types.ToolTypeWebSearch):
if verbTense == "wants to" {
action = "wants to search for"
} else {
action = "is searching for"
}
return fmt.Sprintf("### Cline %s `%s`", action, tool.Path)
case string(types.ToolTypeListCodeDefinitionNames):
if verbTense == "wants to" {
action = "wants to list code definitions in"
@@ -215,8 +207,8 @@ func (tr *ToolRenderer) GenerateToolContentPreview(tool *types.ToolMessage) stri
previewMd := fmt.Sprintf("```\n%s\n```", preview)
return tr.renderMarkdown(previewMd)
case string(types.ToolTypeReadFile), string(types.ToolTypeWebFetch), string(types.ToolTypeWebSearch), string(types.ToolTypeFileDeleted):
// No preview for read/fetch/search operations
case string(types.ToolTypeReadFile), string(types.ToolTypeWebFetch), string(types.ToolTypeFileDeleted):
// No preview for read/fetch operations
return ""
default:
@@ -251,8 +243,7 @@ func (tr *ToolRenderer) GenerateToolContentBody(tool *types.ToolMessage) string
string(types.ToolTypeListFilesRecursive),
string(types.ToolTypeListCodeDefinitionNames),
string(types.ToolTypeSearchFiles),
string(types.ToolTypeWebFetch),
string(types.ToolTypeWebSearch):
string(types.ToolTypeWebFetch):
// Use parser for structured output
preview := toolParser.ParseToolResult(tool)
return tr.renderMarkdown(preview)
@@ -339,13 +330,6 @@ func (tr *ToolRenderer) RenderCommandOutput(output string) string {
return result.String()
}
func (tr *ToolRenderer) RenderCommandPermissionDenied(command string) string {
command = strings.TrimSpace(command)
rendered := tr.renderMarkdown("### Command was denied")
message := fmt.Sprintf("Cline does not have permission to execute this command: `%s`", command)
return fmt.Sprintf("\n%s\n\n%s\n", rendered, message)
}
// RenderUserResponse renders user approval/rejection feedback
func (tr *ToolRenderer) RenderUserResponse(approved bool, feedback string) string {
var symbol, status string
+76 -7
View File
@@ -221,12 +221,83 @@ func (p *ToolResultParser) ParseCodeDefinitions(content string) string {
// ParseWebFetch formats webFetch tool results with content preview
func (p *ToolResultParser) ParseWebFetch(content, url string) string {
return ""
}
if content == "" {
return fmt.Sprintf("*Fetched content from %s (empty response)*", url)
}
// ParseWebSearch formats webSearch tool results
func (p *ToolResultParser) ParseWebSearch(content, query string) string {
return ""
lines := strings.Split(content, "\n")
var result strings.Builder
// Try to extract title
var title string
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "#") && !strings.HasPrefix(trimmed, "##") {
title = strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
break
}
}
if title != "" {
result.WriteString(fmt.Sprintf("**Title:** %s\n\n", title))
}
// Show preview of content
result.WriteString("**Preview:**\n")
charCount := 0
maxChars := 500
previewLines := []string{}
for _, line := range lines {
// Skip markdown headers
if strings.HasPrefix(strings.TrimSpace(line), "#") {
continue
}
trimmed := strings.TrimSpace(line)
if trimmed == "" {
continue
}
if charCount+len(trimmed) > maxChars {
break
}
previewLines = append(previewLines, trimmed)
charCount += len(trimmed)
}
result.WriteString(strings.Join(previewLines, " "))
result.WriteString("...\n\n")
// Extract sections
sections := []string{}
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "##") {
section := strings.TrimSpace(strings.TrimPrefix(trimmed, "##"))
sections = append(sections, section)
if len(sections) >= 5 {
break
}
}
}
if len(sections) > 0 {
result.WriteString("**Sections Found:**\n")
for _, section := range sections {
result.WriteString(fmt.Sprintf("- %s\n", section))
}
result.WriteString("\n")
}
// Word count estimate
wordCount := len(strings.Fields(content))
result.WriteString(fmt.Sprintf("*[Full content: ~%s]*", p.formatWordCount(wordCount)))
return result.String()
}
// detectLanguage returns syntax highlighting language based on file extension
@@ -294,8 +365,6 @@ func (p *ToolResultParser) ParseToolResult(tool *types.ToolMessage) string {
return p.ParseCodeDefinitions(tool.Content)
case "webFetch":
return p.ParseWebFetch(tool.Content, tool.Path)
case "webSearch":
return p.ParseWebSearch(tool.Content, tool.Path)
default:
return tool.Content
}
@@ -14,20 +14,21 @@ import (
"github.com/cline/grpc-go/cline"
)
type ClineInstances struct {
registry *InstanceRegistry
// ClineClients manages Cline instances using the new registry system
type ClineClients struct {
registry *ClientRegistry
}
// NewClineInstances creates a new ClineInstances instance
func NewClineInstances(configPath string) *ClineInstances {
registry := NewInstanceRegistry(configPath)
return &ClineInstances{
// NewClineClients creates a new ClineClients instance
func NewClineClients(configPath string) *ClineClients {
registry := NewClientRegistry(configPath)
return &ClineClients{
registry: registry,
}
}
// Initialize performs cleanup of stale instances
func (c *ClineInstances) Initialize(ctx context.Context) error {
func (c *ClineClients) Initialize(ctx context.Context) error {
// Clean up stale entries (direct SQLite operations)
_ = c.registry.CleanupStaleInstances(ctx)
@@ -35,8 +36,7 @@ func (c *ClineInstances) Initialize(ctx context.Context) error {
}
// StartNewInstance starts a new Cline instance and waits for cline-core to self-register
// An "instance" is a pair of cline-core and cline-host processes
func (c *ClineInstances) StartNewInstance(ctx context.Context, workspaces ...string) (*common.CoreInstanceInfo, error) {
func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstanceInfo, error) {
// Find available ports
corePort, hostPort, err := common.FindAvailablePortPair()
if err != nil {
@@ -48,7 +48,7 @@ func (c *ClineInstances) StartNewInstance(ctx context.Context, workspaces ...str
}
// Start cline-host first
hostCmd, err := startClineHost(hostPort, workspaces)
hostCmd, err := startClineHost(hostPort, corePort)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
@@ -102,7 +102,7 @@ func (c *ClineInstances) StartNewInstance(ctx context.Context, workspaces ...str
if Config.Verbose {
fmt.Println("Services started and registered successfully!")
fmt.Printf(" Address: %s\n", instance.CoreAddress)
fmt.Printf(" Address: %s\n", instance.Address)
fmt.Printf(" Core Port: %d\n", instance.CorePort())
fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort())
fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid)
@@ -120,7 +120,7 @@ func (c *ClineInstances) StartNewInstance(ctx context.Context, workspaces ...str
}
// StartNewInstanceAtPort starts a new Cline instance at the specified port and waits for self-registration
func (c *ClineInstances) StartNewInstanceAtPort(ctx context.Context, corePort int, workspaces ...string) (*common.CoreInstanceInfo, error) {
func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int) (*common.CoreInstanceInfo, error) {
// Find available host port (core port + 1000)
hostPort := corePort + 1000
coreAddress := fmt.Sprintf("localhost:%d", corePort)
@@ -135,7 +135,7 @@ func (c *ClineInstances) StartNewInstanceAtPort(ctx context.Context, corePort in
}
// Start cline-host first
hostCmd, err := startClineHost(hostPort, workspaces)
hostCmd, err := startClineHost(hostPort, corePort)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
@@ -189,7 +189,7 @@ func (c *ClineInstances) StartNewInstanceAtPort(ctx context.Context, corePort in
if Config.Verbose {
fmt.Println("Services started and registered successfully!")
fmt.Printf(" Address: %s\n", instance.CoreAddress)
fmt.Printf(" Address: %s\n", instance.Address)
fmt.Printf(" Core Port: %d\n", instance.CorePort())
fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort())
fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid)
@@ -207,12 +207,12 @@ func (c *ClineInstances) StartNewInstanceAtPort(ctx context.Context, corePort in
}
// GetRegistry returns the client registry
func (c *ClineInstances) GetRegistry() *InstanceRegistry {
func (c *ClineClients) GetRegistry() *ClientRegistry {
return c.registry
}
// EnsureInstanceAtAddress ensures an instance exists at the given address, starting one if needed
func (c *ClineInstances) EnsureInstanceAtAddress(ctx context.Context, address string) error {
func (c *ClineClients) EnsureInstanceAtAddress(ctx context.Context, address string) error {
// Expect host:port everywhere
normalized := address
if normalized == "" {
@@ -230,7 +230,7 @@ func (c *ClineInstances) EnsureInstanceAtAddress(ctx context.Context, address st
return fmt.Errorf("invalid address format %s", address)
}
// Use IPv6-compatible localhost detection
// Use IPv6-compatible localhost detection
if common.IsLocalAddress(host) {
_, err := c.StartNewInstanceAtPort(ctx, port)
if err != nil {
@@ -242,7 +242,7 @@ func (c *ClineInstances) EnsureInstanceAtAddress(ctx context.Context, address st
return fmt.Errorf("cannot start remote instance at %s", normalized)
}
func startClineHost(hostPort int, workspaces []string) (*exec.Cmd, error) {
func startClineHost(hostPort, corePort int) (*exec.Cmd, error) {
if Config.Verbose {
fmt.Printf("Starting cline-host on port %d\n", hostPort)
}
@@ -255,18 +255,10 @@ func startClineHost(hostPort int, workspaces []string) (*exec.Cmd, error) {
binDir := path.Dir(execPath)
clineHostPath := path.Join(binDir, "cline-host")
// Build command arguments
args := []string{
"--verbose",
"--port", fmt.Sprintf("%d", hostPort),
}
for _, ws := range workspaces {
args = append(args, "--workspace", ws)
}
// Start the cline-host process
cmd := exec.Command(clineHostPath, args...)
cmd := exec.Command(clineHostPath,
"--verbose",
"--port", fmt.Sprintf("%d", hostPort))
// Create logs directory in ~/.cline/logs
logsDir := path.Join(Config.ConfigPath, "logs")
@@ -305,7 +297,7 @@ func startClineHost(hostPort int, workspaces []string) (*exec.Cmd, error) {
}
// KillInstanceByAddress kills a Cline instance by its address
func KillInstanceByAddress(ctx context.Context, registry *InstanceRegistry, address string) error {
func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, address string) error {
// Check if the instance exists in the registry
_, err := registry.GetInstance(address)
if err != nil {
@@ -341,7 +333,7 @@ func KillInstanceByAddress(ctx context.Context, registry *InstanceRegistry, addr
if Config.Verbose {
fmt.Printf("Waiting for instance to clean up registry entry...\n")
}
for range 5 {
for i := 0; i < 5; i++ {
time.Sleep(1 * time.Second)
if !registry.HasInstanceAtAddress(address) {
if Config.Verbose {
@@ -355,9 +347,9 @@ func KillInstanceByAddress(ctx context.Context, registry *InstanceRegistry, addr
defaultInstance := registry.GetDefaultInstance()
if defaultInstance == address || defaultInstance == "" {
if len(instances) > 0 {
if err := registry.SetDefaultInstance(instances[0].CoreAddress); err == nil {
if err := registry.SetDefaultInstance(instances[0].Address); err == nil {
if Config.Verbose {
fmt.Printf("Updated default instance to: %s\n", instances[0].CoreAddress)
fmt.Printf("Updated default instance to: %s\n", instances[0].Address)
}
}
}
@@ -416,15 +408,15 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
// This handles the case where we're running from cli/bin/cline
devClineCorePath := path.Join(binDir, "..", "..", "dist-standalone", "cline-core.js")
devInstallDir := path.Join(binDir, "..", "..", "dist-standalone")
if Config.Verbose {
fmt.Printf("Primary location not found, trying development path: %s\n", devClineCorePath)
}
if _, err := os.Stat(devClineCorePath); os.IsNotExist(err) {
return nil, fmt.Errorf("cline-core.js not found at '%s' or '%s'. Please ensure you're running from the correct location or reinstall with 'npm install -g cline'", clineCorePath, devClineCorePath)
}
finalClineCorePath = devClineCorePath
finalInstallDir = devInstallDir
if Config.Verbose {
@@ -483,16 +475,15 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
realNodeModules := path.Join(finalInstallDir, "node_modules")
fakeNodeModules := path.Join(finalInstallDir, "fake_node_modules")
nodePath := fmt.Sprintf("%s%c%s", realNodeModules, os.PathListSeparator, fakeNodeModules)
env = append(env,
fmt.Sprintf("NODE_PATH=%s", nodePath),
// These control gRPC debug logging
//"GRPC_TRACE=all",
//"GRPC_VERBOSITY=DEBUG",
"GRPC_TRACE=all",
"GRPC_VERBOSITY=DEBUG",
"NODE_ENV=development",
)
cmd.Env = env
if Config.Verbose {
fmt.Printf("NODE_PATH set to: %s\n", nodePath)
}
+15 -21
View File
@@ -22,8 +22,8 @@ type GlobalConfig struct {
}
var (
Config *GlobalConfig
Instances *ClineInstances
Config *GlobalConfig
Clients *ClineClients
// Version info - set at build time via ldflags
// Version is the Cline Core version (from root package.json)
@@ -37,16 +37,11 @@ var (
func InitializeGlobalConfig(cfg *GlobalConfig) error {
if cfg.ConfigPath == "" {
// Check CLINE_DIR environment variable first
if clineDir := os.Getenv("CLINE_DIR"); clineDir != "" {
cfg.ConfigPath = clineDir
} else {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
}
// Ensure .cline directory exists
@@ -61,11 +56,11 @@ func InitializeGlobalConfig(cfg *GlobalConfig) error {
// Otherwise lipgloss auto-detects terminal capabilities (default behavior)
Config = cfg
Instances = NewClineInstances(cfg.ConfigPath)
Clients = NewClineClients(cfg.ConfigPath)
// Initialize the clients registry
ctx := context.Background()
if err := Instances.Initialize(ctx); err != nil {
if err := Clients.Initialize(ctx); err != nil {
return fmt.Errorf("failed to initialize clients: %w", err)
}
@@ -76,25 +71,25 @@ func InitializeGlobalConfig(cfg *GlobalConfig) error {
func GetDefaultClient(ctx context.Context) (*client.ClineClient, error) {
if Config.CoreAddress != "" && Config.CoreAddress != fmt.Sprintf("localhost:%d", common.DEFAULT_CLINE_CORE_PORT) {
// User specified a specific address, use that
return Instances.GetRegistry().GetClient(ctx, Config.CoreAddress)
return Clients.GetRegistry().GetClient(ctx, Config.CoreAddress)
}
// Use the default instance from registry
return Instances.GetRegistry().GetDefaultClient(ctx)
return Clients.GetRegistry().GetDefaultClient(ctx)
}
// GetClientForAddress returns a client for a specific address
func GetClientForAddress(ctx context.Context, address string) (*client.ClineClient, error) {
return Instances.GetRegistry().GetClient(ctx, address)
return Clients.GetRegistry().GetClient(ctx, address)
}
// EnsureDefaultInstance ensures a default instance exists
func EnsureDefaultInstance(ctx context.Context) error {
if Instances == nil {
if Clients == nil {
return fmt.Errorf("global clients not initialized")
}
registry := Instances.GetRegistry()
registry := Clients.GetRegistry()
// First, check if there are any instances already registered in SQLite
instances := registry.ListInstances()
@@ -108,12 +103,11 @@ func EnsureDefaultInstance(ctx context.Context) error {
if registry.GetDefaultInstance() == "" {
// No instances exist, start a new one
// Note: StartNewInstance will automatically set it as default since it's the first instance
_, err := Instances.StartNewInstance(ctx)
_, err := Clients.StartNewInstance(ctx)
if err != nil {
return fmt.Errorf("failed to start new default instance: %w", err)
}
}
return nil
}
}
+28 -27
View File
@@ -18,28 +18,28 @@ import (
"google.golang.org/grpc/health/grpc_health_v1"
)
// InstanceRegistry manages Cline client connections using direct SQLite operations
type InstanceRegistry struct {
// ClientRegistry manages Cline client connections using direct SQLite operations
type ClientRegistry struct {
lockManager *sqlite.LockManager
configPath string
}
// NewInstanceRegistry creates a new instance registry
func NewInstanceRegistry(configPath string) *InstanceRegistry {
// NewClientRegistry creates a new client registry
func NewClientRegistry(configPath string) *ClientRegistry {
lockManager, err := sqlite.NewLockManager(configPath)
if err != nil {
// Log error but continue - we can still function without SQLite
log.Fatalf("Warning: Failed to initialize SQLite lock manager: %v\n", err)
}
return &InstanceRegistry{
return &ClientRegistry{
lockManager: lockManager,
configPath: configPath,
}
}
// GetDefaultInstance returns the default instance address from settings file
func (r *InstanceRegistry) GetDefaultInstance() string {
func (r *ClientRegistry) GetDefaultInstance() string {
defaultAddr, err := sqlite.GetDefaultInstance(r.configPath)
if err != nil {
return ""
@@ -48,7 +48,7 @@ func (r *InstanceRegistry) GetDefaultInstance() string {
}
// SetDefaultInstance sets the default instance (writes default.json)
func (r *InstanceRegistry) SetDefaultInstance(address string) error {
func (r *ClientRegistry) SetDefaultInstance(address string) error {
// Verify the instance exists in SQLite
if r.lockManager != nil {
exists, err := r.lockManager.HasInstanceAtAddress(address)
@@ -64,7 +64,7 @@ func (r *InstanceRegistry) SetDefaultInstance(address string) error {
}
// GetInstance returns instance information directly from SQLite
func (r *InstanceRegistry) GetInstance(address string) (*common.CoreInstanceInfo, error) {
func (r *ClientRegistry) GetInstance(address string) (*common.CoreInstanceInfo, error) {
if r.lockManager == nil {
return nil, fmt.Errorf("lock manager not available")
}
@@ -73,7 +73,7 @@ func (r *InstanceRegistry) GetInstance(address string) (*common.CoreInstanceInfo
}
// GetClient returns a connected client for the given address (created on-demand)
func (r *InstanceRegistry) GetClient(ctx context.Context, address string) (*client.ClineClient, error) {
func (r *ClientRegistry) GetClient(ctx context.Context, address string) (*client.ClineClient, error) {
// Verify instance exists in SQLite
if r.lockManager != nil {
exists, err := r.lockManager.HasInstanceAtAddress(address)
@@ -104,7 +104,7 @@ func (r *InstanceRegistry) GetClient(ctx context.Context, address string) (*clie
}
// GetDefaultClient returns a client for the default instance
func (r *InstanceRegistry) GetDefaultClient(ctx context.Context) (*client.ClineClient, error) {
func (r *ClientRegistry) GetDefaultClient(ctx context.Context) (*client.ClineClient, error) {
defaultAddr := r.GetDefaultInstance()
if defaultAddr == "" {
return nil, fmt.Errorf("no default instance configured")
@@ -117,7 +117,7 @@ func (r *InstanceRegistry) GetDefaultClient(ctx context.Context) (*client.ClineC
// Database is unavailable - Return error instead of attempting cleanup
return nil, fmt.Errorf("cannot verify default instance: database unavailable: %w", err)
}
if !exists {
// Instance doesn't exist in database but config file references it
// This is a stale config - remove it and try to find another instance
@@ -127,14 +127,14 @@ func (r *InstanceRegistry) GetDefaultClient(ctx context.Context) (*client.ClineC
} else {
fmt.Printf("Removed stale default instance config (instance %s not found in database)\n", defaultAddr)
}
// Try to find and set a new default instance
instances := r.ListInstances()
if len(instances) > 0 {
if err := r.EnsureDefaultInstance(instances); err != nil {
return nil, fmt.Errorf("failed to set new default instance: %w", err)
}
// Retry with the new default
newDefaultAddr := r.GetDefaultInstance()
if newDefaultAddr != "" {
@@ -142,7 +142,7 @@ func (r *InstanceRegistry) GetDefaultClient(ctx context.Context) (*client.ClineC
return r.GetClient(ctx, newDefaultAddr)
}
}
return nil, fmt.Errorf("no default instance configured")
}
}
@@ -151,7 +151,7 @@ func (r *InstanceRegistry) GetDefaultClient(ctx context.Context) (*client.ClineC
}
// ListInstances returns all registered instances directly from SQLite
func (r *InstanceRegistry) ListInstances() []*common.CoreInstanceInfo {
func (r *ClientRegistry) ListInstances() []*common.CoreInstanceInfo {
if r.lockManager == nil {
return []*common.CoreInstanceInfo{}
}
@@ -170,7 +170,7 @@ func (r *InstanceRegistry) ListInstances() []*common.CoreInstanceInfo {
}
// HasInstanceAtAddress checks if an instance exists at the given address (delegates to SQLite)
func (r *InstanceRegistry) HasInstanceAtAddress(address string) bool {
func (r *ClientRegistry) HasInstanceAtAddress(address string) bool {
if r.lockManager == nil {
return false
}
@@ -185,7 +185,7 @@ func (r *InstanceRegistry) HasInstanceAtAddress(address string) bool {
}
// CleanupStaleInstances removes stale instances using direct SQLite operations
func (r *InstanceRegistry) CleanupStaleInstances(ctx context.Context) error {
func (r *ClientRegistry) CleanupStaleInstances(ctx context.Context) error {
if r.lockManager == nil {
return nil
}
@@ -202,15 +202,15 @@ func (r *InstanceRegistry) CleanupStaleInstances(ctx context.Context) error {
// Try to gracefully shutdown the paired host process before cleanup
fmt.Printf("Attempting to shutdown dangling host service %s for stale cline core instance %s\n",
instance.HostServiceAddress, instance.CoreAddress)
instance.HostServiceAddress, instance.Address)
r.tryShutdownHostProcess(instance.HostServiceAddress)
// Remove from SQLite database
if err := r.lockManager.RemoveInstanceLock(instance.CoreAddress); err != nil {
return fmt.Errorf("failed to remove stale instance %s: %w", instance.CoreAddress, err)
if err := r.lockManager.RemoveInstanceLock(instance.Address); err != nil {
return fmt.Errorf("failed to remove stale instance %s: %w", instance.Address, err)
}
fmt.Printf("Removed stale instance: %s\n", instance.CoreAddress)
fmt.Printf("Removed stale instance: %s\n", instance.Address)
}
}
@@ -218,7 +218,8 @@ func (r *InstanceRegistry) CleanupStaleInstances(ctx context.Context) error {
}
// tryShutdownHostProcess attempts to gracefully shutdown a host process via RPC
func (r *InstanceRegistry) tryShutdownHostProcess(hostServiceAddress string) {
// Best effort, don't throw errors i guess
func (r *ClientRegistry) tryShutdownHostProcess(hostServiceAddress string) {
err := common.RetryOperation(3, 2*time.Second, func() error {
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
@@ -251,7 +252,7 @@ func (r *InstanceRegistry) tryShutdownHostProcess(hostServiceAddress string) {
}
// ListInstancesCleaned performs cleanup and returns instances with health checks
func (r *InstanceRegistry) ListInstancesCleaned(ctx context.Context) ([]*common.CoreInstanceInfo, error) {
func (r *ClientRegistry) ListInstancesCleaned(ctx context.Context) ([]*common.CoreInstanceInfo, error) {
// 1. Clean up stale entries (best-effort)
_ = r.CleanupStaleInstances(ctx)
@@ -267,7 +268,7 @@ func (r *InstanceRegistry) ListInstancesCleaned(ctx context.Context) ([]*common.
}
// EnsureDefaultInstance ensures a default instance is set if instances exist but no default is configured
func (r *InstanceRegistry) EnsureDefaultInstance(instances []*common.CoreInstanceInfo) error {
func (r *ClientRegistry) EnsureDefaultInstance(instances []*common.CoreInstanceInfo) error {
currentDefault := r.GetDefaultInstance()
// If we have no instances, clear any stale default and remove settings file
@@ -282,13 +283,13 @@ func (r *InstanceRegistry) EnsureDefaultInstance(instances []*common.CoreInstanc
// If we have instances but no default, pick the first one
if currentDefault == "" {
return sqlite.SetDefaultInstance(r.configPath, instances[0].CoreAddress)
return sqlite.SetDefaultInstance(r.configPath, instances[0].Address)
}
// Validate current default still exists in the instances
defaultExists := false
for _, instance := range instances {
if instance.CoreAddress == currentDefault {
if instance.Address == currentDefault {
defaultExists = true
break
}
@@ -296,7 +297,7 @@ func (r *InstanceRegistry) EnsureDefaultInstance(instances []*common.CoreInstanc
if !defaultExists {
// Current default doesn't exist, pick a new one from available instances
return sqlite.SetDefaultInstance(r.configPath, instances[0].CoreAddress)
return sqlite.SetDefaultInstance(r.configPath, instances[0].Address)
}
return nil
-1
View File
@@ -25,7 +25,6 @@ type DisplayContext struct {
State *types.ConversationState
Renderer *display.Renderer
ToolRenderer *display.ToolRenderer
HookRenderer *display.HookRenderer
SystemRenderer *display.SystemMessageRenderer
IsLast bool
IsPartial bool
+12 -40
View File
@@ -6,8 +6,8 @@ import (
"strings"
"github.com/cline/cli/pkg/cli/clerror"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/cli/pkg/cli/output"
)
// SayHandler handles SAY type messages
@@ -90,12 +90,6 @@ func (h *SayHandler) Handle(msg *types.ClineMessage, dc *DisplayContext) error {
return h.handleInfo(msg, dc)
case string(types.SayTypeTaskProgress):
return h.handleTaskProgress(msg, dc)
case string(types.SayTypeHookStatus):
return h.handleHookStatus(msg, dc)
case string(types.SayTypeHookOutputStream):
return h.handleHookOutputStream(msg, dc)
case string(types.SayTypeCommandPermissionDenied):
return h.handleCommandPermissionDenied(msg, dc)
default:
return h.handleDefault(msg, dc)
}
@@ -248,18 +242,19 @@ func (h *SayHandler) handleCompletionResult(msg *types.ClineMessage, dc *Display
}
func formatUserMessage(text string) string {
lines := strings.Split(text, "\n")
// Wrap each line in backticks
for i, line := range lines {
if line != "" {
lines[i] = fmt.Sprintf("`%s`", line)
}
}
return strings.Join(lines, "\n")
lines := strings.Split(text, "\n")
// Wrap each line in backticks
for i, line := range lines {
if line != "" {
lines[i] = fmt.Sprintf("`%s`", line)
}
}
return strings.Join(lines, "\n")
}
// handleUserFeedback handles user feedback messages
func (h *SayHandler) handleUserFeedback(msg *types.ClineMessage, dc *DisplayContext) error {
if msg.Text != "" {
@@ -348,18 +343,6 @@ func (h *SayHandler) handleCommandOutput(msg *types.ClineMessage, dc *DisplayCon
return nil
}
func (h *SayHandler) handleCommandPermissionDenied(msg *types.ClineMessage, dc *DisplayContext) error {
if msg.Text == "" {
return nil
}
// Use unified ToolRenderer
rendered := dc.ToolRenderer.RenderCommandPermissionDenied(msg.Text)
output.Print(rendered)
return nil
}
func (h *SayHandler) handleTool(msg *types.ClineMessage, dc *DisplayContext) error {
var tool types.ToolMessage
if err := json.Unmarshal([]byte(msg.Text), &tool); err != nil {
@@ -534,16 +517,5 @@ func (h *SayHandler) handleTaskProgress(msg *types.ClineMessage, dc *DisplayCont
// handleDefault handles unknown SAY message types
func (h *SayHandler) handleDefault(msg *types.ClineMessage, dc *DisplayContext) error {
// Debug: log unhandled say types to help identify missing cases using output.Printf for CLI consistency
if dc.Verbose {
output.Printf("[DEBUG] Unhandled SAY type: '%s' (text preview: %s)\n", msg.Say, truncateForDisplay(msg.Text, 50))
}
return dc.Renderer.RenderMessage("SAY", msg.Text, true)
}
func truncateForDisplay(text string, maxLen int) string {
if len(text) <= maxLen {
return text
}
return text[:maxLen] + "..."
}
-198
View File
@@ -1,198 +0,0 @@
package handlers
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/types"
)
// Hook-specific SAY handlers and helpers.
// Kept in a separate file to keep say_handlers.go focused on routing.
// handleHookStatus handles hook execution status messages.
func (h *SayHandler) handleHookStatus(msg *types.ClineMessage, dc *DisplayContext) error {
hook, err := parseHookMessage(msg.Text)
if err != nil {
// Fallback to basic output if JSON parsing fails
return dc.Renderer.RenderMessage("HOOK", msg.Text, true)
}
logHookDebug(hook, dc)
hook.ScriptPaths = formatHookPaths(hook.ScriptPaths)
return renderHookStatus(hook, dc)
}
// handleHookOutputStream handles streaming output from hooks.
//
// Hook stdout/stderr currently arrives line-by-line from the backend as
// `hook_output_stream` messages. The CLI intentionally suppresses these by default
// to keep the transcript high-signal.
//
// In --verbose mode, we print each non-empty line prefixed with "HOOK>" for easy grepping.
// Future work could associate these lines with a specific hook execution and render them
// as a grouped section under the hook status header.
func (h *SayHandler) handleHookOutputStream(msg *types.ClineMessage, dc *DisplayContext) error {
if !dc.Verbose {
return nil
}
line := strings.TrimRight(msg.Text, "\n")
if strings.TrimSpace(line) == "" {
return nil
}
output.Printf("HOOK> %s\n", line)
return nil
}
func parseHookMessage(jsonText string) (types.HookMessage, error) {
var hook types.HookMessage
if err := json.Unmarshal([]byte(jsonText), &hook); err != nil {
return types.HookMessage{}, err
}
return hook, nil
}
func logHookDebug(hook types.HookMessage, dc *DisplayContext) {
if dc.Verbose {
output.Printf("[DEBUG] Hook parsed: name=%s, status=%s, toolName=%s, scriptPaths=%v\n",
hook.HookName, hook.Status, hook.ToolName, hook.ScriptPaths)
}
}
func formatHookPaths(paths []string) []string {
if len(paths) == 0 {
return paths
}
formatted := make([]string, 0, len(paths))
for _, p := range paths {
if strings.TrimSpace(p) == "" {
continue
}
formatted = append(formatted, formatHookPath(p))
}
return formatted
}
func renderHookStatus(hook types.HookMessage, dc *DisplayContext) error {
if dc.HookRenderer != nil {
rendered := dc.HookRenderer.RenderHookStatus(hook)
// Match ToolRenderers spacing: one leading newline, one trailing newline.
output.Print("\n")
output.Print(rendered)
output.Print("\n")
return nil
}
// Fallback: if HookRenderer not available
return dc.Renderer.RenderMessage("HOOK", fmt.Sprintf("%s %s", hook.HookName, hook.Status), true)
}
func formatHookPath(fullPath string) string {
// Normalize for display and prefix checks. This is display-only; do not use for IO.
normalized := normalizeSlashes(fullPath)
// If this is a repo-scoped hook script (i.e. lives under <repo>/.clinerules/hooks/),
// always include the repo name for disambiguation even in single-repo workspaces.
//
// This intentionally runs before workspace-relative formatting, which would otherwise
// collapse to ".clinerules/hooks/..." and lose the repo context.
if p, ok := tryRepoScopedHooksPath(normalized); ok {
return p
}
// Prefer workspace-relative paths first for readability, since most hook scripts
// live inside the current project.
if p, ok := tryWorkspaceRelativeHookPath(normalized); ok {
return p
}
// Follow existing CLI pattern: resolve home via os.UserHomeDir.
if p, ok := tryHomeTildePath(normalized); ok {
return p
}
// Secondary heuristic: if hook lives under <repo>/.clinerules, collapse to repo-relative.
if p, ok := tryRepoRelativeHookPath(normalized); ok {
return p
}
return fallbackLastComponents(normalized, 3)
}
func normalizeSlashes(p string) string {
return filepath.ToSlash(p)
}
func tryWorkspaceRelativeHookPath(normalizedPath string) (string, bool) {
root, err := os.Getwd()
if err != nil {
return "", false
}
// filepath.Rel expects OS-native paths, so we need to convert the normalized path
// back to OS-native format before calling Rel, then normalize the result for display.
targetOS := filepath.FromSlash(normalizedPath)
rel, err := filepath.Rel(root, targetOS)
if err != nil {
return "", false
}
// If it's not within the workspace, Rel will start with "..".
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", false
}
return normalizeSlashes(rel), true
}
func tryHomeTildePath(normalizedPath string) (string, bool) {
homeDir, err := os.UserHomeDir()
if err != nil || strings.TrimSpace(homeDir) == "" {
return "", false
}
homeDir = normalizeSlashes(homeDir)
if !strings.HasPrefix(normalizedPath, homeDir) {
return "", false
}
rel := strings.TrimPrefix(normalizedPath, homeDir)
rel = strings.TrimPrefix(rel, "/")
return "~/" + rel, true
}
func tryRepoRelativeHookPath(normalizedPath string) (string, bool) {
parts := strings.Split(normalizedPath, "/")
for i, part := range parts {
if part == ".clinerules" && i > 0 {
repoName := parts[i-1]
return repoName + "/" + strings.Join(parts[i:], "/"), true
}
}
return "", false
}
// tryRepoScopedHooksPath returns a repo-prefixed path like
// "myrepo/.clinerules/hooks/PreToolUse" when the given path points to a hook script
// under a repo's .clinerules/hooks directory.
//
// This is more specific than tryRepoRelativeHookPath and is used to ensure hook script
// paths always include repo context.
func tryRepoScopedHooksPath(normalizedPath string) (string, bool) {
// Fast path check to avoid split work.
if !strings.Contains(normalizedPath, "/.clinerules/hooks/") {
return "", false
}
return tryRepoRelativeHookPath(normalizedPath)
}
func fallbackLastComponents(normalizedPath string, n int) string {
parts := strings.Split(normalizedPath, "/")
if len(parts) >= n {
return strings.Join(parts[len(parts)-n:], "/")
}
return normalizedPath
}
@@ -1,41 +0,0 @@
package handlers
import (
"os"
"path/filepath"
"testing"
)
func TestFormatHookPath_PrefersWorkspaceRelative(t *testing.T) {
// Create a stable workspace root (avoid TempDir's nested ".../001" patterns)
// so that workspace-relative formatting is deterministic.
root := filepath.Join(t.TempDir(), "workspace")
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd: %v", err)
}
defer func() { _ = os.Chdir(oldWd) }()
if err := os.Chdir(root); err != nil {
t.Fatalf("Chdir: %v", err)
}
inside := filepath.Join(root, ".clinerules", "hooks", "pre.sh")
got := formatHookPath(inside)
// Repo-scoped hook scripts should always include the repo name (the directory
// immediately containing .clinerules) even when running inside that repo.
expected := "workspace/" + filepath.ToSlash(filepath.Join(".clinerules", "hooks", "pre.sh"))
if got != expected {
t.Fatalf("expected formatted path to be %q. got=%q", expected, got)
}
}
func TestFormatHookPath_FallsBackToLastComponents(t *testing.T) {
// Use an obviously non-workspace path (relative, but not prefixed with cwd).
got := formatHookPath("/var/tmp/foo/bar/baz.sh")
if got != "foo/bar/baz.sh" {
t.Fatalf("expected last 3 components fallback, got=%q", got)
}
}
-35
View File
@@ -1,35 +0,0 @@
package handlers
import (
"os"
"testing"
)
func TestFormatHookPath_HomeDirToTilde(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil || home == "" {
t.Skip("home dir not available; skipping")
}
got := formatHookPath(home + "/Documents/Cline/Hooks/TaskStart")
want := "~/Documents/Cline/Hooks/TaskStart"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFormatHookPath_WorkspaceRepoRelative(t *testing.T) {
got := formatHookPath("/Users/alice/dev/repo-name/.clinerules/hooks/TaskStart")
want := "repo-name/.clinerules/hooks/TaskStart"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFormatHookPath_FallbackLast3Components(t *testing.T) {
got := formatHookPath("/a/b/c/d/e")
want := "c/d/e"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
+27 -27
View File
@@ -92,12 +92,12 @@ func newInstanceKillCommand() *cobra.Command {
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if global.Instances == nil {
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
ctx := cmd.Context()
registry := global.Instances.GetRegistry()
registry := global.Clients.GetRegistry()
if killAllCLI {
return killAllCLIInstances(ctx, registry)
@@ -112,7 +112,7 @@ func newInstanceKillCommand() *cobra.Command {
return cmd
}
func killAllCLIInstances(ctx context.Context, registry *global.InstanceRegistry) error {
func killAllCLIInstances(ctx context.Context, registry *global.ClientRegistry) error {
// Get all instances from registry
instances, err := registry.ListInstancesCleaned(ctx)
if err != nil {
@@ -135,7 +135,7 @@ func killAllCLIInstances(ctx context.Context, registry *global.InstanceRegistry)
cliInstances = append(cliInstances, instance)
} else {
skippedNonCLI++
fmt.Printf("⊘ Skipping %s instance: %s\n", platform, instance.CoreAddress)
fmt.Printf("⊘ Skipping %s instance: %s\n", platform, instance.Address)
}
}
}
@@ -160,16 +160,16 @@ func killAllCLIInstances(ctx context.Context, registry *global.InstanceRegistry)
// Kill all CLI instances
for _, instance := range cliInstances {
result := killInstanceProcess(ctx, registry, instance.CoreAddress)
result := killInstanceProcess(ctx, registry, instance.Address)
killResults = append(killResults, result)
if result.err != nil {
fmt.Printf("✗ Failed to kill %s: %v\n", instance.CoreAddress, result.err)
fmt.Printf("✗ Failed to kill %s: %v\n", instance.Address, result.err)
} else if result.alreadyDead {
fmt.Printf("⚠ Instance %s appears to be already dead\n", instance.CoreAddress)
fmt.Printf("⚠ Instance %s appears to be already dead\n", instance.Address)
} else {
fmt.Printf("✓ Killed %s (PID %d)\n", instance.CoreAddress, result.pid)
killedAddresses[instance.CoreAddress] = true
fmt.Printf("✓ Killed %s (PID %d)\n", instance.Address, result.pid)
killedAddresses[instance.Address] = true
}
}
@@ -190,8 +190,8 @@ func killAllCLIInstances(ctx context.Context, registry *global.InstanceRegistry)
// Check if any of the killed instances are still in the registry
stillPresent := []string{}
for _, remaining := range remainingInstances {
if killedAddresses[remaining.CoreAddress] {
stillPresent = append(stillPresent, remaining.CoreAddress)
if killedAddresses[remaining.Address] {
stillPresent = append(stillPresent, remaining.Address)
}
}
@@ -247,7 +247,7 @@ type killResult struct {
err error
}
func killInstanceProcess(ctx context.Context, registry *global.InstanceRegistry, address string) killResult {
func killInstanceProcess(ctx context.Context, registry *global.ClientRegistry, address string) killResult {
// Get gRPC client and process info
client, err := registry.GetClient(ctx, address)
if err != nil {
@@ -276,12 +276,12 @@ func newInstanceListCommand() *cobra.Command {
Short: "List all registered Cline instances",
Long: `List all registered Cline instances with their status and connection details.`,
RunE: func(cmd *cobra.Command, args []string) error {
if global.Instances == nil {
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
ctx := cmd.Context()
registry := global.Instances.GetRegistry()
registry := global.Clients.GetRegistry()
// Load, cleanup stale local entries, and update health
instances, err := registry.ListInstancesCleaned(ctx)
@@ -310,7 +310,7 @@ func newInstanceListCommand() *cobra.Command {
var rows []instanceRow
for _, instance := range instances {
isDefault := ""
if instance.CoreAddress == defaultInstance {
if instance.Address == defaultInstance {
isDefault = "✓"
}
@@ -324,7 +324,7 @@ func newInstanceListCommand() *cobra.Command {
platform := platformNA
if instance.Status == grpc_health_v1.HealthCheckResponse_SERVING {
// Get PID from core
if client, err := registry.GetClient(ctx, instance.CoreAddress); err == nil {
if client, err := registry.GetClient(ctx, instance.Address); err == nil {
if processInfo, err := client.State.GetProcessInfo(ctx, &cline.EmptyRequest{}); err == nil {
pid = fmt.Sprintf("%d", processInfo.ProcessId)
// Update version from RPC if available
@@ -341,7 +341,7 @@ func newInstanceListCommand() *cobra.Command {
}
rows = append(rows, instanceRow{
address: instance.CoreAddress,
address: instance.Address,
status: instance.Status.String(),
version: instance.Version,
lastSeen: lastSeen,
@@ -407,7 +407,7 @@ func newInstanceListCommand() *cobra.Command {
fmt.Print(strings.TrimLeft(rendered, "\n"))
}
fmt.Println()
fmt.Println("\n")
}
}
@@ -428,11 +428,11 @@ func newInstanceDefaultCommand() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
address := args[0]
if global.Instances == nil {
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
registry := global.Instances.GetRegistry()
registry := global.Clients.GetRegistry()
// Verify the instance exists
_, err := registry.GetInstance(address)
@@ -464,34 +464,34 @@ func newInstanceNewCommand() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if global.Instances == nil {
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
fmt.Println("Starting new Cline instance...")
instance, err := global.Instances.StartNewInstance(ctx)
instance, err := global.Clients.StartNewInstance(ctx)
if err != nil {
return fmt.Errorf("failed to start instance: %w", err)
}
fmt.Printf("Successfully started new instance:\n")
fmt.Printf(" Address: %s\n", instance.CoreAddress)
fmt.Printf(" Address: %s\n", instance.Address)
fmt.Printf(" Core Port: %d\n", instance.CorePort())
fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort())
registry := global.Instances.GetRegistry()
registry := global.Clients.GetRegistry()
// If --default flag provided, set this instance as the default
if setDefault {
if err := registry.SetDefaultInstance(instance.CoreAddress); err != nil {
if err := registry.SetDefaultInstance(instance.Address); err != nil {
fmt.Printf("Warning: Failed to set as default: %v\n", err)
} else {
fmt.Printf(" Status: Set as default instance\n")
}
} else {
// Otherwise, check if EnsureDefaultInstance already set it as default
if registry.GetDefaultInstance() == instance.CoreAddress {
if registry.GetDefaultInstance() == instance.Address {
fmt.Printf(" Status: Default instance\n")
}
}
@@ -503,4 +503,4 @@ func newInstanceNewCommand() *cobra.Command {
cmd.Flags().BoolVarP(&setDefault, "default", "d", false, "set as default instance")
return cmd
}
}
+23 -146
View File
@@ -9,13 +9,12 @@ import (
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/slash"
)
// InputType represents the type of input being collected
type InputType int
const INPUT_WIDTH = 46
const INPUT_WIDTH = 46
const (
InputTypeMessage InputType = iota
@@ -25,11 +24,11 @@ const (
// InputSubmitMsg is sent when the user submits input
type InputSubmitMsg struct {
Value string
InputType InputType
Approved bool // For approval type
NeedsFeedback bool // For approval type
NoAskAgain bool // For approval type - indicates "don't ask again" was selected
Value string
InputType InputType
Approved bool // For approval type
NeedsFeedback bool // For approval type
NoAskAgain bool // For approval type - indicates "don't ask again" was selected
}
// InputCancelMsg is sent when the user cancels input (Ctrl+C)
@@ -37,8 +36,8 @@ type InputCancelMsg struct{}
// ChangeInputTypeMsg changes the current input type
type ChangeInputTypeMsg struct {
InputType InputType
Title string
InputType InputType
Title string
Placeholder string
}
@@ -58,7 +57,7 @@ type InputModel struct {
placeholder string
currentMode string // "plan" or "act"
width int
lastHeight int // Track height for cleanup on submit
lastHeight int // Track height for cleanup on submit
// For approval type
approvalOptions []string
@@ -67,9 +66,6 @@ type InputModel struct {
// Styles (huh-inspired theme)
styles fieldStyles
// Slash command autocomplete dropdown
completion CompletionModel
}
// fieldStyles holds the styling for the input field
@@ -119,17 +115,12 @@ func newFieldStyles() fieldStyles {
// NewInputModel creates a new input model
func NewInputModel(inputType InputType, title, placeholder, currentMode string) InputModel {
return NewInputModelWithRegistry(inputType, title, placeholder, currentMode, nil)
}
// NewInputModelWithRegistry creates a new input model with slash command autocomplete support
func NewInputModelWithRegistry(inputType InputType, title, placeholder, currentMode string, registry *slash.Registry) InputModel {
ta := textarea.New()
ta.Placeholder = placeholder
ta.Focus()
ta.CharLimit = 0
ta.ShowLineNumbers = false
ta.Prompt = "" // Remove prompt prefix (this is what adds the inner border!)
ta.Prompt = "" // Remove prompt prefix (this is what adds the inner border!)
ta.SetHeight(5)
// Don't set width here - let WindowSizeMsg handle it
ta.SetWidth(INPUT_WIDTH)
@@ -147,11 +138,11 @@ func NewInputModelWithRegistry(inputType InputType, title, placeholder, currentM
cursorColor = lipgloss.Color("39") // Blue for act
}
ta.FocusedStyle.CursorLine = lipgloss.NewStyle() // No cursor line highlighting
ta.FocusedStyle.EndOfBuffer = lipgloss.NewStyle() // No end-of-buffer styling
ta.FocusedStyle.CursorLine = lipgloss.NewStyle() // No cursor line highlighting
ta.FocusedStyle.EndOfBuffer = lipgloss.NewStyle() // No end-of-buffer styling
ta.FocusedStyle.Placeholder = styles.placeholder
ta.FocusedStyle.Text = styles.textArea
ta.FocusedStyle.Prompt = lipgloss.NewStyle() // No prompt styling
ta.FocusedStyle.Prompt = lipgloss.NewStyle() // No prompt styling
ta.Cursor.Style = lipgloss.NewStyle().Foreground(cursorColor)
ta.Cursor.TextStyle = styles.textArea
@@ -163,7 +154,6 @@ func NewInputModelWithRegistry(inputType InputType, title, placeholder, currentM
currentMode: currentMode,
width: 0, // Will be set by first WindowSizeMsg
styles: styles,
completion: NewCompletionModel(registry),
}
// For approval type, set up options
@@ -227,6 +217,13 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, nil
default:
// Forward all other messages to textarea (including blink ticks)
if !m.suspended && (m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback) {
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
}
case tea.KeyMsg:
if m.suspended {
return m, nil
@@ -234,31 +231,6 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Handle keys for text input types (Message/Feedback)
if m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback {
// When completion menu is visible, let it handle navigation keys first
if m.completion.Visible() {
// ctrl+c always cancels, even with dropdown open
if msg.String() == "ctrl+c" {
return m, func() tea.Msg { return InputCancelMsg{} }
}
var handled bool
m.completion, cmd, handled = m.completion.Update(msg)
if handled {
// Check if a completion was selected
if applied := m.completion.Apply(); applied != "" {
m.textarea.SetValue(applied)
m.textarea.CursorEnd()
}
return m, cmd
}
// Key not handled by completion - pass to textarea and update completion
m.textarea, cmd = m.textarea.Update(msg)
m.completion.CheckInput(m.textarea.Value())
return m, cmd
}
// Normal key handling when completion menu is NOT visible
switch msg.String() {
case "ctrl+c":
return m, func() tea.Msg { return InputCancelMsg{} }
@@ -267,11 +239,6 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Open external editor (like huh does)
return m, m.openEditor()
case "tab":
// Tab without dropdown visible - do nothing special
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
case "enter":
// Intercept enter for submit (textarea handles alt+enter and ctrl+j for newlines)
return m.handleSubmit()
@@ -282,9 +249,8 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, cmd
}
// Pass all other keys to textarea, then check for slash completion
// Pass all other keys to textarea (including alt+enter, ctrl+j for newlines)
m.textarea, cmd = m.textarea.Update(msg)
m.completion.CheckInput(m.textarea.Value())
return m, cmd
}
@@ -310,13 +276,6 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
}
}
default:
// Forward all other messages to textarea (including blink ticks)
if !m.suspended && (m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback) {
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
}
}
return m, nil
@@ -348,7 +307,7 @@ func (m *InputModel) handleSubmit() (tea.Model, tea.Cmd) {
return ChangeInputTypeMsg{
InputType: InputTypeFeedback,
Title: "Your feedback",
Placeholder: "/plan or /act to switch modes\nctrl+e to open editor\nctrl+c to exit",
Placeholder: "/plan or /act to switch modes\nctrl+e to open editor",
}
}
}
@@ -406,11 +365,6 @@ func (m *InputModel) View() string {
case InputTypeMessage, InputTypeFeedback:
parts = append(parts, m.textarea.View())
// Render completion dropdown if visible
if m.completion.Visible() {
parts = append(parts, m.completion.View())
}
case InputTypeApproval:
var options []string
for i, option := range m.approvalOptions {
@@ -457,7 +411,7 @@ func (m *InputModel) Clone() *InputModel {
ta.ShowLineNumbers = false
ta.Prompt = ""
ta.SetHeight(5)
ta.SetWidth(INPUT_WIDTH)
ta.SetWidth(INPUT_WIDTH)
ta.Focus()
// Configure keybindings
@@ -492,7 +446,6 @@ func (m *InputModel) Clone() *InputModel {
selectedOption: m.selectedOption,
pendingApproval: m.pendingApproval, // Preserve approval decision
styles: m.styles,
completion: NewCompletionModel(m.completion.registry), // Preserve registry, start fresh state
}
return clone
@@ -542,79 +495,3 @@ func (m *InputModel) openEditor() tea.Cmd {
return editorFinishedMsg{content: content, err: err}
})
}
// SetSlashRegistry sets the slash command registry for autocomplete
func (m *InputModel) SetSlashRegistry(registry *slash.Registry) {
m.completion.SetRegistry(registry)
}
// initialPromptWrapper wraps InputModel to capture the submit result for initial task prompts
type initialPromptWrapper struct {
model *InputModel
result string
cancelled bool
}
func (w *initialPromptWrapper) Init() tea.Cmd {
return w.model.Init()
}
func (w *initialPromptWrapper) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case InputSubmitMsg:
w.result = msg.Value
clearCodes := w.model.ClearScreen()
if clearCodes != "" {
fmt.Print(clearCodes)
}
return w, tea.Quit
case InputCancelMsg:
w.cancelled = true
clearCodes := w.model.ClearScreen()
if clearCodes != "" {
fmt.Print(clearCodes)
}
return w, tea.Quit
}
// Forward to wrapped model
_, cmd := w.model.Update(msg)
return w, cmd
}
func (w *initialPromptWrapper) View() string {
return w.model.View()
}
// ErrUserAborted is returned when the user cancels the input prompt
var ErrUserAborted = fmt.Errorf("user aborted")
// PromptForInitialTask displays an interactive prompt for the initial task with slash command autocomplete.
// Returns the entered text, or ErrUserAborted if cancelled.
func PromptForInitialTask(title, placeholder, mode string, registry *slash.Registry) (string, error) {
model := NewInputModelWithRegistry(
InputTypeMessage,
title,
placeholder,
mode,
registry,
)
wrapper := &initialPromptWrapper{
model: &model,
}
p := tea.NewProgram(wrapper)
_, err := p.Run()
if err != nil {
return "", fmt.Errorf("input prompt failed: %w", err)
}
if wrapper.cancelled {
return "", ErrUserAborted
}
return strings.TrimSpace(wrapper.result), nil
}
-265
View File
@@ -1,265 +0,0 @@
package output
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/slash"
)
const maxVisibleCompletions = 7
// completionStyles holds the styling for the completion dropdown
type completionStyles struct {
menu lipgloss.Style
selected lipgloss.Style
normalName lipgloss.Style
description lipgloss.Style
scrollIndicator lipgloss.Style
}
// newCompletionStyles creates the default styles for the completion dropdown
func newCompletionStyles() completionStyles {
return completionStyles{
menu: lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("238")).
Padding(0, 1),
selected: lipgloss.NewStyle().
Background(lipgloss.Color("62")).
Foreground(lipgloss.Color("230")),
normalName: lipgloss.NewStyle().
Foreground(lipgloss.AdaptiveColor{Light: "235", Dark: "252"}),
description: lipgloss.NewStyle().
Foreground(lipgloss.Color("243")),
scrollIndicator: lipgloss.NewStyle().
Foreground(lipgloss.Color("243")),
}
}
// CompletionModel is a Bubbletea model for slash command autocomplete dropdown
type CompletionModel struct {
registry *slash.Registry
visible bool
matches []slash.Command
index int // selected item (0-based)
scroll int // scroll offset for long lists
styles completionStyles
// pendingApply holds the command to apply after selection
pendingApply string
}
// NewCompletionModel creates a new completion model with the given registry
func NewCompletionModel(registry *slash.Registry) CompletionModel {
return CompletionModel{
registry: registry,
styles: newCompletionStyles(),
}
}
// SetRegistry sets the slash command registry
func (m *CompletionModel) SetRegistry(registry *slash.Registry) {
m.registry = registry
}
// Visible returns whether the completion dropdown is currently visible
func (m CompletionModel) Visible() bool {
return m.visible
}
// Update handles key messages for the completion dropdown.
// Returns the updated model, any commands, and whether the key was handled.
// If handled is true, the parent should NOT pass the key to the textarea.
func (m CompletionModel) Update(msg tea.Msg) (CompletionModel, tea.Cmd, bool) {
if !m.visible {
return m, nil, false
}
keyMsg, ok := msg.(tea.KeyMsg)
if !ok {
return m, nil, false
}
switch keyMsg.String() {
case "up":
m.navigateUp()
return m, nil, true
case "down":
m.navigateDown()
return m, nil, true
case "tab", "enter":
// Select the current completion
if len(m.matches) > 0 {
selected := m.matches[m.index]
m.pendingApply = "/" + selected.Name + " "
}
m.Hide()
return m, nil, true
case "esc":
m.Hide()
return m, nil, true
}
// Key not handled by completion - let parent process it
return m, nil, false
}
// CheckInput updates the completion state based on the current input value.
// Call this after each input change to show/hide/update the dropdown.
func (m *CompletionModel) CheckInput(value string) {
if m.registry == nil {
return
}
// Only activate if input starts with "/" (first character requirement)
if !strings.HasPrefix(value, "/") {
m.Hide()
return
}
// Extract the command being typed (everything after "/" until space/newline)
rest := value[1:] // Everything after the "/"
// If there's whitespace, the command is complete - hide dropdown
if idx := strings.IndexAny(rest, " \n\t"); idx != -1 {
m.Hide()
return
}
// Update matches based on prefix
m.updateMatches(rest)
m.visible = len(m.matches) > 0
}
// Apply returns the command string to insert (if any) and clears the pending state.
// The parent should call this after Update returns handled=true for tab/enter.
func (m *CompletionModel) Apply() string {
result := m.pendingApply
m.pendingApply = ""
return result
}
// Hide hides the completion dropdown and resets state
func (m *CompletionModel) Hide() {
m.visible = false
m.matches = nil
m.index = 0
m.scroll = 0
}
// View renders the completion dropdown
func (m CompletionModel) View() string {
if !m.visible || len(m.matches) == 0 {
return ""
}
var lines []string
// Calculate visible range
endIdx := min(m.scroll+maxVisibleCompletions, len(m.matches))
// Show scroll indicator if there are items above
if m.scroll > 0 {
lines = append(lines, m.styles.scrollIndicator.Render(" ↑ more"))
}
// Find the longest command name for alignment
maxNameLen := 0
for _, cmd := range m.matches {
nameLen := len(cmd.Name) + 1 // +1 for the "/"
if nameLen > maxNameLen {
maxNameLen = nameLen
}
}
// Cap at reasonable width
if maxNameLen > 15 {
maxNameLen = 15
}
// Render visible items
for i := m.scroll; i < endIdx; i++ {
cmd := m.matches[i]
name := "/" + cmd.Name
desc := cmd.Description
// Truncate description if too long
maxDescLen := 35
if len(desc) > maxDescLen {
desc = desc[:maxDescLen-3] + "..."
}
// Pad name for alignment
paddedName := fmt.Sprintf("%-*s", maxNameLen, name)
if i == m.index {
// Selected item - highlight the entire line
line := fmt.Sprintf("> %s %s", paddedName, desc)
lines = append(lines, m.styles.selected.Render(line))
} else {
// Normal item
line := fmt.Sprintf(" %s %s", m.styles.normalName.Render(paddedName), m.styles.description.Render(desc))
lines = append(lines, line)
}
}
// Show scroll indicator if there are items below
if endIdx < len(m.matches) {
lines = append(lines, m.styles.scrollIndicator.Render(" ↓ more"))
}
return m.styles.menu.Render(strings.Join(lines, "\n"))
}
// updateMatches filters commands by prefix and updates the matches list
func (m *CompletionModel) updateMatches(prefix string) {
if m.registry == nil {
m.matches = nil
return
}
m.matches = m.registry.GetMatching(prefix)
// Reset selection if out of bounds
if m.index >= len(m.matches) {
m.index = 0
m.scroll = 0
}
m.adjustScroll()
}
// navigateUp moves selection up in the dropdown
func (m *CompletionModel) navigateUp() {
if len(m.matches) == 0 {
return
}
m.index--
if m.index < 0 {
m.index = len(m.matches) - 1
}
m.adjustScroll()
}
// navigateDown moves selection down in the dropdown
func (m *CompletionModel) navigateDown() {
if len(m.matches) == 0 {
return
}
m.index++
if m.index >= len(m.matches) {
m.index = 0
}
m.adjustScroll()
}
// adjustScroll ensures the selected item is visible in the dropdown
func (m *CompletionModel) adjustScroll() {
if m.index < m.scroll {
m.scroll = m.index
} else if m.index >= m.scroll+maxVisibleCompletions {
m.scroll = m.index - maxVisibleCompletions + 1
}
}
-142
View File
@@ -1,142 +0,0 @@
package slash
import (
"context"
"fmt"
"strings"
"sync"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/grpc-go/cline"
)
// Command represents a slash command available for autocomplete
type Command struct {
Name string
Description string
Section string // "default", "custom", or "cli"
CLICompatible bool
}
// Registry holds available slash commands for autocomplete
type Registry struct {
mu sync.RWMutex
commands []Command
}
// CLI-local commands (handled by CLI, not sent to backend)
var cliLocalCommands = []Command{
{Name: "plan", Description: "Switch to plan mode", Section: "cli", CLICompatible: true},
{Name: "act", Description: "Switch to act mode", Section: "cli", CLICompatible: true},
{Name: "cancel", Description: "Cancel the current task", Section: "cli", CLICompatible: true},
{Name: "exit", Description: "Exit follow mode", Section: "cli", CLICompatible: true},
}
// NewRegistry creates a new slash command registry
func NewRegistry(ctx context.Context) *Registry {
defaultCommands := append([]Command{}, cliLocalCommands...)
r := &Registry{
commands: defaultCommands,
}
r.FetchFromBackend(ctx)
return r
}
// FetchFromBackend fetches available commands from cline-core backend
func (r *Registry) FetchFromBackend(ctx context.Context) error {
grpcClient, err := global.GetDefaultClient(ctx)
if err != nil && global.Config.Verbose {
fmt.Printf("Warning: could not get gRPC client: %v\n", err)
return nil
}
resp, err := grpcClient.Slash.GetAvailableSlashCommands(ctx, &cline.EmptyRequest{})
if err != nil && global.Config.Verbose {
fmt.Printf("Warning: could not get gRPC client: %v\n", err)
return nil
}
r.mu.Lock()
defer r.mu.Unlock()
// Add backend commands (only CLI-compatible ones)
for _, cmd := range resp.Commands {
if cmd.CliCompatible {
r.commands = append(r.commands, Command{
Name: cmd.Name,
Description: cmd.Description,
Section: cmd.Section,
CLICompatible: cmd.CliCompatible,
})
}
}
return nil
}
// GetMatching returns commands that start with the given prefix (case-insensitive)
func (r *Registry) GetMatching(prefix string) []Command {
r.mu.RLock()
defer r.mu.RUnlock()
prefix = strings.ToLower(prefix)
var matches []Command
for _, cmd := range r.commands {
if strings.HasPrefix(strings.ToLower(cmd.Name), prefix) {
matches = append(matches, cmd)
}
}
return matches
}
// IsValid checks if a command name is valid
func (r *Registry) IsValid(name string) bool {
r.mu.RLock()
defer r.mu.RUnlock()
name = strings.ToLower(name)
for _, cmd := range r.commands {
if strings.ToLower(cmd.Name) == name {
return true
}
}
return false
}
// IsCLILocal checks if a command is handled locally by CLI (not sent to backend)
func (r *Registry) IsCLILocal(name string) bool {
name = strings.ToLower(name)
for _, cmd := range cliLocalCommands {
if strings.ToLower(cmd.Name) == name {
return true
}
}
return false
}
// HasCommands returns true if the registry has any commands loaded
func (r *Registry) HasCommands() bool {
r.mu.RLock()
defer r.mu.RUnlock()
return len(r.commands) > 0
}
// ParseModeSwitch checks if message starts with /act or /plan and extracts the mode and remaining message.
// Returns (mode, remainingMessage, isModeSwitch).
// This is a package-level function so it can be used both during initial task creation
// and during interactive input handling.
func ParseModeSwitch(message string) (string, string, bool) {
trimmed := strings.TrimSpace(message)
lower := strings.ToLower(trimmed)
if strings.HasPrefix(lower, "/plan") {
remaining := strings.TrimSpace(trimmed[5:])
return "plan", remaining, true
}
if strings.HasPrefix(lower, "/act") {
remaining := strings.TrimSpace(trimmed[4:])
return "act", remaining, true
}
return "", message, false
}
+7 -7
View File
@@ -19,20 +19,20 @@ import (
// Handles localhost/127.0.0.1 equivalence by returning both forms.
func normalizeAddressVariants(address string) []string {
variants := []string{address}
// Extract host and port
host, port, err := net.SplitHostPort(address)
if err != nil {
return variants
}
// Add the alternate form for localhost/127.0.0.1
if host == "localhost" {
variants = append(variants, net.JoinHostPort("127.0.0.1", port))
} else if host == "127.0.0.1" {
variants = append(variants, net.JoinHostPort("localhost", port))
}
return variants
}
@@ -182,7 +182,7 @@ func (lm *LockManager) GetInstanceInfo(address string) (*common.CoreInstanceInfo
query := common.SelectInstanceLockByHolderSQL
variants := normalizeAddressVariants(address)
var heldBy, lockTarget string
var lockedAt int64
var lastErr error
@@ -193,7 +193,7 @@ func (lm *LockManager) GetInstanceInfo(address string) (*common.CoreInstanceInfo
if err == nil {
// Found it!
return &common.CoreInstanceInfo{
CoreAddress: heldBy,
Address: heldBy,
HostServiceAddress: lockTarget,
Status: grpc_health_v1.HealthCheckResponse_UNKNOWN,
LastSeen: time.Unix(lockedAt/1000, 0),
@@ -204,7 +204,7 @@ func (lm *LockManager) GetInstanceInfo(address string) (*common.CoreInstanceInfo
lastErr = err
}
}
// None of the variants were found
if lastErr != nil {
return nil, fmt.Errorf("failed to query instance: %w", lastErr)
@@ -235,7 +235,7 @@ func (lm *LockManager) ListInstancesWithHealthCheck(ctx context.Context) ([]*com
}
info := &common.CoreInstanceInfo{
CoreAddress: lock.HeldBy,
Address: lock.HeldBy,
HostServiceAddress: lock.LockTarget,
Status: status,
LastSeen: time.Unix(lock.LockedAt/1000, 0),
+19 -18
View File
@@ -20,14 +20,13 @@ import (
// TaskOptions contains options for creating a task
type TaskOptions struct {
Images []string
Files []string
Mode string
Settings []string
Yolo bool
Address string
Verbose bool
Workspaces []string
Images []string
Files []string
Mode string
Settings []string
Yolo bool
Address string
Verbose bool
}
func NewTaskCommand() *cobra.Command {
@@ -80,7 +79,7 @@ func ensureTaskManager(ctx context.Context, address string) error {
}
// Always set the instance we're using as the default
registry := global.Instances.GetRegistry()
registry := global.Clients.GetRegistry()
if err := registry.SetDefaultInstance(instanceAddress); err != nil {
// Log warning but don't fail - this is not critical
fmt.Printf("Warning: failed to set default instance: %v\n", err)
@@ -91,10 +90,10 @@ func ensureTaskManager(ctx context.Context, address string) error {
// ensureInstanceAtAddress ensures an instance exists at the given address
func ensureInstanceAtAddress(ctx context.Context, address string) error {
if global.Instances == nil {
if global.Clients == nil {
return fmt.Errorf("global clients not initialized")
}
return global.Instances.EnsureInstanceAtAddress(ctx, address)
return global.Clients.EnsureInstanceAtAddress(ctx, address)
}
func newTaskNewCommand() *cobra.Command {
@@ -117,7 +116,7 @@ func newTaskNewCommand() *cobra.Command {
ctx := cmd.Context()
// Check if an instance exists when no address specified
if address == "" && global.Instances.GetRegistry().GetDefaultInstance() == "" {
if address == "" && global.Clients.GetRegistry().GetDefaultInstance() == "" {
fmt.Println("No instances available for creating tasks")
return nil
}
@@ -230,7 +229,7 @@ func newTaskSendCommand() *cobra.Command {
ctx := cmd.Context()
// Check if an instance exists when no address specified
if address == "" && global.Instances.GetRegistry().GetDefaultInstance() == "" {
if address == "" && global.Clients.GetRegistry().GetDefaultInstance() == "" {
fmt.Println("No instances available for sending messages")
return nil
}
@@ -395,7 +394,7 @@ func newTaskViewCommand() *cobra.Command {
return taskManager.FollowConversation(ctx, taskManager.GetCurrentInstance(), false)
} else if followComplete {
// Follow until completion
return taskManager.FollowConversationUntilCompletion(ctx, task.DefaultFollowOptions())
return taskManager.FollowConversationUntilCompletion(ctx)
} else {
// Default: show snapshot
return taskManager.ShowConversation(ctx)
@@ -620,6 +619,11 @@ func CleanupTaskManager() {
}
}
// NewTaskManagerForAddress is an exported wrapper around task.NewManagerForAddress
func NewTaskManagerForAddress(ctx context.Context, address string) (*task.Manager, error) {
return task.NewManagerForAddress(ctx, address)
}
// CreateAndFollowTask creates a new task and immediately follows it in interactive mode
// This is used by the root command to provide a streamlined UX
func CreateAndFollowTask(ctx context.Context, prompt string, opts TaskOptions) error {
@@ -664,10 +668,7 @@ func CreateAndFollowTask(ctx context.Context, prompt string, opts TaskOptions) e
// If yolo mode is enabled, follow until completion (non-interactive)
// Otherwise, follow in interactive mode
if opts.Yolo {
// Skip active task check since we just created the task
return taskManager.FollowConversationUntilCompletion(ctx, task.FollowOptions{
SkipActiveTaskCheck: true,
})
return taskManager.FollowConversationUntilCompletion(ctx)
} else {
return taskManager.FollowConversation(ctx, taskManager.GetCurrentInstance(), true)
}
-15
View File
@@ -1,15 +0,0 @@
package task
// FollowOptions contains options for following a conversation
type FollowOptions struct {
// SkipActiveTaskCheck skips the check for an active task
// This is useful when following a task that was just created to avoid race conditions
SkipActiveTaskCheck bool
}
// DefaultFollowOptions returns the default options for following a conversation
func DefaultFollowOptions() FollowOptions {
return FollowOptions{
SkipActiveTaskCheck: false,
}
}
+48 -37
View File
@@ -13,41 +13,38 @@ import (
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/slash"
"github.com/cline/cli/pkg/cli/types"
)
// InputHandler manages interactive user input during follow mode
type InputHandler struct {
manager *Manager
coordinator *StreamCoordinator
cancelFunc context.CancelFunc
mu sync.RWMutex
isRunning bool
pollTicker *time.Ticker
program *tea.Program
programRunning bool
programDoneChan chan struct{} // Signals when program actually exits
resultChan chan output.InputSubmitMsg
cancelChan chan struct{}
feedbackApproval bool // Track if we're in feedback after approval
feedbackApproved bool // Track the approval decision
approvalMessage *types.ClineMessage // Store the approval message for determining action
slashCommandRegistry *slash.Registry // Slash command registry for autocomplete
ctx context.Context // Context for restart callback
manager *Manager
coordinator *StreamCoordinator
cancelFunc context.CancelFunc
mu sync.RWMutex
isRunning bool
pollTicker *time.Ticker
program *tea.Program
programRunning bool
programDoneChan chan struct{} // Signals when program actually exits
resultChan chan output.InputSubmitMsg
cancelChan chan struct{}
feedbackApproval bool // Track if we're in feedback after approval
feedbackApproved bool // Track the approval decision
approvalMessage *types.ClineMessage // Store the approval message for determining action
ctx context.Context // Context for restart callback
}
// NewInputHandler creates a new input handler
func NewInputHandler(manager *Manager, coordinator *StreamCoordinator, cancelFunc context.CancelFunc) *InputHandler {
return &InputHandler{
manager: manager,
coordinator: coordinator,
cancelFunc: cancelFunc,
isRunning: false,
pollTicker: time.NewTicker(500 * time.Millisecond),
resultChan: make(chan output.InputSubmitMsg, 1),
slashCommandRegistry: slash.NewRegistry(context.Background()),
cancelChan: make(chan struct{}, 1),
manager: manager,
coordinator: coordinator,
cancelFunc: cancelFunc,
isRunning: false,
pollTicker: time.NewTicker(500 * time.Millisecond),
resultChan: make(chan output.InputSubmitMsg, 1),
cancelChan: make(chan struct{}, 1),
}
}
@@ -166,7 +163,7 @@ func (ih *InputHandler) Start(ctx context.Context, errChan chan error) {
if shouldSend {
// Check for mode switch commands first
newMode, remainingMessage, isModeSwitch := slash.ParseModeSwitch(message)
newMode, remainingMessage, isModeSwitch := ih.parseModeSwitch(message)
if isModeSwitch {
// Create styles for mode switch messages (respect global color profile)
actStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("39")).Bold(true)
@@ -254,8 +251,7 @@ func determineAutoApprovalAction(msg *types.ClineMessage) (string, error) {
types.ToolTypeListFilesRecursive,
types.ToolTypeListCodeDefinitionNames,
types.ToolTypeSearchFiles,
types.ToolTypeWebFetch,
types.ToolTypeWebSearch:
types.ToolTypeWebFetch:
return "read_files", nil
case types.ToolTypeEditedExistingFile,
types.ToolTypeNewFileCreated:
@@ -284,12 +280,11 @@ func determineAutoApprovalAction(msg *types.ClineMessage) (string, error) {
func (ih *InputHandler) promptForInput(ctx context.Context) (string, bool, error) {
currentMode := ih.manager.GetCurrentMode()
model := output.NewInputModelWithRegistry(
model := output.NewInputModel(
output.InputTypeMessage,
"Cline is ready for your message...",
"/plan or /act to switch modes\ntab to autocomplete commands\nctrl+e to open editor\nctrl+c to exit",
"/plan or /act to switch modes\nctrl+e to open editor",
currentMode,
ih.slashCommandRegistry,
)
return ih.runInputProgram(ctx, model)
@@ -299,13 +294,12 @@ func (ih *InputHandler) promptForInput(ctx context.Context) (string, bool, error
func (ih *InputHandler) promptForApproval(ctx context.Context, msg *types.ClineMessage) (bool, string, error) {
// Store the approval message for later use in determining auto-approval action
ih.approvalMessage = msg
model := output.NewInputModelWithRegistry(
model := output.NewInputModel(
output.InputTypeApproval,
"Let Cline use this tool?",
"",
ih.manager.GetCurrentMode(),
ih.slashCommandRegistry,
)
message, shouldSend, err := ih.runInputProgram(ctx, model)
@@ -400,7 +394,7 @@ func (ih *InputHandler) runInputProgram(ctx context.Context, model output.InputM
// Need to collect feedback - will be handled by model state change
return "", false, nil
}
// Check if NoAskAgain was selected
if result.NoAskAgain && result.Approved && ih.approvalMessage != nil {
// Determine which auto-approval action to enable
@@ -416,7 +410,7 @@ func (ih *InputHandler) runInputProgram(ctx context.Context, model output.InputM
}
}
}
// Store approval state for when feedback comes back
ih.feedbackApproval = false
ih.feedbackApproved = result.Approved
@@ -446,7 +440,6 @@ func (w *inputProgramWrapper) Init() tea.Cmd {
}
func (w *inputProgramWrapper) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case output.InputSubmitMsg:
// Handle input submission - clear the screen before quitting
@@ -481,6 +474,24 @@ func (w *inputProgramWrapper) View() string {
return w.model.View()
}
// parseModeSwitch checks if message starts with /act or /plan and extracts the mode and remaining message
func (ih *InputHandler) parseModeSwitch(message string) (string, string, bool) {
trimmed := strings.TrimSpace(message)
lower := strings.ToLower(trimmed)
if strings.HasPrefix(lower, "/plan") {
remaining := strings.TrimSpace(trimmed[5:])
return "plan", remaining, true
}
if strings.HasPrefix(lower, "/act") {
remaining := strings.TrimSpace(trimmed[4:])
return "act", remaining, true
}
return "", message, false
}
// handleSpecialCommand processes special commands like /cancel, /exit
func (ih *InputHandler) handleSpecialCommand(ctx context.Context, message string) bool {
switch strings.ToLower(strings.TrimSpace(message)) {
+7 -91
View File
@@ -32,7 +32,6 @@ type Manager struct {
clientAddress string
state *types.ConversationState
renderer *display.Renderer
hookRenderer *display.HookRenderer
toolRenderer *display.ToolRenderer
systemRenderer *display.SystemMessageRenderer
streamingDisplay *display.StreamingDisplay
@@ -47,7 +46,6 @@ func NewManager(client *client.ClineClient) *Manager {
state := types.NewConversationState()
renderer := display.NewRenderer(global.Config.OutputFormat)
toolRenderer := display.NewToolRenderer(renderer.GetMdRenderer(), global.Config.OutputFormat)
hookRenderer := display.NewHookRenderer(renderer.GetMdRenderer(), global.Config.OutputFormat)
systemRenderer := display.NewSystemMessageRenderer(renderer, renderer.GetMdRenderer(), global.Config.OutputFormat)
streamingDisplay := display.NewStreamingDisplay(state, renderer)
@@ -61,7 +59,6 @@ func NewManager(client *client.ClineClient) *Manager {
clientAddress: "", // Will be set when client is provided
state: state,
renderer: renderer,
hookRenderer: hookRenderer,
toolRenderer: toolRenderer,
systemRenderer: systemRenderer,
streamingDisplay: streamingDisplay,
@@ -79,7 +76,6 @@ func NewManagerForAddress(ctx context.Context, address string) (*Manager, error)
manager := NewManager(client)
manager.clientAddress = address
return manager, nil
}
@@ -93,8 +89,8 @@ func NewManagerForDefault(ctx context.Context) (*Manager, error) {
manager := NewManager(client)
// Get the default instance address
if global.Instances != nil {
manager.clientAddress = global.Instances.GetRegistry().GetDefaultInstance()
if global.Clients != nil {
manager.clientAddress = global.Clients.GetRegistry().GetDefaultInstance()
}
return manager, nil
@@ -284,8 +280,8 @@ func (m *Manager) CheckSendEnabled(ctx context.Context) error {
// Error types which we allow sending on
errorTypes := []string{
string(types.AskTypeAPIReqFailed), // "api_req_failed"
string(types.AskTypeMistakeLimitReached), // "mistake_limit_reached"
string(types.AskTypeAPIReqFailed), // "api_req_failed"
string(types.AskTypeMistakeLimitReached), // "mistake_limit_reached"
}
isError := false
@@ -757,21 +753,7 @@ func (m *Manager) FollowConversation(ctx context.Context, instanceAddress string
}
// FollowConversationUntilCompletion streams conversation updates until task completion
func (m *Manager) FollowConversationUntilCompletion(ctx context.Context, opts FollowOptions) error {
// Check if there's an active task before entering follow mode
// Skip this check if we just created a task (to avoid race condition where task isn't active yet)
if !opts.SkipActiveTaskCheck {
err := m.CheckSendEnabled(ctx)
if err != nil {
if errors.Is(err, ErrNoActiveTask) {
fmt.Println("No task is currently running.")
return nil
}
// For other errors (like task busy), we can still enter follow mode
// as the user may want to observe the task
}
}
func (m *Manager) FollowConversationUntilCompletion(ctx context.Context) error {
// Enable streaming mode
m.mu.Lock()
m.isStreamingMode = true
@@ -970,15 +952,6 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeCommandPermissionDenied):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeBrowserActionLaunch):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -997,33 +970,6 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeMcpServerResponse):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeMcpNotification):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeUseMcpServer):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeCheckpointCreated):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -1033,26 +979,6 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeHookStatus):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeHookOutputStream):
// Hook stdout/stderr streaming arrives as hook_output_stream messages.
// These are intentionally suppressed unless verbose (see SayHandler.handleHookOutputStream),
// but we still need to route them through the normal handler pipeline in streaming/follow
// mode so verbose users actually see `HOOK> ...` lines.
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeAPIReqStarted):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
apiInfo := types.APIRequestInfo{Cost: -1}
@@ -1067,14 +993,6 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
}
}
case msg.Say == string(types.SayTypeCompletionResult):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !msg.Partial && !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Ask == string(types.AskTypeCommandOutput):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -1187,11 +1105,9 @@ func (m *Manager) displayMessage(msg *types.ClineMessage, isLast, isPartial bool
State: m.state,
Renderer: m.renderer,
ToolRenderer: m.toolRenderer,
HookRenderer: m.hookRenderer,
SystemRenderer: m.systemRenderer,
IsLast: isLast,
IsPartial: isPartial,
Verbose: global.Config.Verbose,
MessageIndex: messageIndex,
IsStreamingMode: isStreaming,
IsInteractive: isInteractive,
@@ -1323,7 +1239,7 @@ func (m *Manager) updateMode(stateJson string) {
// UpdateTaskAutoApprovalAction enables a specific auto-approval action for the current task
func (m *Manager) UpdateTaskAutoApprovalAction(ctx context.Context, actionKey string) error {
boolPtr := func(b bool) *bool { return &b }
settings := &cline.Settings{
AutoApprovalSettings: &cline.AutoApprovalSettings{
Actions: &cline.AutoApprovalActions{},
@@ -1332,7 +1248,7 @@ func (m *Manager) UpdateTaskAutoApprovalAction(ctx context.Context, actionKey st
// Set the specific action to true based on actionKey
truePtr := boolPtr(true)
switch actionKey {
case "read_files":
settings.AutoApprovalSettings.Actions.ReadFiles = truePtr
-6
View File
@@ -290,12 +290,6 @@ func setSimpleField(settings *cline.Settings, key, value string) error {
return err
}
settings.ActModeAwsBedrockCustomSelected = boolPtr(val)
case "azure_identity":
val, err := parseBool(value)
if err != nil {
return err
}
settings.AzureIdentity = boolPtr(val)
// Integer fields
case "request_timeout_ms":
+11 -12
View File
@@ -3,16 +3,15 @@ package types
// HistoryItem represents a task history item from taskHistory.json
// This struct matches the JSON format stored on disk
type HistoryItem struct {
Id string `json:"id"`
Ulid string `json:"ulid,omitempty"`
Ts int64 `json:"ts"`
Task string `json:"task"`
TokensIn int32 `json:"tokensIn"`
TokensOut int32 `json:"tokensOut"`
CacheWrites int32 `json:"cacheWrites,omitempty"`
CacheReads int32 `json:"cacheReads,omitempty"`
TotalCost float64 `json:"totalCost"`
Size int64 `json:"size,omitempty"`
IsFavorited bool `json:"isFavorited,omitempty"`
WorkspacePaths []string `json:"workspacePaths,omitempty"`
Id string `json:"id"`
Ulid string `json:"ulid,omitempty"`
Ts int64 `json:"ts"`
Task string `json:"task"`
TokensIn int32 `json:"tokensIn"`
TokensOut int32 `json:"tokensOut"`
CacheWrites int32 `json:"cacheWrites,omitempty"`
CacheReads int32 `json:"cacheReads,omitempty"`
TotalCost float64 `json:"totalCost"`
Size int64 `json:"size,omitempty"`
IsFavorited bool `json:"isFavorited,omitempty"`
}
+5 -53
View File
@@ -47,11 +47,11 @@ const (
AskTypeResumeTask AskType = "resume_task"
AskTypeResumeCompletedTask AskType = "resume_completed_task"
AskTypeMistakeLimitReached AskType = "mistake_limit_reached"
AskTypeBrowserActionLaunch AskType = "browser_action_launch"
AskTypeUseMcpServer AskType = "use_mcp_server"
AskTypeNewTask AskType = "new_task"
AskTypeCondense AskType = "condense"
AskTypeReportBug AskType = "report_bug"
AskTypeBrowserActionLaunch AskType = "browser_action_launch"
AskTypeUseMcpServer AskType = "use_mcp_server"
AskTypeNewTask AskType = "new_task"
AskTypeCondense AskType = "condense"
AskTypeReportBug AskType = "report_bug"
)
// SayType represents different types of SAY messages
@@ -87,11 +87,6 @@ const (
SayTypeLoadMcpDocumentation SayType = "load_mcp_documentation"
SayTypeInfo SayType = "info"
SayTypeTaskProgress SayType = "task_progress"
// Hook status streaming from the backend.
// These values must match the backend "say" strings emitted by the extension.
SayTypeHookStatus SayType = "hook_status"
SayTypeHookOutputStream SayType = "hook_output_stream"
SayTypeCommandPermissionDenied SayType = "command_permission_denied"
)
// ToolMessage represents a tool-related message
@@ -118,7 +113,6 @@ const (
ToolTypeListCodeDefinitionNames ToolType = "listCodeDefinitionNames"
ToolTypeSearchFiles ToolType = "searchFiles"
ToolTypeWebFetch ToolType = "webFetch"
ToolTypeWebSearch ToolType = "webSearch"
ToolTypeSummarizeTask ToolType = "summarizeTask"
)
@@ -150,42 +144,6 @@ type APIRequestRetryStatus struct {
ErrorSnippet string `json:"errorSnippet,omitempty"`
}
// HookMessage represents hook execution metadata sent from the backend
type HookMessage struct {
HookName string `json:"hookName"` // Type of hook (TaskStart, PreToolUse, etc.)
ToolName string `json:"toolName,omitempty"` // Optional tool name for tool-specific hooks
Status string `json:"status"` // "running", "completed", "cancelled", or "failed"
ScriptPaths []string `json:"scriptPaths,omitempty"` // Full paths to hook script(s)
PendingToolInfo *ToolInfo `json:"pendingToolInfo,omitempty"` // Metadata about the pending tool execution (PreToolUse)
ExitCode int `json:"exitCode,omitempty"` // Exit code for completed/failed hooks
HasJsonResponse bool `json:"hasJsonResponse,omitempty"` // Whether hook returned JSON
Error *HookError `json:"error,omitempty"` // Error details if hook failed
}
// ToolInfo represents a compact subset of tool parameters for UI display.
// This mirrors the extension's pendingToolInfo shape and is used by the CLI to
// show what tool the PreToolUse hook is gating.
type ToolInfo struct {
Tool string `json:"tool"`
Path string `json:"path,omitempty"`
Command string `json:"command,omitempty"`
Content string `json:"content,omitempty"`
Diff string `json:"diff,omitempty"`
Regex string `json:"regex,omitempty"`
Url string `json:"url,omitempty"`
McpTool string `json:"mcpTool,omitempty"`
McpServer string `json:"mcpServer,omitempty"`
ResourceUri string `json:"resourceUri,omitempty"`
}
// HookError represents structured error information from a failed hook
type HookError struct {
Type string `json:"type"` // Error type: "execution", "timeout", "validation", etc.
Message string `json:"message"` // Human-readable error message
Details string `json:"details,omitempty"` // Additional error details
ScriptPath string `json:"scriptPath,omitempty"` // Path to script that failed
}
// GetTimestamp returns a formatted timestamp string
func (m *ClineMessage) GetTimestamp() string {
return time.Unix(m.Timestamp/1000, 0).Format("15:04:05")
@@ -365,12 +323,6 @@ func convertProtoSayType(sayType cline.ClineSay) string {
return string(SayTypeInfo)
case cline.ClineSay_TASK_PROGRESS:
return string(SayTypeTaskProgress)
case cline.ClineSay_HOOK_STATUS:
return string(SayTypeHookStatus)
case cline.ClineSay_HOOK_OUTPUT_STREAM:
return string(SayTypeHookOutputStream)
case cline.ClineSay_COMMAND_PERMISSION_DENIED:
return string(SayTypeCommandPermissionDenied)
default:
return "unknown"
}
+11 -14
View File
@@ -8,19 +8,6 @@ import (
"github.com/spf13/cobra"
)
// VersionString returns the full version information string
func VersionString() string {
return fmt.Sprintf(`Cline CLI
Cline CLI Version: %s
Cline Core Version: %s
Commit: %s
Built: %s
Built by: %s
Go version: %s
OS/Arch: %s/%s
`, global.CliVersion, global.Version, global.Commit, global.Date, global.BuiltBy, runtime.Version(), runtime.GOOS, runtime.GOARCH)
}
// NewVersionCommand creates the version command
func NewVersionCommand() *cobra.Command {
var short bool
@@ -31,11 +18,21 @@ func NewVersionCommand() *cobra.Command {
Short: "Show version information",
Long: `Display version information for the Cline CLI.`,
RunE: func(cmd *cobra.Command, args []string) error {
// Versions are injected at build time via ldflags
if short {
fmt.Println(global.CliVersion)
return nil
}
fmt.Print(VersionString())
fmt.Printf("Cline CLI\n")
fmt.Printf("Cline CLI Version: %s\n", global.CliVersion)
fmt.Printf("Cline Core Version: %s\n", global.Version)
fmt.Printf("Commit: %s\n", global.Commit)
fmt.Printf("Built: %s\n", global.Date)
fmt.Printf("Built by: %s\n", global.BuiltBy)
fmt.Printf("Go version: %s\n", runtime.Version())
fmt.Printf("OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
return nil
},
}
+2 -2
View File
@@ -10,7 +10,7 @@ import (
// This is the canonical definition used across all CLI packages
type CoreInstanceInfo struct {
// Full core address including port
CoreAddress string `json:"address"`
Address string `json:"address"`
// Host bridge service address that core holds (host is ALWAYS running on localhost FYI)
HostServiceAddress string `json:"host_port"`
Status grpc_health_v1.HealthCheckResponse_ServingStatus `json:"status"`
@@ -20,7 +20,7 @@ type CoreInstanceInfo struct {
}
func (c *CoreInstanceInfo) CorePort() int {
_, port, _ := ParseHostPort(c.CoreAddress)
_, port, _ := ParseHostPort(c.Address)
return port
}
-71
View File
@@ -4,9 +4,7 @@ import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
@@ -185,72 +183,3 @@ DEBUGGING STEPS:
For additional help, visit: https://github.com/cline/cline/issues
`, maxRetries, lastErr, GetNodeVersion())
}
// validateDirsExist validates that all workspace paths exist on the filesystem
func ValidateDirsExist(paths []string) error {
for _, p := range paths {
info, err := os.Stat(p)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("path does not exist: %s", p)
}
return fmt.Errorf("failed to access path %s: %w", p, err)
}
if !info.IsDir() {
return fmt.Errorf("path is not a directory: %s", p)
}
}
return nil
}
// absPath returns the absolute path, resolving symlinks
func AbsPath(path string) (string, error) {
// First get absolute path
abs, err := filepath.Abs(path)
if err != nil {
return "", err
}
// Then resolve any symlinks
resolved, err := filepath.EvalSymlinks(abs)
if err != nil {
// If symlink resolution fails, return the absolute path
return abs, nil
}
return resolved, nil
}
// shortenPath shortens a filesystem path to fit within maxLen
func ShortenPath(path string, maxLen int) string {
// Try to replace home directory with ~ (cross-platform)
if homeDir, err := os.UserHomeDir(); err == nil {
if strings.HasPrefix(path, homeDir) {
shortened := "~" + path[len(homeDir):]
// Always use ~ version if we can
path = shortened
}
}
if len(path) <= maxLen {
return path
}
// If still too long, show last few path components
if len(path) > maxLen {
parts := strings.Split(path, string(filepath.Separator))
if len(parts) > 2 {
// Show last 2-3 components
lastParts := parts[len(parts)-2:]
shortened := "..." + string(filepath.Separator) + strings.Join(lastParts, string(filepath.Separator))
if len(shortened) <= maxLen {
return shortened
}
}
}
// Last resort: truncate with ellipsis
if len(path) > maxLen {
return "..." + path[len(path)-maxLen+3:]
}
return path
}
+5 -17
View File
@@ -47,10 +47,7 @@ func (s *DiffService) generateDiffID() string {
return fmt.Sprintf("diff_%d_%d", os.Getpid(), id)
}
// splitLines splits content into lines, preserving trailing newlines.
// This matches the behavior of JavaScript's String.split("\n"):
// - "hello\nworld\n" -> ["hello", "world", ""]
// - "hello\nworld" -> ["hello", "world"]
// splitLines splits content into lines, preserving line ending information
func splitLines(content string) []string {
if content == "" {
return []string{}
@@ -68,9 +65,10 @@ func splitLines(content string) []string {
}
}
// Always add the last segment - if content ends with newline, this will be
// an empty string which preserves the trailing newline when joined back
lines = append(lines, current)
// Add the last line if it doesn't end with newline
if current != "" {
lines = append(lines, current)
}
return lines
}
@@ -178,19 +176,9 @@ func (s *DiffService) ReplaceText(ctx context.Context, req *proto.ReplaceTextReq
endLine = startLine
}
// Check if we're replacing to the end of the document
replacingToEnd := endLine >= len(session.lines)
// Split new content into lines
newLines := splitLines(newContent)
// Remove trailing empty line for proper splicing, BUT only when NOT replacing
// to the end of the document. When replacing to the end, keep the trailing
// empty string to preserve trailing newlines from the content.
if !replacingToEnd && len(newLines) > 0 && newLines[len(newLines)-1] == "" {
newLines = newLines[:len(newLines)-1]
}
// Ensure we have enough lines in the current content
for len(session.lines) < endLine {
session.lines = append(session.lines, "")
+39
View File
@@ -0,0 +1,39 @@
package hostbridge
import (
"log"
"github.com/cline/grpc-go/host"
)
// WatchService implements the host.WatchServiceServer interface
type WatchService struct {
host.UnimplementedWatchServiceServer
coreAddress string
verbose bool
}
// NewWatchService creates a new WatchService
func NewWatchService(coreAddress string, verbose bool) *WatchService {
return &WatchService{
coreAddress: coreAddress,
verbose: verbose,
}
}
// SubscribeToFile subscribes to file change notifications
func (s *WatchService) SubscribeToFile(req *host.SubscribeToFileRequest, stream host.WatchService_SubscribeToFileServer) error {
if s.verbose {
log.Printf("SubscribeToFile called for path: %s", req.GetPath())
}
// For console implementation, we'll just log that we would watch the file
// In a real implementation, we'd use fsnotify or similar to watch file changes
log.Printf("[Cline] Would watch file: %s", req.GetPath())
// Keep the stream open but don't send any events for now
// In a real implementation, we'd send FileChangeEvent messages when files change
<-stream.Context().Done()
return nil
}
+4 -6
View File
@@ -5,7 +5,6 @@ import (
"log"
"os"
"github.com/cline/grpc-go/cline"
"github.com/cline/grpc-go/host"
)
@@ -44,25 +43,24 @@ func (s *WorkspaceService) GetWorkspacePaths(ctx context.Context, req *host.GetW
// SaveOpenDocumentIfDirty saves an open document if it has unsaved changes
func (s *WorkspaceService) SaveOpenDocumentIfDirty(ctx context.Context, req *host.SaveOpenDocumentIfDirtyRequest) (*host.SaveOpenDocumentIfDirtyResponse, error) {
if s.verbose {
log.Printf("SaveOpenDocumentIfDirty called for path: %v", req.FilePath)
log.Printf("SaveOpenDocumentIfDirty called for path: %s", req.GetPath())
}
// For console implementation, we'll assume the document is already saved
// In a real implementation, we'd check if the file has unsaved changes
f := false
return &host.SaveOpenDocumentIfDirtyResponse{
WasSaved: &f, // Assume no changes to save
WasSaved: false, // Assume no changes to save
}, nil
}
// GetDiagnostics returns diagnostic information for a file
func (s *WorkspaceService) GetDiagnostics(ctx context.Context, req *host.GetDiagnosticsRequest) (*host.GetDiagnosticsResponse, error) {
if s.verbose {
log.Printf("GetDiagnostics called")
log.Printf("GetDiagnostics called for path: %s", req.GetPath())
}
// For console implementation, return empty diagnostics
return &host.GetDiagnosticsResponse{
FileDiagnostics: []*cline.FileDiagnostics{},
Diagnostics: []*host.Diagnostic{},
}, nil
}
+1 -1
View File
@@ -77,7 +77,7 @@ func (s *EnvService) GetHostVersion(ctx context.Context, req *cline.EmptyRequest
return &host.GetHostVersionResponse{
Platform: proto.String("Cline CLI"),
Version: proto.String(global.CliVersion),
Version: proto.String(""),
ClineType: proto.String("CLI"),
ClineVersion: proto.String(global.CliVersion),
}, nil
+2 -4
View File
@@ -16,17 +16,15 @@ import (
type GrpcServer struct {
port int
verbose bool
workspaces []string
server *grpc.Server
shutdownCh chan struct{}
}
// NewGrpcServer creates a new GrpcServer
func NewGrpcServer(port int, verbose bool, workspaces []string) *GrpcServer {
func NewGrpcServer(port int, verbose bool) *GrpcServer {
return &GrpcServer{
port: port,
verbose: verbose,
workspaces: workspaces,
shutdownCh: make(chan struct{}),
}
}
@@ -52,7 +50,7 @@ func (s *GrpcServer) Start(ctx context.Context) error {
grpc_health_v1.RegisterHealthServer(s.server, healthServer)
// Register services
workspaceService := NewSimpleWorkspaceService(s.verbose, s.workspaces)
workspaceService := NewSimpleWorkspaceService(s.verbose)
host.RegisterWorkspaceServiceServer(s.server, workspaceService)
windowService := NewWindowService(s.verbose)
+8 -20
View File
@@ -12,15 +12,13 @@ import (
// SimpleWorkspaceService implements a basic workspace service without complex dependencies
type SimpleWorkspaceService struct {
host.UnimplementedWorkspaceServiceServer
verbose bool
workspaces []string
verbose bool
}
// NewSimpleWorkspaceService creates a new SimpleWorkspaceService
func NewSimpleWorkspaceService(verbose bool, workspaces []string) *SimpleWorkspaceService {
func NewSimpleWorkspaceService(verbose bool) *SimpleWorkspaceService {
return &SimpleWorkspaceService{
verbose: verbose,
workspaces: workspaces,
verbose: verbose,
}
}
@@ -30,24 +28,14 @@ func (s *SimpleWorkspaceService) GetWorkspacePaths(ctx context.Context, req *hos
log.Printf("GetWorkspacePaths called")
}
paths := []string{}
if len(s.workspaces) == 0 {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
paths = append(paths, cwd)
} else {
paths = s.workspaces
}
if s.verbose {
log.Printf("Returning configured workspaces: %v", paths)
// Get current working directory as the workspace
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
return &host.GetWorkspacePathsResponse{
Paths: paths,
Paths: []string{cwd},
}, nil
}
+48
View File
@@ -0,0 +1,48 @@
# Git
.git
.gitignore
.gitattributes
# Node modules
node_modules
npm-debug.log
# Build artifacts
dist
dist-standalone
build
*.log
# Generated code
src/generated
# CLI build artifacts
cli/bin
cli/dist
# Webview build artifacts
webview-ui/dist
webview-ui/build
# IDE
.vscode
.idea
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Documentation
*.md
!README.md
# Tests
tests
*.test.js
*.spec.js
# CI/CD
.github
.gitlab-ci.yml
+49
View File
@@ -0,0 +1,49 @@
FROM node:22-slim
# TARGETARCH enables multi-architecture support without emulation warnings:
# - Docker automatically sets TARGETARCH to the build platform's architecture
# - On arm64 machines (Apple Silicon): TARGETARCH=arm64, uses linux-arm64 binaries
# - On amd64 machines (Intel/AMD): TARGETARCH=amd64, uses linux-x64 binaries
# The corresponding platform-specific binaries and native modules (better-sqlite3)
# are pre-built by scripts/package-standalone.mjs during the build process.
ARG TARGETARCH
# Install only runtime dependencies
RUN apt-get update && apt-get install -y \
git curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /opt/cline
# Copy the entire pre-built distribution
COPY dist-standalone/ ./
# Create symlink for Linux native modules
# Map Docker's TARGETARCH (arm64/amd64) to Node's platform naming (x64 for amd64)
RUN if [ "$TARGETARCH" = "amd64" ]; then \
ln -sf /opt/cline/binaries/linux-x64/node_modules/better-sqlite3 /opt/cline/node_modules/better-sqlite3; \
else \
ln -sf /opt/cline/binaries/linux-$TARGETARCH/node_modules/better-sqlite3 /opt/cline/node_modules/better-sqlite3; \
fi
# Set up CLI binaries
# The Linux binaries are already in /opt/cline/bin/ from dist-standalone
# Just need to create symlinks to the platform-specific ones
RUN cd /opt/cline/bin && \
ln -sf cline-linux-$TARGETARCH cline && \
ln -sf cline-host-linux-$TARGETARCH cline-host && \
chmod +x cline-linux-$TARGETARCH cline-host-linux-$TARGETARCH cline cline-host
# Add binaries to PATH
ENV PATH="/opt/cline/bin:${PATH}"
ENV NODE_ENV=production
ENV CLINE_HOME=/root/.cline
RUN mkdir -p $CLINE_HOME
WORKDIR /workspace
EXPOSE 8000
ENTRYPOINT ["/opt/cline/bin/cline"]
CMD ["--help"]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Some files were not shown because too many files have changed in this diff Show More