Merge branch 'main' into audit-command-line-flags

This commit is contained in:
Tomasz Stefaniak 2025-08-05 23:30:08 -07:00
commit da655bede9
17 changed files with 2586 additions and 99 deletions

87
.github/workflows/beta-release.yml vendored Normal file
View file

@ -0,0 +1,87 @@
name: Beta Release
on:
schedule:
# Run every day at 9am UTC
- cron: "0 9 * * *"
workflow_dispatch:
# Allow manual triggering
permissions:
contents: write
issues: write
pull-requests: write
jobs:
beta-release:
name: Beta Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Install dependencies
run: npm ci
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Get current version
id: get_version
run: |
# Get the latest version from package.json or npm registry
CURRENT_VERSION=$(node -p "require('./package.json').version")
if [[ "$CURRENT_VERSION" == "0.0.0-dev" ]]; then
# If it's dev version, get latest from npm registry
LATEST_VERSION=$(npm view @continuedev/cli version --silent 2>/dev/null || echo "0.0.0")
echo "Using latest npm version: $LATEST_VERSION"
CURRENT_VERSION=$LATEST_VERSION
fi
# Create beta version with current date
DATE_SUFFIX=$(date -u +%Y%m%d)
BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}"
echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT
- name: Update package.json for beta
run: |
# Update version in package.json
npm version ${{ steps.get_version.outputs.beta_version }} --no-git-tag-version
- name: Build
run: npm run build
- name: Publish beta to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm publish --tag beta
echo "Published beta version: ${{ steps.get_version.outputs.beta_version }}"
- name: Create beta release on GitHub
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Create a git tag for the beta
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "v${{ steps.get_version.outputs.beta_version }}"
git push origin "v${{ steps.get_version.outputs.beta_version }}"
# Create GitHub release
gh release create "v${{ steps.get_version.outputs.beta_version }}" \
--title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \
--notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \
--prerelease

View file

@ -1,11 +1,11 @@
name: Release
name: Legacy Release (Deprecated)
on:
# schedule:
# # Run every day at 9am UTC
# - cron: "0 9 * * *"
workflow_dispatch:
# Allow manual triggering
# Keep manual triggering for emergencies
permissions:
contents: write

137
.github/workflows/stable-release.yml vendored Normal file
View file

@ -0,0 +1,137 @@
name: Stable Release
on:
schedule:
# Run every Monday at 10am UTC (1 hour after beta release)
- cron: "0 10 * * 1"
workflow_dispatch:
inputs:
beta_version:
description: 'Specific beta version to promote (e.g., 1.2.3-beta.20240115)'
required: false
type: string
permissions:
contents: write
issues: write
pull-requests: write
jobs:
stable-release:
name: Stable Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Find beta version to promote
id: find_beta
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [[ -n "${{ inputs.beta_version }}" ]]; then
# Manual input provided
BETA_VERSION="${{ inputs.beta_version }}"
echo "Using manually specified beta version: $BETA_VERSION"
else
# Find beta version that's at least 7 days old
SEVEN_DAYS_AGO=$(date -u -d '7 days ago' +%Y%m%d)
echo "Looking for beta versions from $SEVEN_DAYS_AGO or earlier"
# Get all beta versions from npm
BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' | sort -V)
CANDIDATE_VERSION=""
for version in $BETA_VERSIONS; do
# Extract date from beta version (format: x.y.z-beta.YYYYMMDD)
if [[ $version =~ -beta\.([0-9]{8}) ]]; then
BETA_DATE="${BASH_REMATCH[1]}"
if [[ $BETA_DATE -le $SEVEN_DAYS_AGO ]]; then
CANDIDATE_VERSION=$version
fi
fi
done
if [[ -z "$CANDIDATE_VERSION" ]]; then
echo "No beta version found that is at least 7 days old"
exit 1
fi
BETA_VERSION=$CANDIDATE_VERSION
echo "Selected beta version for promotion: $BETA_VERSION"
fi
# Extract base version (remove -beta.YYYYMMDD suffix)
STABLE_VERSION=$(echo "$BETA_VERSION" | sed 's/-beta\.[0-9]\{8\}//')
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT
- name: Download and verify beta package
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
# Download the specific beta version
npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }}
# Extract and verify the package
PACKAGE_FILE=$(ls continuedev-cli-*.tgz)
tar -xzf "$PACKAGE_FILE"
echo "Beta package contents verified"
ls -la package/
- name: Update package.json for stable release
run: |
# Copy the beta package contents
cp -r package/* .
# Update version to stable (remove beta suffix)
npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version
- name: Build (verification step)
run: npm run build
- name: Run tests (verification step)
run: npm test
- name: Publish stable to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm publish --tag latest
echo "Published stable version: ${{ steps.find_beta.outputs.stable_version }}"
- name: Create stable release on GitHub
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Create a git tag for the stable release
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "v${{ steps.find_beta.outputs.stable_version }}"
git push origin "v${{ steps.find_beta.outputs.stable_version }}"
# Create GitHub release
gh release create "v${{ steps.find_beta.outputs.stable_version }}" \
--title "Stable Release v${{ steps.find_beta.outputs.stable_version }}" \
--notes "Stable release promoted from tested beta version ${{ steps.find_beta.outputs.beta_version }}. This version has been thoroughly tested in beta for at least 7 days." \
--latest
- name: Update GitHub release notes
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Mark the original beta release as superseded
gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \
--notes "This beta version has been promoted to stable as v${{ steps.find_beta.outputs.stable_version }}."

150
README-sentry.md Normal file
View file

@ -0,0 +1,150 @@
# Sentry Integration
This document explains how to configure and use Sentry for error monitoring and performance tracking in the Continue CLI.
## Setup
### Environment Variables
To enable Sentry, set the following environment variables:
```bash
# Required: Sentry DSN (Data Source Name)
export SENTRY_DSN="https://your-dsn@sentry.io/project-id"
# Optional: Environment name (defaults to NODE_ENV or "development")
export SENTRY_ENVIRONMENT="production"
# Optional: Sample rates (defaults to 1.0 for all)
export SENTRY_SAMPLE_RATE="1.0" # Error sampling rate
export SENTRY_PROFILES_SAMPLE_RATE="1.0" # Performance profiling rate
export SENTRY_TRACES_SAMPLE_RATE="1.0" # Performance tracing rate
```
### Disabling Sentry
To completely disable Sentry, you can:
1. **Not set `SENTRY_DSN`** - Sentry will be disabled automatically
2. **Explicitly disable**: `export SENTRY_ENABLED="false"`
## What Gets Monitored
### Automatic Error Capture
- **Unhandled Promise Rejections**: Global promise rejections are captured
- **Uncaught Exceptions**: Global uncaught exceptions are captured
- **Logger Errors**: All `logger.error()` and `logger.warn()` calls are sent to Sentry
- **Command Errors**: Errors in chat commands and other CLI operations
### Performance Monitoring
- **Profiling**: CPU and memory profiling data (when enabled)
- **Performance Traces**: Request timing and performance metrics
### Context Information
Sentry automatically includes:
- Application version
- Environment (development/production)
- Node.js version and platform
- Error stack traces
- Custom context for each error (when available)
## Usage in Code
The Sentry service is automatically initialized and available throughout the application. You can use it directly:
```typescript
import { sentryService } from "./sentry.js";
// Capture an exception with context
try {
// some code
} catch (error) {
sentryService.captureException(error, {
context: "my_operation",
userId: "12345",
});
}
// Capture a message
sentryService.captureMessage("Something important happened", "info", {
customData: "value",
});
// Set user context
sentryService.setUser({
id: "user123",
email: "user@example.com",
});
// Add breadcrumbs for debugging
sentryService.addBreadcrumb({
message: "User performed action",
category: "user",
level: "info",
data: { action: "click_button" },
});
```
## Testing the Integration
### Test Error Capture
```bash
# Set up Sentry (replace with your actual DSN)
export SENTRY_DSN="https://your-dsn@sentry.io/project-id"
# Run the CLI and trigger an error to test
cn "this should work normally"
```
### Test Disabled State
```bash
# Disable Sentry
export SENTRY_ENABLED="false"
# or simply don't set SENTRY_DSN
# Run the CLI - no Sentry data should be sent
cn "this will run without Sentry"
```
### Verify Configuration
The application logs will show when Sentry is initialized:
```
DEBUG: Sentry initialized { environment: 'development', release: '0.0.0-dev' }
```
If Sentry is disabled, you won't see this log message.
## Privacy and Security
- Sentry only captures error information and performance metrics
- No user prompts or sensitive data are sent to Sentry by default
- All data transmission is encrypted (HTTPS)
- You control what environment and sampling rates to use
## Troubleshooting
### Sentry Not Working
1. **Check DSN**: Ensure `SENTRY_DSN` is set correctly
2. **Check Network**: Ensure your environment can reach sentry.io
3. **Check Logs**: Look for Sentry initialization messages in debug logs
4. **Check Sampling**: Ensure sample rates are > 0
### Too Much Data
1. **Reduce Sample Rates**: Lower `SENTRY_SAMPLE_RATE`, `SENTRY_PROFILES_SAMPLE_RATE`, or `SENTRY_TRACES_SAMPLE_RATE`
2. **Use Environment Filtering**: Set different configurations for dev vs prod
### No Data in Sentry Dashboard
1. **Check Project Settings**: Ensure the DSN matches your Sentry project
2. **Check Filters**: Verify no filters are blocking your data
3. **Wait**: It can take a few minutes for data to appear in Sentry

1716
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -48,6 +48,8 @@
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"@sentry/node": "^9.43.0",
"@sentry/profiling-node": "^9.43.0",
"@types/express": "^5.0.3",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",

View file

@ -13,6 +13,8 @@ import { processCommandFlags } from "../flags/flagProcessor.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
// initializeWithOnboarding is now handled internally by initializeServices
// import { initializeWithOnboarding } from "../onboarding.js";
import { sentryService } from "../sentry.js";
import { initializeServices } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
@ -300,7 +302,13 @@ async function processMessage(
// Save session after each successful response
saveSession(chatHistory);
} catch (e: any) {
logger.error(`\n${chalk.red(`Error: ${formatError(e)}`)}`);
const error = e instanceof Error ? e : new Error(String(e));
logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
sentryService.captureException(error, {
context: "chat_response",
isHeadless,
chatHistoryLength: chatHistory.length,
});
if (!isHeadless) {
logger.info(
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
@ -394,7 +402,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
if (!options.headless) {
// Process flags for TUI mode
const { permissionOverrides } = processCommandFlags(options);
// Initialize services with onboarding handled internally
const initResult = await initializeServices({
configPath: options.config,
@ -412,15 +420,27 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
console.log(CONTINUE_ASCII_ART);
// Start TUI with skipOnboarding since we already handled it
await startTUIChat(prompt, options.resume, options.config, options.rule, permissionOverrides, true);
await startTUIChat(
prompt,
options.resume,
options.config,
options.rule,
permissionOverrides,
true
);
return;
}
// Run headless mode
await runHeadlessMode(prompt, options);
} catch (error: any) {
const err = error instanceof Error ? error : new Error(String(error));
// Use headless-aware error logging to ensure fatal errors are shown in headless mode
logging.error(chalk.red(`Fatal error: ${formatError(error)}`));
logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
sentryService.captureException(err, {
context: "chat_command_fatal",
headless: options.headless,
});
process.exit(1);
} finally {
// Stop active time tracking

View file

@ -313,7 +313,15 @@ function isFilePath(configPath: string): boolean {
return (
configPath.startsWith(".") ||
configPath.startsWith("/") ||
configPath.startsWith("~")
configPath.startsWith("~") ||
// Windows absolute paths (C:\, D:\, etc.)
/^[A-Za-z]:[/\\]/.test(configPath) ||
// UNC paths (\\server\share)
configPath.startsWith("\\\\") ||
// Contains file extension
configPath.includes(".yaml") ||
configPath.includes(".yml") ||
configPath.includes(".json")
);
}

View file

@ -8,7 +8,11 @@ import { logout } from "./commands/logout.js";
import { remoteTest } from "./commands/remote-test.js";
import { remote } from "./commands/remote.js";
import { serve } from "./commands/serve.js";
import { validateFlags, handleValidationErrors } from "./flags/flagValidator.js";
import {
validateFlags,
handleValidationErrors,
} from "./flags/flagValidator.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
import { logger } from "./util/logger.js";
@ -18,11 +22,18 @@ import { getVersion } from "./version.js";
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled Rejection at:", { promise, reason });
sentryService.captureException(
reason instanceof Error ? reason : new Error(String(reason)),
{
promise: String(promise),
}
);
// Don't exit the process, just log the error
});
process.on("uncaughtException", (error) => {
logger.error("Uncaught Exception:", error);
sentryService.captureException(error);
// Don't exit the process, just log the error
});
@ -67,7 +78,7 @@ addCommonOptions(program)
ask: options.ask,
exclude: options.exclude,
isRootCommand: true,
commandName: 'cn'
commandName: "cn",
});
if (!validation.isValid) {
@ -105,7 +116,9 @@ addCommonOptions(program)
// In headless mode, ensure we have a prompt
if (options.print && !prompt) {
console.error("Error: A prompt is required when using the -p/--print flag.\n");
console.error(
"Error: A prompt is required when using the -p/--print flag.\n"
);
console.error("Usage examples:");
console.error(' cn -p "please review my current git diff"');
console.error(' echo "hello" | cn -p');
@ -190,5 +203,19 @@ try {
program.parse();
} catch (error) {
console.error(error);
sentryService.captureException(
error instanceof Error ? error : new Error(String(error))
);
process.exit(1);
}
}
// Graceful shutdown - flush Sentry data
process.on("SIGINT", async () => {
await sentryService.flush();
process.exit(0);
});
process.on("SIGTERM", async () => {
await sentryService.flush();
process.exit(0);
});

155
src/onboarding.test.ts Normal file
View file

@ -0,0 +1,155 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { describe, expect, test, beforeEach, afterEach } from 'vitest';
import type { AuthConfig } from './auth/workos.js';
import { runNormalFlow } from './onboarding.js';
describe('onboarding config flag handling', () => {
let tempDir: string;
let mockAuthConfig: AuthConfig;
beforeEach(() => {
// Create a temporary directory for test config files
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'continue-test-'));
// Create a minimal auth config for testing
mockAuthConfig = {
userId: 'test-user',
userEmail: 'test@example.com',
accessToken: 'test-token',
refreshToken: 'test-refresh',
expiresAt: Date.now() + 3600000,
organizationId: 'test-org',
};
});
afterEach(() => {
// Clean up temporary directory
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
test('should fail loudly when --config points to non-existent file', async () => {
const configPath = path.join(tempDir, 'non-existent.yaml');
// Verify the file doesn't exist
expect(fs.existsSync(configPath)).toBe(false);
// Should throw an error that mentions both the path and the failure
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/Failed to load config from ".*non-existent\.yaml": .*ENOENT/
);
});
test('should fail loudly when --config points to malformed YAML file', async () => {
const configPath = path.join(tempDir, 'malformed.yaml');
// Create a malformed YAML file
fs.writeFileSync(configPath, `
name: "Test Config"
models:
- name: "GPT-4"
provider: "openai"
invalid_yaml_syntax: [unclosed array
`);
// Verify the file exists
expect(fs.existsSync(configPath)).toBe(true);
// Should throw an error mentioning the path and failure to load
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/Failed to load config from ".*malformed\.yaml": .+/
);
});
test('should fail loudly when --config points to file with missing required fields', async () => {
const configPath = path.join(tempDir, 'incomplete.yaml');
// Create a config file missing required fields
fs.writeFileSync(configPath, `
name: "Incomplete Config"
# Missing models array and other required fields
`);
// Verify the file exists
expect(fs.existsSync(configPath)).toBe(true);
// Should throw with our specific error format and include path
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/^Failed to load config from ".*": .+/
);
});
test('should handle different config path formats with proper error messages', async () => {
const testPaths = [
'./non-existent.yaml',
'/absolute/path/config.yaml',
'../relative/config.yaml',
'simple-name.yaml'
];
for (const configPath of testPaths) {
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/Failed to load config from ".*": .+/
);
}
});
test('should handle empty string config path', async () => {
// Empty string should be treated differently from undefined
// Note: empty string triggers onboarding flow, but should still fail in our error format
await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow();
});
test('should not fall back to default config when explicit config fails', async () => {
const configPath = path.join(tempDir, 'bad-config.yaml');
// Create a bad config file
fs.writeFileSync(configPath, 'invalid: yaml: content: [');
const promise = runNormalFlow(mockAuthConfig, configPath);
await expect(promise).rejects.toThrow();
try {
await promise;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
// CRITICAL: Must have our specific error format from the fix
expect(message).toMatch(/^Failed to load config from ".*": .+/);
// Error should be about the specific config file we provided
expect(message).toContain(configPath);
// Should NOT mention falling back to default config (this was the bug!)
expect(message).not.toContain('~/.continue/config.yaml');
expect(message).not.toContain('default config');
expect(message).not.toContain('fallback');
}
});
test('demonstrates the fix: explicit config failure vs no config provided', async () => {
const badConfigPath = path.join(tempDir, 'bad.yaml');
fs.writeFileSync(badConfigPath, 'invalid yaml [');
// Case 1: Explicit --config that fails should throw our specific error
await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow(
/^Failed to load config from "/
);
// Case 2: No explicit config should follow different logic
try {
await runNormalFlow(mockAuthConfig, undefined);
// If it succeeds, that's fine - the point is it's different behavior
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
// This should NOT have our "Failed to load config from" prefix
expect(errorMessage).not.toMatch(/^Failed to load config from "/);
}
});
});

View file

@ -12,7 +12,10 @@ import { processRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { MCPService } from "./mcp.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import {
isValidAnthropicApiKey,
getApiKeyValidationError,
} from "./util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
@ -48,10 +51,10 @@ export async function createOrUpdateConfig(apiKey: string): Promise<void> {
fs.mkdirSync(configDir, { recursive: true });
}
const existingContent = fs.existsSync(CONFIG_PATH)
const existingContent = fs.existsSync(CONFIG_PATH)
? fs.readFileSync(CONFIG_PATH, "utf8")
: "";
const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
fs.writeFileSync(CONFIG_PATH, updatedContent);
}
@ -67,11 +70,12 @@ export async function runOnboardingFlow(
}
// Step 2: Check if we're in a test/CI environment - if so, skip interactive prompts
const isTestEnv = process.env.NODE_ENV === "test" ||
process.env.CI === "true" ||
process.env.VITEST === "true" ||
process.env.GITHUB_ACTIONS === "true" ||
!process.stdin.isTTY;
const isTestEnv =
process.env.NODE_ENV === "test" ||
process.env.CI === "true" ||
process.env.VITEST === "true" ||
process.env.GITHUB_ACTIONS === "true" ||
!process.stdin.isTTY;
if (isTestEnv) {
// In test/CI environment, return a minimal working configuration
@ -125,12 +129,21 @@ export async function runNormalFlow(
): Promise<OnboardingResult> {
// Step 1: Check if --config flag is provided
if (configPath) {
const result = await initialize(authConfig, configPath);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
try {
const result = await initialize(authConfig, configPath);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch (error) {
// If user explicitly provided --config flag, fail loudly instead of falling back
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to load config from "${configPath}": ${errorMessage}`
);
}
return { ...result, wasOnboarded: false };
}
// Step 2: If user is logged in, look for first assistant in selected org
@ -269,4 +282,4 @@ export async function initializeWithOnboarding(
}
return result;
}
}

163
src/sentry.ts Normal file
View file

@ -0,0 +1,163 @@
import * as Sentry from "@sentry/node";
import { nodeProfilingIntegration } from "@sentry/profiling-node";
import { logger } from "./util/logger.js";
import { getVersion } from "./version.js";
interface SentryConfig {
enabled: boolean;
dsn?: string;
environment: string;
release: string;
sampleRate: number;
profilesSampleRate: number;
tracesSampleRate: number;
}
class SentryService {
private config: SentryConfig;
private initialized = false;
constructor() {
this.config = this.loadConfig();
if (this.config.enabled) {
this.initialize();
}
}
private loadConfig(): SentryConfig {
const enabled =
process.env.SENTRY_ENABLED !== "false" && !!process.env.SENTRY_DSN;
return {
enabled,
dsn: process.env.SENTRY_DSN,
environment:
process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV || "development",
release: getVersion(),
sampleRate: parseFloat(process.env.SENTRY_SAMPLE_RATE || "1.0"),
profilesSampleRate: parseFloat(
process.env.SENTRY_PROFILES_SAMPLE_RATE || "1.0"
),
tracesSampleRate: parseFloat(
process.env.SENTRY_TRACES_SAMPLE_RATE || "1.0"
),
};
}
private initialize() {
if (this.initialized || !this.config.dsn) {
return;
}
try {
Sentry.init({
dsn: this.config.dsn,
environment: this.config.environment,
release: this.config.release,
sampleRate: this.config.sampleRate,
profilesSampleRate: this.config.profilesSampleRate,
tracesSampleRate: this.config.tracesSampleRate,
integrations: [nodeProfilingIntegration()],
beforeSend(event) {
// Filter out certain error types if needed
if (event.exception?.values?.[0]?.type === "AbortError") {
return null;
}
return event;
},
});
this.initialized = true;
logger.debug("Sentry initialized", {
environment: this.config.environment,
release: this.config.release,
});
} catch (error) {
logger.error("Failed to initialize Sentry", error);
}
}
public isEnabled(): boolean {
return this.config.enabled && this.initialized;
}
public captureException(error: Error, context?: Record<string, any>) {
if (!this.isEnabled()) return;
Sentry.withScope((scope) => {
if (context) {
Object.entries(context).forEach(([key, value]) => {
scope.setContext(key, value);
});
}
Sentry.captureException(error);
});
}
public captureMessage(
message: string,
level: "info" | "warning" | "error" | "debug" | "fatal" = "info",
context?: Record<string, any>
) {
if (!this.isEnabled()) return;
Sentry.withScope((scope) => {
if (context) {
Object.entries(context).forEach(([key, value]) => {
scope.setContext(key, value);
});
}
Sentry.captureMessage(message, level);
});
}
public setUser(user: { id?: string; email?: string; username?: string }) {
if (!this.isEnabled()) return;
Sentry.setUser(user);
}
public setTag(key: string, value: string) {
if (!this.isEnabled()) return;
Sentry.setTag(key, value);
}
public setContext(key: string, context: Record<string, any>) {
if (!this.isEnabled()) return;
Sentry.setContext(key, context);
}
public addBreadcrumb(breadcrumb: {
message: string;
category?: string;
level?: "fatal" | "error" | "warning" | "log" | "info" | "debug";
data?: Record<string, any>;
}) {
if (!this.isEnabled()) return;
Sentry.addBreadcrumb(breadcrumb);
}
public startSpan(name: string, op?: string) {
if (!this.isEnabled()) return null;
return Sentry.startSpan({ name, op }, (span) => span);
}
public async flush(timeout = 2000): Promise<boolean> {
if (!this.isEnabled()) return true;
return await Sentry.flush(timeout);
}
public async close(timeout = 2000): Promise<boolean> {
if (!this.isEnabled()) return true;
return await Sentry.close(timeout);
}
}
export const sentryService = new SentryService();

View file

@ -128,11 +128,10 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
// Use current config path from ConfigService state if available (for reloads),
// otherwise use initial options.configPath (for first initialization)
// IMPORTANT: Always prefer explicit --config flag over saved state
const currentState = configService.getState();
let configPath =
currentState.configPath !== undefined
? currentState.configPath
: options.configPath;
let configPath = options.configPath ||
(currentState.configPath !== undefined ? currentState.configPath : undefined);
// If no config path is available, check for saved config URI in auth config
if (!configPath) {

View file

@ -1,14 +1,6 @@
// Import after mocking
import { AssistantUnrolled } from "@continuedev/config-yaml";
import {
afterEach,
beforeEach,
describe,
expect,
vi,
test,
} from "vitest";
import { afterEach, beforeEach, describe, expect, vi, test } from "vitest";
import * as workos from "./auth/workos.js";
import * as commands from "./commands/commands.js";
@ -39,10 +31,12 @@ describe("handleSlashCommands", () => {
// Since the mock already returns the required value, we don't need to set it
// Just verify it returns what we expect
expect(commands.getAllSlashCommands(mockAssistant)).toEqual(expect.arrayContaining([
expect.objectContaining({ name: "help" }),
expect.objectContaining({ name: "login" }),
]));
expect(commands.getAllSlashCommands(mockAssistant)).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "help" }),
expect.objectContaining({ name: "login" }),
])
);
});
afterEach(() => {
@ -114,7 +108,9 @@ describe("handleSlashCommands", () => {
{ id: "org2", name: "Organization 2" },
];
(services.auth.getAvailableOrganizations as any).mockResolvedValue(mockOrgs);
(services.auth.getAvailableOrganizations as any).mockResolvedValue(
mockOrgs
);
const result = await handleSlashCommands("/org list", mockAssistant);
@ -164,9 +160,9 @@ describe("handleSlashCommands", () => {
const result = await handleSlashCommands("/help", mockAssistant);
expect(result).not.toBeNull();
expect(result?.output).toContain("Available commands:");
expect(result?.output).toContain("/help - Show help");
expect(result?.output).toContain("/login - Authenticate");
expect(result?.output).toContain("Slash commands:");
expect(result?.output).toContain("/help: Show help");
expect(result?.output).toContain("/login: Authenticate");
});
test.skip("logout command should exit", async () => {

View file

@ -29,8 +29,8 @@ export async function handleSlashCommands(
case "help":
const allCommands = getAllSlashCommands(assistant);
const helpMessage = [
"Available commands:",
...allCommands.map((cmd) => `/${cmd.name} - ${cmd.description}`),
chalk.cyan("Slash commands:"),
...allCommands.map((cmd) => `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`),
].join("\n");
posthogService.capture("useSlashCommand", {
name: "help",

View file

@ -105,13 +105,13 @@ const UserInput: React.FC<UserInputProps> = ({
const allCommands = getSlashCommands();
const exactMatch = allCommands.find((cmd) => cmd.name === afterSlash);
// Hide selector if we have an exact match and there's more content after the cursor
// Hide selector if we have an exact match and there's a space after cursor
if (exactMatch) {
const restOfText = text.slice(cursor);
// If there's a space immediately after cursor, or we're at end of line/text, hide selector
// Only hide if there's a space or newline immediately after cursor
// Don't hide just because we're at the end - user might want to see the suggestion
if (
restOfText.startsWith(" ") ||
restOfText === "" ||
restOfText.startsWith("\n")
) {
setShowSlashCommands(false);

View file

@ -1,93 +1,97 @@
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from "crypto";
import fs from "fs";
import os from "os";
import path from "path";
import chalk from 'chalk';
import winston from 'winston';
import chalk from "chalk";
import winston from "winston";
import { sentryService } from "../sentry.js";
const { combine, timestamp, printf, errors } = winston.format;
// Generate a unique session ID for this process
const SESSION_ID = crypto.randomBytes(4).toString('hex');
const SESSION_ID = crypto.randomBytes(4).toString("hex");
// Get log directory
function getLogDir(): string {
const homeDir = os.homedir();
const logDir = path.join(homeDir, '.continue', 'logs');
const logDir = path.join(homeDir, ".continue", "logs");
// Create directory if it doesn't exist
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
return logDir;
}
// Get current log file path
function getLogFilePath(): string {
const logDir = getLogDir();
return path.join(logDir, 'cn.log');
return path.join(logDir, "cn.log");
}
// Simple replacer for JSON.stringify to handle common issues
function createReplacer() {
const seen = new Set();
return (key: string, value: any) => {
// Handle circular references
if (typeof value === 'object' && value !== null) {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return '[Circular]';
return "[Circular]";
}
seen.add(value);
}
// Handle functions
if (typeof value === 'function') {
return '[Function]';
if (typeof value === "function") {
return "[Function]";
}
// Handle undefined (which JSON.stringify skips by default)
if (value === undefined) {
return '[undefined]';
return "[undefined]";
}
return value;
};
}
// Custom format for log output
const logFormat = printf(({ level, message, timestamp, stack, ...metadata }) => {
let msg = `${timestamp} [${SESSION_ID}] [${level}]: ${message}`;
// Add metadata if present
if (Object.keys(metadata).length > 0) {
try {
msg += ` ${JSON.stringify(metadata, createReplacer())}`;
} catch (err) {
// Fallback if stringify still fails somehow
msg += ` [Failed to stringify metadata: ${err}]`;
const logFormat = printf(
({ level, message, timestamp, stack, ...metadata }) => {
let msg = `${timestamp} [${SESSION_ID}] [${level}]: ${message}`;
// Add metadata if present
if (Object.keys(metadata).length > 0) {
try {
msg += ` ${JSON.stringify(metadata, createReplacer())}`;
} catch (err) {
// Fallback if stringify still fails somehow
msg += ` [Failed to stringify metadata: ${err}]`;
}
}
// Add stack trace for errors
if (stack) {
msg += `\n${stack}`;
}
return msg;
}
// Add stack trace for errors
if (stack) {
msg += `\n${stack}`;
}
return msg;
});
);
// Track headless mode
let isHeadlessMode = false;
// Create the logger instance
// Create the winstonLogger instance
const winstonLogger = winston.createLogger({
level: 'info', // Default level
level: "info", // Default level
format: combine(
errors({ stack: true }),
timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
timestamp({ format: "YYYY-MM-DD HH:mm:ss.SSS" }),
logFormat
),
transports: [
@ -110,20 +114,34 @@ export function configureHeadlessMode(headless: boolean) {
isHeadlessMode = headless;
}
// Export logger methods
// Export winstonLogger methods
export const logger = {
debug: (message: string, meta?: any) => winstonLogger.debug(message, meta),
info: (message: string, meta?: any) => winstonLogger.info(message, meta),
warn: (message: string, meta?: any) => winstonLogger.warn(message, meta),
warn: (message: string, meta?: any) => {
winstonLogger.warn(message, meta);
sentryService.captureMessage(message, "warning", meta);
},
error: (message: string, error?: Error | any, meta?: any) => {
if (error instanceof Error) {
winstonLogger.error(message, { ...meta, error: error.message, stack: error.stack });
winstonLogger.error(message, {
...meta,
error: error.message,
stack: error.stack,
});
sentryService.captureException(error, { message, ...meta });
} else if (error) {
winstonLogger.error(message, { ...meta, error });
sentryService.captureMessage(
`${message}: ${String(error)}`,
"error",
meta
);
} else {
winstonLogger.error(message, meta);
sentryService.captureMessage(message, "error", meta);
}
// In headless mode, also output to stderr
if (isHeadlessMode) {
if (error instanceof Error) {
@ -139,4 +157,4 @@ export const logger = {
configureHeadlessMode,
getLogPath: getLogFilePath,
getSessionId: () => SESSION_ID,
};
};