merge main

This commit is contained in:
Dallin Romney 2025-09-15 23:07:52 -07:00
commit 92f8d93b25
72 changed files with 22173 additions and 2815 deletions

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@5dc7a050db441934c26eb910b8433291f627db7f
uses: continuedev/continue/actions/detailed-review@8373ac24010df1110cd00512f925b63813362da1
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@5dc7a050db441934c26eb910b8433291f627db7f
uses: continuedev/continue/actions/general-review@8373ac24010df1110cd00512f925b63813362da1
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -32,6 +32,10 @@ on:
required: false
VOYAGE_API_KEY:
required: false
RELACE_API_KEY:
required: false
INCEPTION_API_KEY:
required: false
permissions:
contents: write
@ -77,6 +81,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
- name: Release
env:

View file

@ -85,26 +85,24 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"watsonx",
];
const MODEL_SUPPORTS_IMAGES: string[] = [
"llava",
"gpt-4-turbo",
"gpt-4o",
"gpt-4o-mini",
"gpt-4-vision",
"claude-3",
"c4ai-aya-vision-8b",
"c4ai-aya-vision-32b",
"gemini-ultra",
"gemini-1.5-pro",
"gemini-1.5-flash",
"sonnet",
"opus",
"haiku",
"pixtral",
"llama3.2",
"llama-3.2",
"llama4",
"granite-vision",
const MODEL_SUPPORTS_IMAGES: RegExp[] = [
/llava/,
/gpt-4-turbo/,
/gpt-4o/,
/gpt-4o-mini/,
/claude-3/,
/gemini-ultra/,
/gemini-1\.5-pro/,
/gemini-1\.5-flash/,
/sonnet/,
/opus/,
/haiku/,
/pixtral/,
/llama-?3\.2/,
/llama-?4/, // might use something like /llama-?(?:[4-9](?:\.\d+)?|\d{2,}(?:\.\d+)?)/ for forward compat, if needed
/\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't!
/\b(pali|med)gemma/,
/qwen(.*)vl/,
];
function modelSupportsImages(
@ -120,10 +118,14 @@ function modelSupportsImages(
return false;
}
const lower = model.toLowerCase();
const lowerModel = model.toLowerCase();
const lowerTitle = title?.toLowerCase() ?? "";
if (
lowerModel.includes("vision") ||
lowerTitle.includes("vision") ||
MODEL_SUPPORTS_IMAGES.some(
(modelName) => lower.includes(modelName) || title?.includes(modelName),
(modelrx) => modelrx.test(lowerModel) || modelrx.test(lowerTitle),
)
) {
return true;

View file

@ -95,10 +95,31 @@ describe("BaseLLM", () => {
test("should return true when modelSupportsImages returns true", () => {
baseLLM.model = "gpt-4-vision";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "fancy-vision-model";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "gemma3:4b";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "google/gemma-3-270m";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "foo/paligemma-custom-100";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "foo/medgemma_4b_it_16Q";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "qwen2.5vl";
expect(baseLLM.supportsImages()).toBe(true);
});
test("should return false when modelSupportsImages returns false", () => {
expect(baseLLM.supportsImages()).toBe(false);
baseLLM.model = "gemma3n";
expect(baseLLM.supportsImages()).toBe(false);
});
});

View file

@ -4,9 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const createNewFileTool: Tool = {
type: "function",
displayTitle: "Create New File",
wouldLikeTo: "create a new file at {{{ filepath }}}",
isCurrently: "creating a new file at {{{ filepath }}}",
hasAlready: "created a new file at {{{ filepath }}}",
wouldLikeTo: "create {{{ filepath }}}",
isCurrently: "creating {{{ filepath }}}",
hasAlready: "created {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: true,

View file

@ -6,7 +6,7 @@ export const fetchUrlContentTool: Tool = {
displayTitle: "Read URL",
wouldLikeTo: "fetch {{{ url }}}",
isCurrently: "fetching {{{ url }}}",
hasAlready: "viewed {{{ url }}}",
hasAlready: "fetched {{{ url }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -4,9 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const globSearchTool: Tool = {
type: "function",
displayTitle: "Glob File Search",
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
isCurrently: 'finding file matches for "{{{ pattern }}}"',
hasAlready: 'retrieved file matches for "{{{ pattern }}}"',
wouldLikeTo: 'search for files like "{{{ pattern }}}"',
isCurrently: 'searching for files like "{{{ pattern }}}"',
hasAlready: 'searched for files like "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -4,9 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const grepSearchTool: Tool = {
type: "function",
displayTitle: "Grep Search",
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
isCurrently: 'getting search results for "{{{ query }}}"',
hasAlready: 'retrieved search results for "{{{ query }}}"',
wouldLikeTo: 'search for "{{{ query }}}"',
isCurrently: 'searching for "{{{ query }}}"',
hasAlready: 'searched for "{{{ query }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -5,9 +5,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "ls",
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
isCurrently: "listing files and folders in {{{ dirPath }}}",
hasAlready: "listed files and folders in {{{ dirPath }}}",
wouldLikeTo: "list files in {{{ dirPath }}}",
isCurrently: "listing files in {{{ dirPath }}}",
hasAlready: "listed files in {{{ dirPath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = {
displayTitle: "Read Currently Open File",
wouldLikeTo: "read the current file",
isCurrently: "reading the current file",
hasAlready: "viewed the current file",
hasAlready: "read the current file",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -6,7 +6,7 @@ export const readFileTool: Tool = {
displayTitle: "Read File",
wouldLikeTo: "read {{{ filepath }}}",
isCurrently: "reading {{{ filepath }}}",
hasAlready: "viewed {{{ filepath }}}",
hasAlready: "read {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -9,7 +9,7 @@ export const readFileRangeTool: Tool = {
isCurrently:
"reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
hasAlready:
"viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
"read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -12,9 +12,9 @@ export interface SingleFindAndReplaceArgs {
export const singleFindAndReplaceTool: Tool = {
type: "function",
displayTitle: "Find and Replace",
wouldLikeTo: "find and replace in {{{ filepath }}}",
isCurrently: "finding and replacing in {{{ filepath }}}",
hasAlready: "found and replaced in {{{ filepath }}}",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,

View file

@ -4,7 +4,6 @@ import * as toolDefinitions from "./definitions";
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
export const getBaseToolDefinitions = () => [
toolDefinitions.readFileTool,
toolDefinitions.createNewFileTool,
toolDefinitions.runTerminalCommandTool,
toolDefinitions.globSearchTool,
@ -13,7 +12,6 @@ export const getBaseToolDefinitions = () => [
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
toolDefinitions.singleFindAndReplaceTool,
];
export const getConfigDependentToolDefinitions = (
@ -42,6 +40,7 @@ export const getConfigDependentToolDefinitions = (
tools.push(toolDefinitions.multiEditTool);
} else {
tools.push(toolDefinitions.editFileTool);
tools.push(toolDefinitions.singleFindAndReplaceTool);
}
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269

View file

@ -44,9 +44,8 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
shownDeprecatedProviderWarnings: {
[providerTitle: string]: boolean;
};
shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean };
autoUpdateCli: boolean;
mcpOauthStorage: {
[serverUrl: string]: {
clientInformation?: OAuthClientInformationFull;
@ -66,16 +65,7 @@ export class GlobalContext {
) {
const filepath = getGlobalContextFilePath();
if (!fs.existsSync(filepath)) {
fs.writeFileSync(
filepath,
JSON.stringify(
{
[key]: value,
},
null,
2,
),
);
fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2));
} else {
const data = fs.readFileSync(filepath, "utf-8");
@ -113,10 +103,7 @@ export class GlobalContext {
}
// Recreate the file with salvaged values plus the new value
const newData = {
...salvaged,
[key]: value,
};
const newData = { ...salvaged, [key]: value };
fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
return;
@ -174,10 +161,7 @@ export class GlobalContext {
newValues: Partial<SharedConfigSchema>,
): SharedConfigSchema {
const currentSharedConfig = this.getSharedConfig();
const updatedSharedConfig = {
...currentSharedConfig,
...newValues,
};
const updatedSharedConfig = { ...currentSharedConfig, ...newValues };
this.update("sharedConfig", updatedSharedConfig);
return updatedSharedConfig;
}
@ -189,10 +173,7 @@ export class GlobalContext {
): GlobalContextModelSelections {
const currentSelections = this.get("selectedModelsByProfileId") ?? {};
const forProfile = currentSelections[profileId] ?? {};
const newSelections = {
...forProfile,
[role]: title,
};
const newSelections = { ...forProfile, [role]: title };
this.update("selectedModelsByProfileId", {
...currentSelections,

View file

@ -231,12 +231,13 @@ This matrix shows which models support tool use and image input capabilities. Co
| Model | Tool Use | Image Input | Context Window |
| :------------- | -------- | ----------- | -------------- |
| Qwen 3 Coder | Yes | No | 32k |
| Qwen 2.5 VL | No | Yes | 128k |
| Devstral Small | Yes | No | 32k |
| Llama 3.1 | Yes | No | 128k |
| Llama 3 | Yes | No | 8k |
| Mistral | Yes | No | 32k |
| Codestral | Yes | No | 32k |
| Gemma 3 4B | Yes | No | 8k |
| Gemma 3 4B | Yes | Yes | 128k |
### Notes

View file

@ -233,6 +233,7 @@
"guides/codebase-documentation-awareness",
"guides/cli",
"guides/continuous-ai",
"guides/posthog-github-continuous-ai",
"guides/continuous-ai-readiness-assessment",
"guides/plan-mode-guide",
"guides/ollama-guide",

View file

@ -190,9 +190,12 @@ models:
#### If Agent Mode Shows "Not Supported"
![agent not supported](/images/guides/images/agent-not-supported.png)
1. First, add `capabilities: [tool_use]` to your model config
2. If you still get errors, the model may not actually support tools despite documentation
3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral)
4. Alternatively, you can turn on [System Message tools](/features/agent/model-setup#how-system-message-tools-work)
See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details.

View file

@ -14,6 +14,7 @@ description: "Comprehensive collection of practical guides for Continue includin
- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows
- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue
- [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption
- [PostHog Session Analysis with Continue CLI](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation
## What Advanced Tutorials Are Available

View file

@ -0,0 +1,496 @@
---
title: "Building a Continuous AI Workflow with PostHog and GitHub"
description: "Build an automated system that continuously monitors PostHog session recordings, analyzes UX issues using Continue CLI, and creates GitHub issues automatically."
sidebarTitle: "PostHog Session Analysis with Continue CLI"
---
<Card title="What You'll Build" icon="robot">
A fully automated workflow that uses Continue CLI to fetch PostHog session
data, analyze user experience issues with AI, and automatically create GitHub
issues with specific technical recommendations
</Card>
## Prerequisites
Before starting, ensure you have:
- GitHub repository where you want to create issues
- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)**
- Node.js 18+ installed locally
- Continue CLI account with **active credits** (required for API usage)
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Set up Continue CLI Account & API Key">
1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations)
2. Sign up or log in to your Continue account
3. Navigate to your organization settings
4. Click **"API Keys"** and then **"+ New API Key"**
5. Copy the API key immediately (you won't see it again!)
6. Login to the CLI: `cn login`
</Step>
<Step title="Add Required Secrets to Continue CLI">
Continue CLI will securely store your API keys as secrets that can be referenced in prompts.
</Step>
</Steps>
<Tip>
Continue CLI handles all the complex API interactions - you just need to
provide the right prompts!
</Tip>
## Step 1: Set Up Your Credentials
First, you'll need to gather your API credentials and add them as secrets in Continue CLI.
### Get Your PostHog API Credentials
You need a **Personal API Key** (not a Project API key) to access session recordings:
1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog
2. Click **+ Create a personal API Key**
3. Name it "Continue CLI Session Analysis"
4. Select these scopes:
- `session_recording:read` - **Required** for accessing session data
- `insight:read` - Optional, for additional analytics
5. Copy the key immediately (you won't see it again!)
<Tip>
**Find Your Project Details**: Your Project ID is in your PostHog URL:
`https://app.posthog.com/project/YOUR_PROJECT_ID`
</Tip>
### Get Your GitHub Personal Access Token
1. Go to [GitHub Personal Access Tokens](https://github.com/settings/personal-access-tokens/new)
2. Click **"Generate new token (classic)"**
3. Name it "Continue CLI PostHog Analysis"
4. Select these scopes:
- `repo` (or just `public_repo` if your repository is public)
- `issues:write` - **Required** for creating issues
5. Copy the token immediately
### Add Secrets to Continue CLI
Use Continue CLI's built-in environment setup helper:
```bash
cn -p "Help me set up my environment for PostHog session analysis. Please:
1. Check if I have the required secrets configured in Continue CLI:
- POSTHOG_API_KEY
- POSTHOG_PROJECT_ID
- POSTHOG_HOST
- GITHUB_PAT
2. If any are missing, guide me through:
- How to get PostHog Personal API Key from PostHog settings
- How to find my PostHog Project ID from the URL
- How to create a GitHub Personal Access Token with issues:write permission
- How to add these as secrets in Continue CLI
3. Help me identify my GitHub repository owner and name by:
- Checking git remote origin URL
- Or asking me to provide them
4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work.
Please walk me through this setup process step by step."
```
<Info>
Continue CLI will guide you through adding secrets and testing your API
connections. Follow the prompts to add: - `POSTHOG_API_KEY`: Your PostHog
Personal API Key - `POSTHOG_PROJECT_ID`: Your PostHog Project ID -
`POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host) -
`GITHUB_PAT`: Your GitHub Personal Access Token
</Info>
## Step 2: Analyze PostHog Sessions with Continue CLI
Now you'll use Continue CLI to fetch PostHog session data and analyze it for UX issues. Continue CLI handles all the API calls and analysis automatically.
### Run the Analysis
Use this prompt with Continue CLI to fetch and analyze your PostHog sessions:
```bash
cn -p "I need you to help me analyze PostHog session recordings to identify UX issues. Please:
1. First, fetch session recordings from PostHog using these details:
- Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from my secrets
- API endpoint: {POSTHOG_HOST}/api/projects/{POSTHOG_PROJECT_ID}/session_recordings/?limit=20
- Include Authorization header: 'Bearer {POSTHOG_API_KEY}'
2. Filter the sessions to find problematic ones with either:
- console_error_count > 0 (JavaScript errors)
- recording_duration > 300 (sessions longer than 5 minutes)
3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems.
4. Format each issue like this:
### 1. **Issue Title Here**
**Problem**: One sentence describing the user problem
**Technical Causes**: Brief technical explanation
**Affected Pages**: List the URLs
**Recommended Fix**:
- Specific action item 1
- Specific action item 2
**Priority**: **HIGH** or **MEDIUM** or **LOW**
**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions')
Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data."
```
<Info>
**What Continue CLI Does:** - Makes authenticated API calls to PostHog using
your stored secrets - Fetches and filters session recordings automatically -
Analyzes patterns in the data using AI - Generates structured issue
descriptions ready for GitHub
</Info>
<Tip>
Save the analysis output to a file by adding `> analysis-results.txt` to the
command if you want to review it later.
</Tip>
## Step 3: Create GitHub Issues Automatically
Now use Continue CLI to create GitHub issues from your analysis results:
```bash
cn -p "I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API.
Use these details from my secrets:
- GITHUB_PAT: My GitHub Personal Access Token
- Repository: Extract from git remote or ask me to specify
For each issue in my analysis:
1. Parse the issue title, body content, and priority level
2. Create a GitHub issue via API POST to: https://api.github.com/repos/{owner}/{repo}/issues
3. Use these headers:
- Authorization: token {GITHUB_PAT}
- Accept: application/vnd.github.v3+json
- Content-Type: application/json
4. Set labels based on priority:
- HIGH: [\"bug\", \"high-priority\", \"user-experience\", \"automated\"]
- MEDIUM: [\"enhancement\", \"medium-priority\", \"user-experience\", \"automated\"]
- LOW: [\"low-priority\", \"user-experience\", \"automated\"]
5. Format the issue title as: \"🔍 UX Issue: {original title}\"
Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs.
"
```
<Warning>
**Repository Labels Required**: Make sure your GitHub repository has these labels:
- `bug`, `enhancement`
- `high-priority`, `medium-priority`, `low-priority`
- `user-experience`, `automated`
Create missing labels in your repo at: **Settings → Labels → New label**
</Warning>
<Info>
**What Continue CLI Does:** - Parses your analysis results automatically -
Makes authenticated GitHub API calls using your stored token - Creates
properly formatted issues with appropriate labels - Checks for duplicate
issues to avoid spam - Provides confirmation with issue URLs
</Info>
## Step 4: Set Up Automated GitHub Actions Workflow
Create a GitHub Actions workflow that runs your Continue CLI analysis automatically on a schedule.
### Add GitHub Secrets
First, add these secrets to your GitHub repository:
1. Go to **Repository Settings → Secrets and variables → Actions**
2. Click **"New repository secret"** and add:
- `CONTINUE_API_KEY`: Your Continue API key from hub.continue.dev
- `POSTHOG_API_KEY`: Your PostHog Personal API Key
- `POSTHOG_PROJECT_ID`: Your PostHog Project ID
- `POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host)
- `GITHUB_PAT`: Your GitHub Personal Access Token
### Create GitHub Actions Workflow
Create `.github/workflows/posthog-analysis.yml` in your repository:
```yaml
name: PostHog Session Analysis with Continue CLI
on:
schedule:
- cron: "0 6 * * *" # Run at 6 AM UTC daily
workflow_dispatch: # Allow manual triggering
jobs:
analyze:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "18"
- name: Install Continue CLI
run: |
npm install -g @continuedev/cli
echo "✅ Continue CLI installed"
cn --version
- name: Set up environment variables
run: |
echo "POSTHOG_API_KEY=${{ secrets.POSTHOG_API_KEY }}" >> $GITHUB_ENV
echo "POSTHOG_PROJECT_ID=${{ secrets.POSTHOG_PROJECT_ID }}" >> $GITHUB_ENV
echo "POSTHOG_HOST=${{ secrets.POSTHOG_HOST || 'https://us.posthog.com' }}" >> $GITHUB_ENV
echo "GITHUB_PAT=${{ secrets.GITHUB_PAT }}" >> $GITHUB_ENV
echo "GITHUB_OWNER=${{ github.repository_owner }}" >> $GITHUB_ENV
echo "GITHUB_REPO=$(echo ${{ github.repository }} | cut -d'/' -f2)" >> $GITHUB_ENV
- name: Authenticate with Continue CLI
run: |
# Set Continue API key
export CONTINUE_API_KEY="${{ secrets.CONTINUE_API_KEY }}"
# Login to Continue CLI
if ! cn auth login --api-key "$CONTINUE_API_KEY"; then
echo "❌ Failed to authenticate with Continue CLI"
exit 1
fi
echo "✅ Continue CLI authenticated"
- name: Run PostHog Session Analysis
run: |
echo "🎬 Starting PostHog session analysis..."
# Create the analysis prompt
cat > analysis_prompt.txt << 'EOF'
I need you to help me analyze PostHog session recordings to identify UX issues. Please:
1. First, fetch session recordings from PostHog using these details:
- Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from environment variables
- API endpoint: $POSTHOG_HOST/api/projects/$POSTHOG_PROJECT_ID/session_recordings/?limit=20
- Include Authorization header: "Bearer $POSTHOG_API_KEY"
2. Filter the sessions to find problematic ones with either:
- console_error_count > 0 (JavaScript errors)
- recording_duration > 300 (sessions longer than 5 minutes)
3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems.
4. Format each issue like this:
### 1. **Issue Title Here**
**Problem**: One sentence describing the user problem
**Technical Causes**: Brief technical explanation
**Affected Pages**: List the URLs
**Recommended Fix**:
- Specific action item 1
- Specific action item 2
**Priority**: **HIGH** or **MEDIUM** or **LOW**
**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions')
Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data.
Environment context:
- POSTHOG_API_KEY: $POSTHOG_API_KEY
- POSTHOG_PROJECT_ID: $POSTHOG_PROJECT_ID
- POSTHOG_HOST: $POSTHOG_HOST
- GitHub Repo: $GITHUB_OWNER/$GITHUB_REPO
EOF
# Run the analysis
cn < analysis_prompt.txt > analysis-results.txt 2>&1
# Check if analysis completed
if [ ! -s analysis-results.txt ]; then
echo "❌ Analysis failed or produced no output"
exit 1
fi
echo "✅ Analysis completed"
echo "📄 Analysis results preview:"
head -20 analysis-results.txt
- name: Create GitHub Issues from Analysis
run: |
echo "📝 Creating GitHub issues from analysis..."
# Create the issue creation prompt
cat > issue_prompt.txt << 'EOF'
I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API.
Use these details from environment variables:
- GITHUB_PAT: My GitHub Personal Access Token
- Repository: $GITHUB_OWNER/$GITHUB_REPO
For each issue in my analysis:
1. Parse the issue title, body content, and priority level
2. Create a GitHub issue via API POST to: https://api.github.com/repos/$GITHUB_OWNER/$GITHUB_REPO/issues
3. Use these headers:
- Authorization: token $GITHUB_PAT
- Accept: application/vnd.github.v3+json
- Content-Type: application/json
4. Set labels based on priority:
- HIGH: ["bug", "high-priority", "user-experience", "automated"]
- MEDIUM: ["enhancement", "medium-priority", "user-experience", "automated"]
- LOW: ["low-priority", "user-experience", "automated"]
5. Format the issue title as: "🔍 UX Issue: {original title}"
Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs.
Here's my analysis to process:
EOF
# Append the analysis results to the prompt
cat analysis-results.txt >> issue_prompt.txt
# Run the issue creation
cn < issue_prompt.txt > issue-creation-results.txt 2>&1
echo "✅ Issue creation completed"
echo "📄 Issue creation results:"
cat issue-creation-results.txt
- name: Upload Analysis Artifacts
uses: actions/upload-artifact@v4
if: always()
with:
name: analysis-results-${{ github.run_number }}
path: |
analysis-results.txt
issue-creation-results.txt
retention-days: 30
- name: Summary
run: |
echo "✅ PostHog analysis workflow completed!"
echo "📊 Check the artifacts for detailed analysis results"
echo "🐛 Check your repository issues for newly created UX issues"
```
## Step 5: Testing Your Workflow
### Test Locally First
Before setting up automation, test the workflow locally:
**Test 1: Session Analysis**
```bash
cn -p "[Paste the PostHog analysis prompt from Step 2]"
```
Expected: Analysis output with 3 formatted GitHub issues
**Test 2: Issue Creation**
```bash
cn -p "[Paste the GitHub issue creation prompt from Step 3 with your analysis results]"
```
Expected: Confirmation of GitHub issues created with URLs
### Test the GitHub Actions Workflow
1. **Manual Trigger**: Go to **Actions** tab in your repository and manually trigger the workflow
2. **Check Artifacts**: Download the analysis results from the workflow run
3. **Verify Issues**: Check that GitHub issues were created in your repository
<Check>
**Success Indicators:** - PostHog API returns session data (not empty) -
Continue CLI generates analysis with identified issues - GitHub issues are
created with proper labels and formatting - Workflow completes without errors
</Check>
## Troubleshooting
If you encounter issues, use this helpful prompt to diagnose problems:
```bash
cn -p "Help me set up my environment for PostHog session analysis. Please:
1. Check if I have the required secrets configured in Continue CLI:
- POSTHOG_API_KEY
- POSTHOG_PROJECT_ID
- POSTHOG_HOST
- GITHUB_PAT
2. If any are missing, guide me through:
- How to get PostHog Personal API Key from PostHog settings
- How to find my PostHog Project ID from the URL
- How to create a GitHub Personal Access Token with issues:write permission
- How to add these as secrets in Continue CLI
3. Help me identify my GitHub repository owner and name by:
- Checking git remote origin URL
- Or asking me to provide them
4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work.
Please walk me through this setup process step by step."
```
## What You've Built
After completing this guide, you have a complete **Continuous AI system** that:
✅ **Monitors user experience** - Automatically fetches and analyzes PostHog session data
✅ **Identifies problems intelligently** - Uses AI to spot patterns and technical issues
✅ **Creates actionable tasks** - Generates GitHub issues with specific recommendations
✅ **Runs autonomously** - Operates daily without manual intervention using GitHub Actions
✅ **Scales with your team** - Handles growing amounts of session data automatically
<Card title="Continuous AI" icon="rocket">
Your system now operates at **[Level 2 Continuous
AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
AI handles routine analysis tasks with human oversight through GitHub issue
review and prioritization.
</Card>
## Security Best Practices
<Warning>
**Protect Your API Keys:** - Store all credentials as GitHub Secrets, never in
code - Use Continue CLI's secure secret storage - Limit token scopes to
minimum required permissions - Rotate API keys regularly (every 90 days
recommended) - Monitor token usage for unusual activity
</Warning>
## Advanced Prompts
Consider enhancing your workflow with these advanced Continue CLI prompts:
<CardGroup cols={2}>
<Card title="Performance Analysis" icon="chart-line">
"Analyze PostHog performance metrics alongside session recordings to
identify slow page loads affecting user experience"
</Card>
<Card title="Error Correlation" icon="bug">
"Cross-reference JavaScript console errors with user actions to identify the
root cause of UX issues"
</Card>
<Card title="Feature Flag Analysis" icon="flag">
"Analyze how PostHog feature flags impact user behavior in session
recordings"
</Card>
<Card title="Custom Slack Alerts" icon="slack">
"Create Slack alerts when critical UX issues are detected in PostHog
sessions"
</Card>
</CardGroup>
## Next Steps
1. **Monitor your first issues** - Review the GitHub issues created and implement fixes
2. **Measure impact** - Track how resolved issues improve PostHog metrics
3. **Refine prompts** - Adjust the Continue CLI prompts based on issue quality
4. **Scale the system** - Add more data sources or create specialized analysis workflows

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

View file

@ -40,6 +40,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Sign out of your current session",
category: "system",
},
{
name: "update",
description: "Update the Continue CLI",
category: "system",
},
{
name: "whoami",
description: "Check who you're currently logged in as",

View file

@ -107,6 +107,11 @@ process.on("uncaughtException", (error) => {
// Don't exit the process, just log the error
});
// keyboard interruption handler for non-TUI flows
process.on("SIGINT", async () => {
await gracefulExit(130);
});
const program = new Command();
program

View file

@ -0,0 +1,241 @@
import { exec, spawn } from "child_process";
import { promisify } from "util";
import { GlobalContext } from "core/util/GlobalContext.js";
import { logger } from "src/util/logger.js";
import { compareVersions, getLatestVersion, getVersion } from "../version.js";
import { BaseService } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { UpdateServiceState, UpdateStatus } from "./types.js";
const execAsync = promisify(exec);
/**
* Service for checking and performing CLI updates
*/
export class UpdateService extends BaseService<UpdateServiceState> {
constructor() {
super("update", {
autoUpdate: true,
isAutoUpdate: true,
status: UpdateStatus.IDLE,
message: "",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: getVersion(),
});
}
/**
* Initialize the update service
*/
async doInitialize(headless?: boolean) {
// Don't automatically check in tests/headless
if (!headless && process.env.NODE_ENV !== "test") {
void this.checkAndAutoUpdate();
}
return this.currentState;
}
private async checkAndAutoUpdate() {
// First get auto update setting from global context
const globalContext = new GlobalContext();
const autoUpdate = globalContext.get("autoUpdateCli") ?? true;
this.setState({
autoUpdate,
});
try {
// Check for updates
this.setState({
status: UpdateStatus.CHECKING,
message: "Checking for updates",
});
const latestVersion = await getLatestVersion();
this.setState({
latestVersion,
});
if (!latestVersion) {
this.setState({
status: UpdateStatus.IDLE,
message: "Continue CLI",
isUpdateAvailable: false,
});
return;
}
const comparison = compareVersions(
this.currentState.currentVersion,
latestVersion,
);
const isUpdateAvailable = comparison === "older";
this.setState({
isUpdateAvailable,
});
if (this.currentState.currentVersion === "0.0.0-dev") {
this.setState({
status: UpdateStatus.IDLE,
message: `Continue CLI`,
isUpdateAvailable,
latestVersion,
});
return; // Uncomment to test auto-update behavior in dev
}
// If update is available, automatically update
if (
autoUpdate &&
isUpdateAvailable &&
this.currentState.status !== "updating" &&
!process.env.CONTINUE_CLI_AUTO_UPDATED //Already auto updated, preventing sequential auto-update
) {
await this.performUpdate(true);
} else {
this.setState({
status: UpdateStatus.IDLE,
message: isUpdateAvailable
? `Update available: v${latestVersion}`
: `Continue CLI v${this.currentState.currentVersion}`,
isUpdateAvailable,
latestVersion,
});
}
} catch (error: any) {
logger.error("Error checking for updates:", error);
this.setState({
status: UpdateStatus.ERROR,
message: `Continue CLI v${this.currentState.currentVersion}`,
error,
});
}
}
public async setAutoUpdate(value: boolean) {
const globalContext = new GlobalContext();
globalContext.update("autoUpdateCli", value);
this.setState({
autoUpdate: value,
});
}
// TODO this is a hack because our service state update code is broken
// Currently all things that need update use serviceContainer.set manually
// Rather than actually using the stateChanged event
setState(newState: Partial<UpdateServiceState>): void {
super.setState(newState);
serviceContainer.set("update", this.currentState);
}
async performUpdate(isAutoUpdate?: boolean) {
if (this.currentState.status === "updating") {
return;
}
try {
this.setState({
isAutoUpdate,
status: UpdateStatus.UPDATING,
message: `${isAutoUpdate ? "Auto-updating" : "Updating"} to v${this.currentState.latestVersion}`,
});
// Install the update
const { stdout, stderr } = await execAsync("npm i -g @continuedev/cli");
logger.debug("Update output:", { stdout, stderr });
if (stderr) {
const errLines = stderr.split("\n");
for (const line of errLines) {
const lower = line.toLowerCase().trim();
if (
!line ||
lower.includes("debugger") ||
lower.includes("npm warn")
) {
continue;
}
this.setState({
status: UpdateStatus.ERROR,
message: `Error updating to v${this.currentState.latestVersion}`,
error: new Error(stderr),
});
return;
}
}
this.setState({
status: UpdateStatus.UPDATED,
message: `${isAutoUpdate ? "Auto-updated to" : "Restart for"} v${this.currentState.latestVersion}`,
isUpdateAvailable: false,
});
if (isAutoUpdate) {
this.restartCLI();
}
} catch (error: any) {
logger.error("Error updating CLI:", error);
this.setState({
status: UpdateStatus.ERROR,
message: isAutoUpdate ? "Auto-update failed" : "Update failed",
error,
});
setTimeout(() => {
this.setState({
status: UpdateStatus.IDLE,
message: `/update to v${this.currentState.latestVersion}`,
});
}, 4000);
}
}
private restartCLI(): void {
try {
const entryPoint = process.argv[1];
const cliArgs = process.argv.slice(2);
const nodeExecutable = process.execPath;
logger.debug(
`Preparing for CLI restart with: ${nodeExecutable} ${entryPoint} ${cliArgs.join(
" ",
)}`,
);
// Halt/clean up parent cn process
try {
// Remove all input listeners
global.clearTimeout = () => {};
global.clearInterval = () => {};
process.stdin.removeAllListeners();
process.stdin.pause();
// console.clear(); // Don't want to clear things that were in console before cn started
} catch (e) {
logger.debug("Error cleaning up terminal:", e);
}
// Spawn a new detached cn process
const child = spawn(nodeExecutable, [entryPoint, ...cliArgs], {
detached: true,
stdio: "inherit",
env: {
...process.env,
CONTINUE_CLI_AUTO_UPDATED: "true",
},
});
// I did not find a way on existing to avoid a bug where next process has input glitches without leaving parent in place
// So instead of existing, parent will exit when child exits
// process.exit(0);
child.on("exit", (code) => {
process.exit(code);
});
child.unref();
} catch (error) {
logger.error("Failed to restart CLI:", error);
}
}
}

View file

@ -21,6 +21,7 @@ import {
ServiceInitOptions,
ServiceInitResult,
} from "./types.js";
import { UpdateService } from "./UpdateService.js";
// Service instances
const authService = new AuthService();
@ -31,6 +32,7 @@ const mcpService = new MCPService();
const fileIndexService = new FileIndexService();
const resourceMonitoringService = new ResourceMonitoringService();
const chatHistoryService = new ChatHistoryService();
const updateService = new UpdateService();
/**
* Initialize all services and register them with the service container
@ -132,6 +134,12 @@ export async function initializeServices(
[], // No dependencies
);
serviceContainer.register(
SERVICE_NAMES.UPDATE,
() => updateService.initialize(),
[], // No dependencies
);
serviceContainer.register(
SERVICE_NAMES.API_CLIENT,
async () => {
@ -283,17 +291,9 @@ export function reloadService(serviceName: string) {
* Check if all core services are ready
*/
export function areServicesReady(): boolean {
return [
SERVICE_NAMES.TOOL_PERMISSIONS,
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.CONFIG,
SERVICE_NAMES.MODEL,
SERVICE_NAMES.MCP,
SERVICE_NAMES.FILE_INDEX,
SERVICE_NAMES.RESOURCE_MONITORING,
SERVICE_NAMES.CHAT_HISTORY,
].every((name) => serviceContainer.isReady(name));
return Object.values(SERVICE_NAMES).every((name) =>
serviceContainer.isReady(name),
);
}
/**
@ -317,6 +317,7 @@ export const services = {
resourceMonitoring: resourceMonitoringService,
systemMessage: systemMessageService,
chatHistory: chatHistoryService,
updateService: updateService,
} as const;
// Export the service container for advanced usage

View file

@ -81,6 +81,25 @@ export interface MCPServiceState {
prompts: MCPPrompt[];
}
export enum UpdateStatus {
IDLE = "idle",
CHECKING = "checking",
UPDATING = "updating",
UPDATED = "updated",
ERROR = "error",
}
export interface UpdateServiceState {
autoUpdate: boolean;
isAutoUpdate: boolean;
status: UpdateStatus;
message: string;
error?: Error | null;
isUpdateAvailable: boolean;
latestVersion: string | null;
currentVersion: string;
}
export interface ApiClientServiceState {
apiClient: DefaultApiInterface | null;
}
@ -92,8 +111,8 @@ export interface ToolPermissionServiceState {
originalPolicies?: ToolPermissions;
}
export type { FileIndexServiceState } from "./FileIndexService.js";
export type { ChatHistoryState } from "./ChatHistoryService.js";
export type { FileIndexServiceState } from "./FileIndexService.js";
/**
* Service names as constants to prevent typos
@ -109,6 +128,7 @@ export const SERVICE_NAMES = {
RESOURCE_MONITORING: "resourceMonitoring",
SYSTEM_MESSAGE: "systemMessage",
CHAT_HISTORY: "chatHistory",
UPDATE: "update",
} as const;
/**

View file

@ -166,22 +166,15 @@ const commandHandlers: Record<string, CommandHandler> = {
},
fork: handleFork,
init: handleInit,
update: () => {
return { openUpdateSelector: true };
},
};
export async function handleSlashCommands(
input: string,
assistant: AssistantConfig,
): Promise<{
output?: string;
exit?: boolean;
newInput?: string;
clear?: boolean;
openConfigSelector?: boolean;
openModelSelector?: boolean;
openMCPSelector?: boolean;
openSessionSelector?: boolean;
compact?: boolean;
} | null> {
): Promise<SlashCommandResult | null> {
// Only trigger slash commands if slash is the very first character
if (!input.startsWith("/") || !input.trim().startsWith("/")) {
return null;

View file

@ -6,8 +6,10 @@ import {
serviceContainer,
} from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
import type { ModelServiceState } from "../services/types.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "../util/logger.js";
import { isModelCapable } from "../utils/index.js";
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
@ -66,9 +68,53 @@ function getDynamicTools(): Tool[] {
return dynamicTools;
}
// Get all builtin tools including dynamic ones
// Check if the current model is capable and should exclude Edit tool
function shouldExcludeEditTool(): boolean {
try {
const modelServiceResult = getServiceSync<ModelServiceState>(
SERVICE_NAMES.MODEL,
);
if (
modelServiceResult.state === "ready" &&
modelServiceResult.value?.model
) {
const { name, provider, model } = modelServiceResult.value.model;
// Check if model is capable
const isCapable = isModelCapable(provider, name, model);
logger.debug("Capability-based tool filtering", {
provider,
name,
isCapable,
willExcludeEdit: isCapable,
});
return isCapable;
}
} catch (error) {
logger.debug("Error checking model capability for tool filtering", {
error,
});
}
return false;
}
// Get all builtin tools including dynamic ones, with capability-based filtering
export function getAllBuiltinTools(): Tool[] {
return [...BUILTIN_TOOLS, ...getDynamicTools()];
let builtinTools = [...BUILTIN_TOOLS];
// Apply capability-based filtering for edit tools
// If model is capable, exclude editTool in favor of multiEditTool
if (shouldExcludeEditTool()) {
builtinTools = builtinTools.filter((tool) => tool.name !== editTool.name);
logger.debug(
"Excluded Edit tool for capable model - MultiEdit will be used instead",
);
}
return [...builtinTools, ...getDynamicTools()];
}
export function getToolDisplayName(toolName: string): string {

View file

@ -9,7 +9,6 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { editTool } from "./edit.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
@ -133,8 +132,8 @@ export const multiEditTool: Tool = {
displayName: "MultiEdit",
readonly: false,
isBuiltIn: true,
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${editTool.name} tool and allows you to perform multiple find-and-replace operations efficiently.
Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file.
description: `This is a tool for making multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
This tool is ideal when you need to make multiple edits to the same file.
To make multiple edits to a file, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not relative)

View file

@ -0,0 +1,33 @@
import { Text } from "ink";
import React, { useEffect, useState } from "react";
interface LoadingTextProps {
text: string;
color?: string;
interval?: number;
}
export const LoadingText: React.FC<LoadingTextProps> = ({
text,
color = "gray",
interval = 300,
}) => {
const [dotsCount, setDotsCount] = useState(1);
useEffect(() => {
const timer = setInterval(() => {
setDotsCount((current) => (current % 3) + 1);
}, interval);
return () => clearInterval(timer);
}, [interval]);
const dots = ".".repeat(dotsCount);
return (
<Text color={color}>
{text}
{dots}
</Text>
);
};

View file

@ -14,6 +14,7 @@ import {
ConfigServiceState,
MCPServiceState,
ModelServiceState,
UpdateServiceState,
} from "../services/types.js";
import { logger } from "../util/logger.js";
@ -93,7 +94,8 @@ function useTUIChatServices(remoteUrl?: string) {
model: ModelServiceState;
mcp: MCPServiceState;
apiClient: ApiClientServiceState;
}>(["auth", "config", "model", "mcp", "apiClient"]);
update: UpdateServiceState;
}>(["auth", "config", "model", "mcp", "apiClient", "update"]);
return { services, allServicesReady, isRemoteMode };
}
@ -207,6 +209,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
onShowConfigSelector: () => navigateTo("config"),
onShowModelSelector: () => navigateTo("model"),
onShowMCPSelector: () => navigateTo("mcp"),
onShowUpdateSelector: () => navigateTo("update"),
onShowSessionSelector: () => navigateTo("session"),
onLoginPrompt: handleLoginPrompt,
onReload: handleReload,

View file

@ -1,10 +1,3 @@
// Mock the version module before any other imports
vi.mock("../version.js", () => ({
getVersion: vi.fn(),
getLatestVersion: vi.fn(),
compareVersions: vi.fn(),
}));
// Mock useTerminalSize hook
vi.mock("./hooks/useTerminalSize.js", () => ({
useTerminalSize: () => ({ columns: 80, rows: 24 }),
@ -30,93 +23,202 @@ import { render } from "ink-testing-library";
import React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as versionModule from "../version.js";
import { UpdateStatus } from "../services/types.js";
import { UpdateNotification } from "./UpdateNotification.js";
const mockVersionModule = vi.mocked(versionModule);
// Mock useServices hook
const mockUseServices = vi.fn();
vi.mock("../hooks/useService.js", () => ({
useServices: () => mockUseServices(),
}));
describe("UpdateNotification", () => {
let originalNodeEnv: string | undefined;
beforeEach(() => {
vi.clearAllMocks();
originalNodeEnv = process.env.NODE_ENV;
// Default mock implementations
mockVersionModule.getLatestVersion.mockResolvedValue("1.0.1");
mockVersionModule.compareVersions.mockReturnValue("older");
// Default mock implementation - no update available
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Continue CLI v1.0.0",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
});
afterEach(() => {
// Restore original NODE_ENV
if (originalNodeEnv === undefined) {
delete process.env.NODE_ENV;
} else {
process.env.NODE_ENV = originalNodeEnv;
}
vi.clearAllMocks();
});
it("should not check for updates when version ends with -dev", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
mockVersionModule.getVersion.mockReturnValue("1.0.0-dev");
it("should show default message when no update is available", () => {
const { lastFrame } = render(<UpdateNotification />);
render(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
// getLatestVersion should not have been called for dev versions
expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled();
expect(lastFrame()).toContain("◉ Continue CLI v1.0.0");
});
it("should check for updates when version does not end with -dev", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
mockVersionModule.getVersion.mockReturnValue("1.0.0");
it("should show update available message when update is available", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Update available: v1.0.1",
error: null,
isUpdateAvailable: true,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
render(<UpdateNotification />);
const { lastFrame } = render(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
// getLatestVersion should have been called for non-dev versions
expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
expect(lastFrame()).toContain("◉ Update available: v1.0.1");
});
it("should handle various dev version formats", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
const devVersions = ["1.0.0-dev", "2.1.3-dev", "0.5.0-dev"];
it("should show checking message when checking for updates", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.CHECKING,
message: "Checking for updates",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
for (const version of devVersions) {
vi.clearAllMocks();
mockVersionModule.getVersion.mockReturnValue(version);
const { lastFrame } = render(<UpdateNotification />);
render(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled();
}
expect(lastFrame()).toContain("◉ Checking for updates");
});
it("should still check for updates with other version suffixes", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
const nonDevVersions = ["1.0.0-beta", "1.0.0-alpha", "1.0.0-rc1"];
it("should show updating message when updating", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.UPDATING,
message: "Updating to v1.0.1",
error: null,
isUpdateAvailable: false,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
for (const version of nonDevVersions) {
vi.clearAllMocks();
mockVersionModule.getVersion.mockReturnValue(version);
const { lastFrame } = render(<UpdateNotification />);
render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Updating to v1.0.1");
});
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
it("should show updated message when update completes", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.UPDATED,
message: "Auto-updated to v1.0.1",
error: null,
isUpdateAvailable: false,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
}
const { lastFrame } = render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Auto-updated to v1.0.1");
});
it("should show error message when update fails", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.ERROR,
message: "Update failed",
error: new Error("Update error"),
isUpdateAvailable: true,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Update failed");
});
it("should show remote mode when in remote mode and no update available", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Continue CLI v1.0.0",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification isRemoteMode={true} />);
expect(lastFrame()).toContain("◉ Remote Mode");
});
it("should show update message even in remote mode when update is available", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Update available: v1.0.1",
error: null,
isUpdateAvailable: true,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification isRemoteMode={true} />);
expect(lastFrame()).toContain("◉ Update available: v1.0.1");
});
it("should show default message when update service has no message", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Continue CLI");
});
});

View file

@ -1,79 +1,54 @@
import { Text } from "ink";
import React, { useEffect, useMemo, useState } from "react";
import React, { useMemo } from "react";
import { compareVersions, getLatestVersion, getVersion } from "../version.js";
import { useServices } from "../hooks/useService.js";
import {
SERVICE_NAMES,
UpdateServiceState,
UpdateStatus,
} from "../services/types.js";
import { useTerminalSize } from "./hooks/useTerminalSize.js";
interface UpdateNotificationProps {
isRemoteMode?: boolean;
}
const UpdateNotification: React.FC<UpdateNotificationProps> = ({
isRemoteMode = false,
}) => {
const [updateAvailable, setUpdateAvailable] = useState(false);
const [latestVersion, setLatestVersion] = useState<string>("");
const [currentVersion] = useState(getVersion());
const { columns } = useTerminalSize();
useEffect(() => {
// Skip update check in test environment
if (process.env.NODE_ENV === "test") {
return;
const { services } = useServices<{
update: UpdateServiceState;
}>([SERVICE_NAMES.UPDATE]);
const color = useMemo(() => {
switch (services.update?.status) {
case UpdateStatus.UPDATING:
case UpdateStatus.CHECKING:
return "yellow";
case UpdateStatus.UPDATED:
return "green";
case UpdateStatus.ERROR:
return "red";
default:
return "dim";
}
// Skip update check for development versions
if (currentVersion.endsWith("-dev")) {
return;
}
const abortController = new AbortController();
const checkForUpdate = async () => {
try {
const latest = await getLatestVersion(abortController.signal);
if (latest) {
setLatestVersion(latest);
const comparison = compareVersions(currentVersion, latest);
setUpdateAvailable(comparison === "older");
}
} catch (error) {
// Silently fail - we don't want to interrupt the user experience
if (error instanceof Error && error.name !== "AbortError") {
console.debug("Failed to check for updates:", error);
}
}
};
// Check for updates but don't block
checkForUpdate();
// Cleanup function to abort the request when component unmounts
return () => {
abortController.abort();
};
}, [currentVersion]);
}, [services.update?.status]);
const text = useMemo(() => {
if (columns < 75) {
return `v${latestVersion} available`;
if (!services.update?.message) {
return "Continue CLI";
}
return `Update available: v${latestVersion} (npm i -g @continuedev/cli)`;
}, [columns, latestVersion]);
if (!updateAvailable) {
if (isRemoteMode) {
return <Text color="cyan">◉ Remote Mode</Text>;
}
return (
<Text wrap="truncate-end" color="gray">
● Continue CLI
</Text>
);
return services.update.message;
}, [columns, services.update?.message]);
if (!services.update?.isUpdateAvailable && isRemoteMode) {
return <Text color="cyan">◉ Remote Mode</Text>;
}
return <Text color="dim">{text}</Text>;
return <Text color={color}>{`◉ ${text}`}</Text>;
};
export { UpdateNotification };

View file

@ -0,0 +1,93 @@
import React, { useMemo, useState } from "react";
import { useService } from "../hooks/useService.js";
import { services } from "../services/index.js";
import type { UpdateServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { Selector, SelectorOption } from "./Selector.js";
interface UpdateSelectorProps {
onCancel: () => void;
}
interface UpdateOption extends SelectorOption {
action: "run" | "toggle-auto" | "back";
}
export const UpdateSelector: React.FC<UpdateSelectorProps> = ({ onCancel }) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const updateServiceState = useService<UpdateServiceState>(
SERVICE_NAMES.UPDATE,
);
const updateState = updateServiceState.value;
const isWorking =
updateServiceState.state === "loading" ||
updateState?.status === "checking" ||
updateState?.status === "updating";
const error: string | null = useMemo(() => {
if (updateServiceState.state === "error") {
return updateServiceState.error?.message || "Update service error";
}
if (updateState?.status === "error") {
return updateState.message || "Update failed";
}
return null;
}, [updateServiceState.state, updateServiceState.error, updateState]);
const loadingMessage = useMemo(() => {
if (!updateState) return "Preparing update...";
return updateState.message || "Working...";
}, [updateState]);
const options: UpdateOption[] = useMemo(() => {
const runLabel = updateState?.latestVersion
? `Run update to v${updateState.latestVersion}`
: "Run update";
const autoUpdateLabel = updateState?.autoUpdate
? "Turn off auto-updates"
: "Turn on auto-updates";
return [
{ id: "run-update", name: runLabel, action: "run" },
{ id: "toggle-auto", name: autoUpdateLabel, action: "toggle-auto" },
{ id: "back", name: "Back", action: "back" },
];
}, [updateState?.latestVersion, updateState?.autoUpdate]);
const handleSelect = async (option: UpdateOption) => {
switch (option.action) {
case "run":
// Perform a manual update (not auto-update)
await services.updateService.performUpdate(false);
return; // Keep selector open to show status changes
case "toggle-auto":
// Toggle auto-update setting
const newValue = !updateState?.autoUpdate;
await services.updateService.setAutoUpdate(newValue);
return; // Keep selector open to show updated label
case "back":
onCancel();
return;
}
};
return (
<Selector
title="Update Continue CLI"
options={options}
selectedIndex={selectedIndex}
loading={!!isWorking}
error={error}
loadingMessage={loadingMessage}
currentId={null}
onSelect={handleSelect}
onCancel={onCancel}
onNavigate={setSelectedIndex}
/>
);
};

View file

@ -1,6 +1,8 @@
import { Box, Text } from "ink";
import React from "react";
import { UpdateServiceState } from "src/services/types.js";
import { listSessions } from "../../session.js";
import { ConfigSelector } from "../ConfigSelector.js";
import type { NavigationScreen } from "../context/NavigationContext.js";
@ -9,6 +11,7 @@ import { MCPSelector } from "../MCPSelector.js";
import { ModelSelector } from "../ModelSelector.js";
import { SessionSelector } from "../SessionSelector.js";
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
import { UpdateSelector } from "../UpdateSelector.js";
import { UserInput } from "../UserInput.js";
import { ToolPermissionSelector } from "./ToolPermissionSelector.js";
@ -42,6 +45,14 @@ interface ScreenContentProps {
onImageInClipboardChange?: (hasImage: boolean) => void;
}
function hideScreenContent(state?: UpdateServiceState) {
return (
(state?.status === "checking" && state?.autoUpdate) ||
(state?.isAutoUpdate &&
(state?.status === "updating" || state?.status === "updated"))
);
}
export const ScreenContent: React.FC<ScreenContentProps> = ({
isScreenActive,
navState,
@ -65,6 +76,10 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
isRemoteMode,
onImageInClipboardChange,
}) => {
if (hideScreenContent(services.update)) {
return null;
}
// Login prompt
if (isScreenActive("login") && navState.screenData) {
return (
@ -106,6 +121,10 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
return <MCPSelector onCancel={closeCurrentScreen} />;
}
if (isScreenActive("update")) {
return <UpdateSelector onCancel={closeCurrentScreen} />;
}
// Model selector
if (isScreenActive("model")) {
return (

View file

@ -1,9 +1,9 @@
import React, {
createContext,
ReactNode,
useCallback,
useContext,
useReducer,
useCallback,
ReactNode,
} from "react";
/**
@ -17,6 +17,7 @@ export type NavigationScreen =
| "free-trial" // Free trial transition UI
| "login" // Login prompt
| "mcp" // MCP selector
| "update" // Update selector
| "session"; // Session selector
interface NavigationState {

View file

@ -48,6 +48,7 @@ interface ProcessSlashCommandResultOptions {
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
onShowConfigSelector: () => void;
onShowModelSelector?: () => void;
onShowUpdateSelector?: () => void;
onShowMCPSelector?: () => void;
onShowSessionSelector?: () => void;
onClear?: () => void;
@ -61,6 +62,7 @@ export function processSlashCommandResult({
chatHistory,
setChatHistory,
onShowConfigSelector,
onShowUpdateSelector,
onShowModelSelector,
onShowMCPSelector,
onShowSessionSelector,
@ -75,6 +77,11 @@ export function processSlashCommandResult({
return null;
}
if (result.openUpdateSelector) {
onShowUpdateSelector?.();
return null;
}
if (result.openConfigSelector) {
onShowConfigSelector();
return null;

View file

@ -55,6 +55,7 @@ export function useChat({
additionalPrompts,
onShowConfigSelector,
onShowModelSelector,
onShowUpdateSelector,
onShowMCPSelector,
onShowSessionSelector,
onLoginPrompt: _onLoginPrompt,
@ -419,6 +420,7 @@ export function useChat({
onShowModelSelector,
onShowMCPSelector,
onShowSessionSelector,
onShowUpdateSelector,
onClear,
});

View file

@ -15,6 +15,7 @@ export interface UseChatProps {
additionalPrompts?: string[];
onShowConfigSelector: () => void;
onShowMCPSelector: () => void;
onShowUpdateSelector: () => void;
onShowModelSelector?: () => void;
onShowSessionSelector?: () => void;
onLoginPrompt?: (promptText: string) => Promise<string>;
@ -57,6 +58,7 @@ export interface SlashCommandResult {
openConfigSelector?: boolean;
openModelSelector?: boolean;
openMcpSelector?: boolean;
openUpdateSelector?: boolean;
openSessionSelector?: boolean;
compact?: boolean;
}

View file

@ -1,5 +1,5 @@
pluginGroup=com.github.continuedev.continueintellijextension
pluginVersion=1.0.43
pluginVersion=1.0.44
platformVersion=2024.1
kotlin.stdlib.default.dependency=false
org.gradle.configuration-cache=true

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.3.8",
"version": "1.3.10",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -1,6 +1,6 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers, RuleWithSource } from "core";
import { useMemo } from "react";
import { memo, useMemo } from "react";
import { defaultBorderRadius, vscBackground } from "..";
import { useAppSelector } from "../../redux/hooks";
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
@ -69,16 +69,20 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const historyKey = isInEdit ? "edit" : "chat";
const placeholder = isInEdit ? "Edit selected code" : undefined;
const toolbarOptions: ToolbarOptions = isInEdit
? {
const toolbarOptions: ToolbarOptions = useMemo(() => {
if (isInEdit) {
return {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText:
editModeState.applyState.status === "done" ? "Retry" : "Edit",
}
: {};
} as ToolbarOptions;
}
// Stable empty object to avoid re-renders from identity changes
return {} as ToolbarOptions;
}, [isInEdit, editModeState.applyState.status]);
const { appliedRules = [], contextItems = [] } = props;
@ -123,4 +127,4 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
);
}
export default ContinueInputBox;
export default memo(ContinueInputBox);

View file

@ -9,7 +9,7 @@ import {
modelSupportsImages,
modelSupportsReasoning,
} from "core/llm/autodetect";
import { useContext, useRef } from "react";
import { memo, useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
@ -242,4 +242,24 @@ function InputToolbar(props: InputToolbarProps) {
);
}
export default InputToolbar;
function shallowToolbarOptionsEqual(a?: ToolbarOptions, b?: ToolbarOptions) {
if (a === b) return true;
if (!a || !b) return false;
return (
a.hideAddContext === b.hideAddContext &&
a.hideImageUpload === b.hideImageUpload &&
a.hideUseCodebase === b.hideUseCodebase &&
a.hideSelectModel === b.hideSelectModel &&
a.enterText === b.enterText
);
}
export default memo(
InputToolbar,
(prev, next) =>
prev.hidden === next.hidden &&
prev.disabled === next.disabled &&
prev.isMainInput === next.isMainInput &&
prev.activeKey === next.activeKey &&
shallowToolbarOptionsEqual(prev.toolbarOptions, next.toolbarOptions),
);

View file

@ -1,7 +1,14 @@
import { Editor, EditorContent, JSONContent } from "@tiptap/react";
import { ContextProviderDescription, InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import {
memo,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
import useUpdatingRef from "../../../hooks/useUpdatingRef";
@ -38,7 +45,7 @@ export interface TipTapEditorProps {
export const TIPPY_DIV_ID = "tippy-js-div";
export function TipTapEditor(props: TipTapEditorProps) {
function TipTapEditorInner(props: TipTapEditorProps) {
const dispatch = useAppDispatch();
const mainEditorContext = useMainEditor();
@ -72,12 +79,13 @@ export function TipTapEditor(props: TipTapEditorProps) {
return;
}
const placeholder = getPlaceholderText(props.placeholder, historyLength);
editor.extensionManager.extensions.filter(
(extension) => extension.name === "placeholder",
)[0].options["placeholder"] = placeholder;
editor.view.dispatch(editor.state.tr);
const placeholderExt = editor.extensionManager.extensions.find(
(e) => e.name === "placeholder",
) as any;
if (placeholderExt) {
placeholderExt.options["placeholder"] = placeholder;
editor.view.dispatch(editor.state.tr);
}
}, [editor, props.placeholder, historyLength]);
useEffect(() => {
@ -281,3 +289,37 @@ export function TipTapEditor(props: TipTapEditorProps) {
</InputBoxDiv>
);
}
function toolbarOptionsEqual(a?: ToolbarOptions, b?: ToolbarOptions) {
if (a === b) return true;
if (!a || !b) return false;
return (
a.hideAddContext === b.hideAddContext &&
a.hideImageUpload === b.hideImageUpload &&
a.hideUseCodebase === b.hideUseCodebase &&
a.hideSelectModel === b.hideSelectModel &&
a.enterText === b.enterText
);
}
const MemoInner = memo(
TipTapEditorInner,
(prev, next) =>
prev.isMainInput === next.isMainInput &&
prev.placeholder === next.placeholder &&
prev.historyKey === next.historyKey &&
prev.inputId === next.inputId &&
toolbarOptionsEqual(prev.toolbarOptions, next.toolbarOptions) &&
(prev.availableContextProviders?.length || 0) ===
(next.availableContextProviders?.length || 0) &&
(prev.availableSlashCommands?.length || 0) ===
(next.availableSlashCommands?.length || 0),
);
export function TipTapEditor(props: TipTapEditorProps) {
return (
<div className="relative w-full">
<MemoInner {...props} />
</div>
);
}

View file

@ -1,5 +1,5 @@
import { Editor } from "@tiptap/react";
import { KeyboardEvent } from "react";
import { KeyboardEvent, useRef } from "react";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../../util";
import {
handleJetBrainsOSRMetaKeyIssues,
@ -13,6 +13,7 @@ export function useEditorEventHandlers(options: {
setActiveKey: (key: string | null) => void;
}) {
const { editor, isOSREnabled, editorFocusedRef, setActiveKey } = options;
const metaActiveRef = useRef(false);
/**
* This handles various issues with meta key actions
@ -31,10 +32,14 @@ export function useEditorEventHandlers(options: {
return;
}
setActiveKey(e.key);
if (!editorFocusedRef?.current || !isMetaEquivalentKeyPressed(e)) return;
// Only set activeKey for Meta/Control/Alt to drive toolbar highlighting
if (e.key === "Meta" || e.key === "Control" || e.key === "Alt") {
setActiveKey(e.key);
metaActiveRef.current = true;
}
if (isOSREnabled) {
handleJetBrainsOSRMetaKeyIssues(e, editor);
} else if (!isJetBrains()) {
@ -42,7 +47,12 @@ export function useEditorEventHandlers(options: {
}
};
const handleKeyUp = () => setActiveKey(null);
const handleKeyUp = () => {
if (metaActiveRef.current) {
setActiveKey(null);
metaActiveRef.current = false;
}
};
return { handleKeyDown, handleKeyUp };
}

View file

@ -0,0 +1,70 @@
import { CSSProperties, useEffect, useRef } from "react";
/**
* useRenderDebug
*
* Developer utility to visualize component re-renders.
*
* - Returns a `ref` to attach to a container element and a `count` that
* increments on every render of the component using this hook.
* - On each render, it briefly adds a CSS class (default: `rerender-flash`)
* to the element for a quick visual flash.
* - Use together with <RenderCountBadge /> to show the render count inline.
*
* Options:
* - enabled: boolean to toggle the effect (default true)
* - flashClassName: class added on each render (default `rerender-flash`)
* - flashDurationMs: duration of the flash animation in ms (default 180)
*/
export function useRenderDebug(options?: {
enabled?: boolean;
flashClassName?: string;
flashDurationMs?: number;
}) {
const {
enabled = true,
flashClassName = "rerender-flash",
flashDurationMs = 180,
} = options || {};
const ref = useRef<HTMLElement | null>(null);
const countRef = useRef(0);
countRef.current += 1;
useEffect(() => {
if (!enabled || !ref.current) return;
const el = ref.current;
el.classList.add(flashClassName);
const t = setTimeout(
() => el.classList.remove(flashClassName),
flashDurationMs,
);
return () => {
clearTimeout(t);
// Ensure we don't leave the flash class applied on cleanup
el.classList.remove(flashClassName);
};
});
return { ref, count: countRef.current, countRef } as const;
}
export function RenderCountBadge(props: {
count: number;
title?: string;
style?: CSSProperties;
className?: string;
}) {
// Simple badge for use with useRenderDebug; keep lightweight.
const { count, title = `Renders: ${count}`, style, className } = props;
return (
<span
className={`render-count ${className || ""}`}
title={title}
style={style}
>
R{count}
</span>
);
}

View file

@ -119,3 +119,28 @@ body {
.scroll-container:is(:hover, :focus)::-webkit-scrollbar {
display: block; /* Show scrollbar only on hover or focus */
}
/* Debug: visible flash when component re-renders */
@keyframes rerenderFlash {
0% {
box-shadow: 0 0 0 2px rgba(255, 0, 0, 0.9) inset;
}
100% {
box-shadow: 0 0 0 0 rgba(255, 0, 0, 0) inset;
}
}
.rerender-flash {
animation: rerenderFlash 180ms ease-out;
}
.render-count {
display: inline-block;
margin-right: 6px;
padding: 0 4px;
border-radius: 3px;
background: rgba(255, 0, 0, 0.15);
color: rgba(255, 0, 0, 0.9);
font-weight: 600;
letter-spacing: 0.02em;
}

View file

@ -57,12 +57,7 @@ export function ToolPoliciesGroup({
: `Enable all tools in ${groupName} group`
}
>
<div
onClick={(e) => {
e.stopPropagation();
dispatch(toggleToolGroupSetting(groupName));
}}
>
<div>
<ToggleSwitch
isToggled={isGroupEnabled}
onToggle={() => dispatch(toggleToolGroupSetting(groupName))}

View file

@ -49,6 +49,8 @@ import { cancelStream } from "../../redux/thunks/cancelStream";
import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
import { useAutoScroll } from "./useAutoScroll";
import { useStore } from "react-redux";
import { RootState } from "../../redux/store";
// Helper function to find the index of the latest conversation summary
function findLatestSummaryIndex(history: ChatHistoryItem[]): number {
@ -98,13 +100,11 @@ function fallbackRender({ error, resetErrorBoundary }: any) {
export function Chat() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const reduxStore = useStore<RootState>();
const onboardingCard = useOnboardingCard();
const showSessionTabs = useAppSelector(
(store) => store.config.config.ui?.showSessionTabs,
);
const selectedModels = useAppSelector(
(store) => store.config?.config.selectedModelByRole,
);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const [stepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
@ -115,7 +115,6 @@ export function Chat() {
(state) => state.config.config.ui?.showChatScrollbar,
);
const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit);
const mode = useAppSelector((store) => store.session.mode);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const lastSessionId = useAppSelector((state) => state.session.lastSessionId);
@ -152,9 +151,6 @@ export function Chat() {
isStreaming,
);
const pendingToolCalls = useAppSelector(selectPendingToolCalls);
const pendingApplyStates = useAppSelector(selectDoneApplyStates);
const sendInput = useCallback(
(
editorState: JSONContent,
@ -162,8 +158,16 @@ export function Chat() {
index?: number,
editorToClearOnSend?: Editor,
) => {
const stateSnapshot = reduxStore.getState();
const latestPendingToolCalls = selectPendingToolCalls(stateSnapshot);
const latestPendingApplyStates = selectDoneApplyStates(stateSnapshot);
const isCurrentlyInEdit = stateSnapshot.session.isInEdit;
const codeToEditSnapshot = stateSnapshot.editModeState.codeToEdit;
const selectedModelByRole =
stateSnapshot.config.config.selectedModelByRole;
// Cancel all pending tool calls
pendingToolCalls.forEach((toolCallState) => {
latestPendingToolCalls.forEach((toolCallState) => {
dispatch(
cancelToolCall({
toolCallId: toolCallState.toolCallId,
@ -172,19 +176,20 @@ export function Chat() {
});
// Reject all pending apply states
pendingApplyStates.forEach((applyState) => {
latestPendingApplyStates.forEach((applyState) => {
if (applyState.status !== "closed") {
ideMessenger.post("rejectDiff", applyState);
}
});
const model = isInEdit
? (selectedModels?.edit ?? selectedModels?.chat)
: selectedModels?.chat;
const model = isCurrentlyInEdit
? (selectedModelByRole.edit ?? selectedModelByRole.chat)
: selectedModelByRole.chat;
if (!model) {
return;
}
if (isInEdit && codeToEdit.length === 0) {
if (isCurrentlyInEdit && codeToEditSnapshot.length === 0) {
return;
}
@ -212,11 +217,11 @@ export function Chat() {
// }
// }
if (isInEdit) {
if (isCurrentlyInEdit) {
void dispatch(
streamEditThunk({
editorState,
codeToEdit,
codeToEdit: codeToEditSnapshot,
}),
);
} else {
@ -227,15 +232,7 @@ export function Chat() {
}
}
},
[
history,
selectedModels,
mode,
isInEdit,
codeToEdit,
pendingToolCalls,
pendingApplyStates,
],
[dispatch, ideMessenger, reduxStore],
);
useWebviewListener(

View file

@ -236,10 +236,11 @@ describe("FindAndReplaceDisplay", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(screen.getByText("Error generating diff")).toBeInTheDocument();
// When diff generation errors, component shows a friendly message
// without rendering the expand/collapse container
expect(
screen.getByText("The searched string was not found in the file"),
).toBeInTheDocument();
});
it("should show 'No changes to display' when diff is empty", () => {

View file

@ -30,7 +30,7 @@ const MAX_SAME_LINES = 2;
function EllipsisLine() {
return (
<div className="text-description-muted px-3 py-1 text-center font-mono">
<div className="text-description-muted px-3 py-1 text-left font-mono">
⋯
</div>
);
@ -68,6 +68,19 @@ function DiffLines({
);
}
function DiffStats({ added, removed }: { added: number; removed: number }) {
if (added === 0 && removed === 0) {
return null;
}
return (
<div className="flex items-center gap-1 font-mono text-xs">
{added > 0 && <span className="text-success">+{added}</span>}
{removed > 0 && <span className="text-error">-{removed}</span>}
</div>
);
}
export function FindAndReplaceDisplay({
fileUri,
relativeFilePath,
@ -141,6 +154,30 @@ export function FindAndReplaceDisplay({
}
}, [currentFileContent, edits]);
const diffStats = useMemo(() => {
if (!diffResult?.diff) {
return { added: 0, removed: 0 };
}
let added = 0;
let removed = 0;
diffResult.diff.forEach((part) => {
const lines = part.value.split("\n");
// Exclude empty line at the end (similar to DiffLines component logic)
const lineCount =
lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
if (part.added) {
added += lineCount;
} else if (part.removed) {
removed += lineCount;
}
});
return { added, removed };
}, [diffResult?.diff]);
const statusIcon = useMemo(() => {
const status = toolCallState?.status;
if (status) {
@ -174,24 +211,27 @@ export function FindAndReplaceDisplay({
setIsExpanded(!showContent);
}}
>
<div className="flex max-w-[50%] flex-row items-center text-xs">
{statusIcon}
<ChevronDownIcon
data-testid="toggle-find-and-replace-diff"
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer select-none transition-all hover:brightness-125 ${
showContent ? "rotate-0" : "-rotate-90"
}`}
/>
<FileInfo
filepath={displayName || "..."}
onClick={(e) => {
if (!fileUri) {
return;
}
e.stopPropagation();
ideMessenger.post("openFile", { path: fileUri });
}}
/>
<div className="flex min-w-0 flex-1 flex-row items-center gap-2 text-xs">
<div className="flex min-w-0 flex-row items-center">
{statusIcon}
<ChevronDownIcon
data-testid="toggle-find-and-replace-diff"
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer select-none transition-all hover:brightness-125 ${
showContent ? "rotate-0" : "-rotate-90"
}`}
/>
<FileInfo
filepath={displayName || "..."}
onClick={(e) => {
if (!fileUri) {
return;
}
e.stopPropagation();
ideMessenger.post("openFile", { path: fileUri });
}}
/>
</div>
<DiffStats added={diffStats.added} removed={diffStats.removed} />
</div>
{applyState && (
@ -218,10 +258,10 @@ export function FindAndReplaceDisplay({
);
if (diffResult?.error) {
return renderContainer(
<div className="text-error p-3 text-sm">
<strong>Error generating diff</strong>
</div>,
return (
<div className="text-description mt-2 px-3">
The searched string was not found in the file
</div>
);
}

View file

@ -6,9 +6,7 @@ import {
} from "../../../components/mainInput/belowMainInput/ContextItemsPeek";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { ToggleWithIcon } from "./ToggleWithIcon";
import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs";
import { ToolCallStatusMessage } from "./ToolCallStatusMessage";
import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon";
import { toolCallStateToContextItems } from "./utils";
interface SimpleToolCallUIProps {
@ -31,11 +29,6 @@ export function SimpleToolCallUI({
}, [toolCallState]);
const [open, setOpen] = useState(false);
const [showingArgs, setShowingArgs] = useState(false);
const args: [string, any][] = useMemo(() => {
return Object.entries(toolCallState.parsedArgs);
}, [toolCallState.parsedArgs]);
const isToggleable = shownContextItems.length > 1;
const isSingleItem = shownContextItems.length === 1;
@ -81,19 +74,7 @@ export function SimpleToolCallUI({
/>
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
</div>
<div className="flex flex-row items-center gap-1.5">
{!!toolCallState.output?.length && (
<ToolTruncateHistoryIcon historyIndex={historyIndex} />
)}
{args.length > 0 ? (
<ArgsToggleIcon
isShowing={showingArgs}
setIsShowing={setShowingArgs}
/>
) : null}
</div>
</div>
<ArgsItems args={args} isShowing={showingArgs} />
{isToggleable && (
<div

View file

@ -1,8 +1,5 @@
import { Tool, ToolCallState } from "core";
import { useMemo, useState } from "react";
import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs";
import { ToolCallStatusMessage } from "./ToolCallStatusMessage";
import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon";
interface ToolCallDisplayProps {
children: React.ReactNode;
@ -19,12 +16,6 @@ export function ToolCallDisplay({
icon,
historyIndex,
}: ToolCallDisplayProps) {
const [argsExpanded, setArgsExpanded] = useState(false);
const args: [string, any][] = useMemo(() => {
return Object.entries(toolCallState.parsedArgs);
}, [toolCallState.parsedArgs]);
return (
<div className="flex flex-col justify-center px-4">
<div className="mb-2 flex flex-col">
@ -38,21 +29,7 @@ export function ToolCallDisplay({
)}
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
</div>
<div className="flex flex-row items-center gap-1.5">
{!!toolCallState.output && (
<ToolTruncateHistoryIcon historyIndex={historyIndex} />
)}
{!!args.length ? (
<ArgsToggleIcon
isShowing={argsExpanded}
setIsShowing={setArgsExpanded}
/>
) : null}
</div>
</div>
{argsExpanded && !!args.length && (
<ArgsItems args={args} isShowing={argsExpanded} />
)}
</div>
<div>{children}</div>
</div>

View file

@ -34,7 +34,7 @@ export function getStatusIntro(
switch (status) {
case "generating":
return "is generating output to";
return "will";
case "generated":
return "wants to";
case "calling":

View file

@ -73,6 +73,8 @@ test(
store.dispatch(setInactive());
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
// Provide empty open files to avoid MockIdeMessenger throwing on getOpenFiles
ideMessenger.responses["getOpenFiles"] = [] as any;
ideMessenger.responses["tools/evaluatePolicy"] = {
policy: "allowedWithPermission",
};

View file

@ -11,10 +11,10 @@ import {
setToolCallCalling,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import { ThunkApiType } from "../store";
import { findToolCallById, logToolUsage } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
export const callToolById = createAsyncThunk<
void,
@ -43,14 +43,15 @@ export const callToolById = createAsyncThunk<
DEFAULT_TOOL_SETTING;
const isAutoApproved = toolPolicy === "allowedWithoutPermission";
const selectedChatModel = selectSelectedChatModel(state);
posthog.capture("gui_tool_call_decision", {
model: selectedChatModel,
decision: isAutoApproved ? "auto_accept" : "accept",
toolName: toolCallState.toolCall.function.name,
toolCallId: toolCallId,
});
const selectedChatModel = selectSelectedChatModel(state);
if (!selectedChatModel) {
throw new Error("No model selected");
}
@ -129,6 +130,7 @@ export const callToolById = createAsyncThunk<
// Capture telemetry for tool call execution outcome with duration
const duration_ms = Date.now() - startTime;
posthog.capture("gui_tool_call_outcome", {
model: selectedChatModel,
succeeded: errorMessage === undefined,
toolName: toolCallState.toolCall.function.name,
errorMessage: errorMessage,

View file

@ -1,5 +1,6 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import posthog from "posthog-js";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
cancelToolCall as cancelToolCallAction,
updateToolCallOutput,
@ -19,6 +20,7 @@ export const cancelToolCallThunk = createAsyncThunk<
ThunkApiType
>("chat/cancelToolCall", async ({ toolCallId }, { dispatch, getState }) => {
const state = getState();
const selectedChatModel = selectSelectedChatModel(state);
const continueAfterToolRejection =
state.config.config.ui?.continueAfterToolRejection;
const toolCallState = findToolCallById(state.session.history, toolCallId);
@ -26,6 +28,7 @@ export const cancelToolCallThunk = createAsyncThunk<
if (toolCallState) {
// Track tool call rejection
posthog.capture("gui_tool_call_decision", {
model: selectedChatModel,
decision: "reject",
toolName: toolCallState.toolCall.function.name,
toolCallId: toolCallId,

View file

@ -565,18 +565,25 @@ describe("streamResponseThunk - tool calls", () => {
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify telemetry events for auto-approved tool execution
expect(mockPosthog.capture).toHaveBeenCalledWith("gui_tool_call_decision", {
decision: "auto_accept",
toolName: "search_codebase",
toolCallId: "tool-call-1",
});
// Use partial matching to allow additional fields (e.g. model) in payload
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_decision",
expect.objectContaining({
decision: "auto_accept",
toolName: "search_codebase",
toolCallId: "tool-call-1",
}),
);
expect(mockPosthog.capture).toHaveBeenCalledWith("gui_tool_call_outcome", {
succeeded: true,
toolName: "search_codebase",
errorMessage: undefined,
duration_ms: expect.any(Number),
});
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_outcome",
expect.objectContaining({
succeeded: true,
toolName: "search_codebase",
errorMessage: undefined,
duration_ms: expect.any(Number),
}),
);
// Verify final state after tool call execution
const finalState = mockStoreWithToolSettings.getState();
@ -2810,18 +2817,25 @@ describe("streamResponseThunk - tool calls", () => {
]);
// Verify telemetry events for manual approval flow
expect(mockPosthog.capture).toHaveBeenCalledWith("gui_tool_call_decision", {
decision: "accept",
toolName: "search_codebase",
toolCallId: "tool-approval-flow-1",
});
// Use partial matching to allow additional fields (e.g. model) in payload
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_decision",
expect.objectContaining({
decision: "accept",
toolName: "search_codebase",
toolCallId: "tool-approval-flow-1",
}),
);
expect(mockPosthog.capture).toHaveBeenCalledWith("gui_tool_call_outcome", {
succeeded: true,
toolName: "search_codebase",
errorMessage: undefined,
duration_ms: expect.any(Number),
});
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_outcome",
expect.objectContaining({
succeeded: true,
toolName: "search_codebase",
errorMessage: undefined,
duration_ms: expect.any(Number),
}),
);
// Verify IDE messenger calls for tool execution
expect(mockIdeMessengerApproval.request).toHaveBeenCalledWith(

View file

@ -1,15 +1,15 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.96",
"version": "1.14.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/config-yaml",
"version": "1.0.96",
"version": "1.14.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.96",
"version": "1.14.0",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -23,7 +23,7 @@
"author": "Continue Dev, Inc.",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/fetch",
"version": "1.0.16",
"version": "1.1.0",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -12,7 +12,7 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
@ -21,6 +21,11 @@
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
"vitest": "^3.2.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"semantic-release": "^21.1.2"
}
}

View file

@ -1,15 +1,15 @@
{
"name": "@continuedev/hub",
"version": "0.0.4",
"version": "0.0.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/hub",
"version": "0.0.4",
"version": "0.0.7",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-yaml": "^1.0.70"
"@continuedev/config-yaml": "^1.14.0"
},
"devDependencies": {
"@types/jest": "^29.5.14",
@ -544,13 +544,17 @@
}
},
"node_modules/@continuedev/config-yaml": {
"version": "1.0.70",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.70.tgz",
"integrity": "sha512-0hwc2a2NyUDDNDAx23SOFfY4sV8EafuCow4JNpRzCz8swH3ZfO+vdOzKMIEzAzcYXcpjldsOAZsYE4iypu1L+Q==",
"version": "1.14.0",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.14.0.tgz",
"integrity": "sha512-MRi2SKTLkXme/lyFZruXGhWsaH9eMHvgkj/gAQcAhe6LxvbEOt2SyG7IS/t/8fDRJ2pXIjK/FtJpdKarXokJpA==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
"bin": {
"config-yaml": "dist/cli.js"
}
},
"node_modules/@cspotcode/source-map-support": {

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/hub",
"version": "0.0.4",
"version": "0.0.7",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -12,7 +12,7 @@
"author": "Continue Dev, Inc.",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-yaml": "^1.0.70"
"@continuedev/config-yaml": "^1.14.0"
},
"devDependencies": {
"@types/jest": "^29.5.14",

File diff suppressed because it is too large Load diff

View file

@ -13,6 +13,11 @@
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^22.15.29",
"typescript": "^5.5.2"
"typescript": "^5.5.2",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"semantic-release": "^21.1.2"
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.5.1",
"version": "1.14.0",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -15,8 +15,8 @@
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.8.0",
"@continuedev/fetch": "^1.0.16",
"@continuedev/config-yaml": "^1.14.0",
"@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",

View file

@ -12,6 +12,7 @@ dotenv.config();
export interface TestConfigOptions {
skipTools: boolean;
expectUsage?: boolean;
skipSystemMessage?: boolean;
}
function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) {
@ -98,9 +99,9 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
},
{
provider: "mistral",
model: "codestral",
model: "codestral-latest",
apiKey: process.env.MISTRAL_API_KEY!,
roles: ["chat"],
roles: ["chat", "autocomplete"],
options: {
skipTools: false,
expectUsage: true,
@ -150,6 +151,7 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
options: {
skipTools: true,
expectUsage: true,
skipSystemMessage: true,
},
},
{

View file

@ -210,26 +210,28 @@ export function testChat(
});
test("should acknowledge system message in chat", async () => {
const response = await api.chatCompletionNonStream(
{
model,
messages: [
{
role: "system",
content:
"Regardless of what is asked of you, your answer should start with 'RESPONSE: '.",
},
{ role: "user", content: "Who are you?" },
],
stream: false,
},
new AbortController().signal,
);
expect(response.choices.length).toBeGreaterThan(0);
const completion = response.choices[0].message.content;
expect(typeof completion).toBe("string");
expect(completion?.length).toBeGreaterThan(0);
expect(completion?.startsWith("RESPONSE: ")).toBe(true);
if (options?.skipSystemMessage !== true) {
const response = await api.chatCompletionNonStream(
{
model,
messages: [
{
role: "system",
content:
"Regardless of what is asked of you, your answer should start with 'RESPONSE: '.",
},
{ role: "user", content: "Who are you?" },
],
stream: false,
},
new AbortController().signal,
);
expect(response.choices.length).toBeGreaterThan(0);
const completion = response.choices[0].message.content;
expect(typeof completion).toBe("string");
expect(completion?.length).toBeGreaterThan(0);
expect(completion?.startsWith("RESPONSE: ")).toBe(true);
}
});
if (options?.skipTools === false) {
@ -315,14 +317,14 @@ export function testChat(
arguments: '{"name":"Nate"}',
name: "say_hello",
},
id: "tool_call_1",
id: "toolcall1", // mistral requires alphanumeric length of 9
type: "function",
},
],
},
{
role: "tool",
tool_call_id: "tool_call_1",
tool_call_id: "toolcall1",
content: "Nate was greeted",
},
],