chore: remove all PostHog and Sentry telemetry collection

Strip all PostHog and Sentry telemetry from the codebase so the product
works without phoning home. OpenTelemetry (CLI, user-configured) is kept.

- Delete core telemetry files (posthog.ts, SentryLogger, TeamAnalytics, TokensBatchingService)
- Remove all capture/report calls from 80+ caller files across core, GUI, VSCode, CLI, IntelliJ
- Remove posthog-node, posthog-js, @sentry/* dependencies from all package.json files
- Remove PostHog/Sentry plugins and build scripts
- Create IdeInfoService.ts and uniqueId.ts for non-telemetry request headers
- Remove PostHog API key from docs config
- Remove posthog from analytics provider config schema

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Patrick Erichsen 2026-03-19 15:15:26 -07:00
parent 571f7af442
commit 32639c5c11
106 changed files with 112 additions and 4147 deletions

2
.idea/gradle.xml generated
View file

@ -5,7 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="gradleHome" value="/usr/local/Cellar/gradle/8.13/libexec" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

View file

@ -50,10 +50,9 @@
"mac-ca": "^2.0.3",
"ncp": "^2.0.0",
"node-fetch": "^3.3.2",
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"tar": "^7.5.10",
"undici": "^7.16.0",
"undici": "^7.24.0",
"uuid": "^9.0.1",
"vectordb": "0.4.20",
"win-ca": "^3.5.1"

View file

@ -1,6 +1,6 @@
import { DataLogger } from "../../data/log";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { getUriFileExtension } from "../../util/uri";
import { AutocompleteOutcome } from "./types";
@ -122,11 +122,5 @@ export class AutocompleteLoggingService {
profileType: restOfOutcome.profileType,
};
outcome.enabledStaticContextualization
? void Telemetry.capture("autocomplete", {
...toLog,
enabledStaticContextualization: true,
})
: void Telemetry.capture("autocomplete", toLog);
}
}

View file

@ -19,7 +19,7 @@ import {
import { getControlPlaneEnv } from "../control-plane/env.js";
import { PolicySingleton } from "../control-plane/PolicySingleton.js";
import { Logger } from "../util/Logger.js";
import { Telemetry } from "../util/posthog.js";
import {
getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
@ -543,25 +543,6 @@ export class ConfigHandler {
this.initter.emit("init");
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
const isSignedIn = await this.controlPlaneClient.isSignedIn();
const profileDescription = this.currentProfile.profileDescription;
const telemetryData: Record<string, any> = {
duration,
reason,
totalConfigLoads: this.totalConfigReloads,
configLoadInterrupted,
profileType: profileDescription.profileType,
isPersonalOrg: this.currentOrg?.id === this.PERSONAL_ORG_DESC.id,
errorCount: errors.length,
isSignedIn,
};
void Telemetry.capture("config_reload", telemetryData);
if (errors.length) {
Logger.error("Errors loading config: ", errors);
}
@ -592,6 +573,7 @@ export class ConfigHandler {
async getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
await this.isInitialized;
if (!this.currentProfile) {
return {
config: undefined,

View file

@ -99,7 +99,6 @@ export class ProfileLifecycleManager {
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
// Capture config loading system failures to Sentry
Logger.error(e, {
context: "profile_config_loading",
});

View file

@ -26,7 +26,6 @@ import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsP
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { initSlashCommand } from "../../promptFiles/initPrompt";
import { getConfigDependentToolDefinitions } from "../../tools";
@ -35,8 +34,7 @@ import { getMCPToolName } from "../../tools/mcpToolName";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { SentryLogger } from "../../util/sentry/SentryLogger";
import { IdeInfoService } from "../../util/IdeInfoService";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
@ -379,31 +377,12 @@ export default async function doLoadConfig(options: {
newConfig.disableIndexing = true;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
newConfig.allowAnonymousTelemetry ?? true,
await ide.getUniqueId(),
// Setup IdeInfoService
IdeInfoService.setup(
uniqueId,
ideInfo,
);
// Setup Sentry logger with same telemetry settings
// TODO: Remove Continue team member check once Sentry is ready for all users
let userEmail: string | undefined;
try {
// Access the session info to get user email for Continue team member check
const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
userEmail = sessionInfo?.account?.id;
} catch (error) {
// Ignore errors getting session info, will default to no Sentry
}
await SentryLogger.setup(
newConfig.allowAnonymousTelemetry ?? false,
await ide.getUniqueId(),
ideInfo,
userEmail,
);
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();
@ -426,21 +405,6 @@ export default async function doLoadConfig(options: {
workOsAccessToken,
};
if (newConfig.analytics) {
// FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in
// controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls
// where undefined is :workspaceId
// await TeamAnalytics.setup(
// newConfig.analytics,
// uniqueId,
// ideInfo.extensionVersion,
// controlPlaneClient,
// controlPlaneProxyInfo,
// );
} else {
await TeamAnalytics.shutdown();
}
newConfig = await injectControlPlaneProxyInfo(
newConfig,
controlPlaneProxyInfo,

View file

@ -61,12 +61,6 @@ vi.mock("../../tools/callTool", () => ({
vi.mock("../../tools/mcpToolName", () => ({
getMCPToolName: vi.fn(),
}));
vi.mock("../../util/posthog", () => ({
Telemetry: { setup: vi.fn() },
}));
vi.mock("../../util/sentry/SentryLogger", () => ({
SentryLogger: { setup: vi.fn() },
}));
vi.mock("../../util/tts", () => ({
TTS: { setup: vi.fn() },
}));
@ -89,9 +83,6 @@ vi.mock("../../control-plane/env", () => ({
vi.mock("../../control-plane/PolicySingleton", () => ({
PolicySingleton: { getInstance: () => ({ policy: null }) },
}));
vi.mock("../../control-plane/TeamAnalytics", () => ({
TeamAnalytics: { setup: vi.fn(), shutdown: vi.fn() },
}));
vi.mock("../../promptFiles/initPrompt", () => ({
initSlashCommand: { name: "init", description: "init" },
}));

View file

@ -1,7 +1,6 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ModelDescription, SerializedContinueConfig } from "../";
import { Telemetry } from "../util/posthog";
/**
* Validates a SerializedContinueConfig object to ensure all properties are correctly formed.
@ -158,14 +157,6 @@ export function validateConfig(config: SerializedContinueConfig) {
});
if (errors.length > 0) {
void Telemetry.capture(
"configValidationError",
{
errors,
},
true,
);
return errors;
}

View file

@ -1,5 +1,5 @@
import { Chunk } from "../../../";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -24,7 +24,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
await Telemetry.captureError("no_reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
@ -34,7 +33,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings:", error);
}
@ -43,10 +41,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
await Telemetry.captureError(
"no_reranker_recently_edited_retrieval",
error,
);
console.error("Error retrieving recently edited files:", error);
}
@ -60,7 +54,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,6 +1,6 @@
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -21,7 +21,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
@ -31,7 +30,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
await Telemetry.captureError("reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings chunks:", error);
}
@ -40,7 +38,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_recently_edited_retrieval", error);
console.error("Error retrieving recently edited files chunks:", error);
}
@ -54,7 +51,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,13 +1,13 @@
import { constants, getTimestamp } from "../../deploy/constants.js";
import { Telemetry } from "../../util/posthog.js";
import { IdeInfoService } from "../../util/IdeInfoService.js";
export async function getHeaders() {
return {
key: constants.c,
timestamp: getTimestamp(),
v: "1",
extensionVersion: Telemetry.ideInfo?.extensionVersion ?? "0.0.0",
os: Telemetry.os ?? "Unknown",
uniqueId: Telemetry.uniqueId ?? "None",
extensionVersion: IdeInfoService.ideInfo?.extensionVersion ?? "0.0.0",
os: IdeInfoService.os ?? "Unknown",
uniqueId: IdeInfoService.uniqueId ?? "None",
};
}

View file

@ -1,77 +0,0 @@
import os from "node:os";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./analytics/IAnalyticsProvider.js";
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
import { ControlPlaneClient } from "./client.js";
import { AnalyticsConfig } from "../index.js";
function createAnalyticsProvider(
config: AnalyticsConfig,
): IAnalyticsProvider | undefined {
// @ts-ignore
switch (config.provider) {
case "posthog":
return new PostHogAnalyticsProvider();
case "logstash":
return new LogStashAnalyticsProvider();
case "continue-proxy":
return new ContinueProxyAnalyticsProvider();
default:
return undefined;
}
}
export class TeamAnalytics {
static provider: IAnalyticsProvider | undefined = undefined;
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static extensionVersion: string | undefined = undefined;
static async capture(event: string, properties: { [key: string]: any }) {
void TeamAnalytics.provider?.capture(event, {
...properties,
os: TeamAnalytics.os,
extensionVersion: TeamAnalytics.extensionVersion,
});
}
static async setup(
config: AnalyticsConfig,
uniqueId: string,
extensionVersion: string,
controlPlaneClient: ControlPlaneClient,
controlPlaneProxyInfo: ControlPlaneProxyInfo,
) {
TeamAnalytics.uniqueId = uniqueId;
TeamAnalytics.os = os.platform();
TeamAnalytics.extensionVersion = extensionVersion;
TeamAnalytics.provider = createAnalyticsProvider(config);
await TeamAnalytics.provider?.setup(
config,
uniqueId,
controlPlaneProxyInfo,
);
if (config.provider === "continue-proxy") {
(
TeamAnalytics.provider as ContinueProxyAnalyticsProvider
).controlPlaneClient = controlPlaneClient;
}
}
static async shutdown() {
if (TeamAnalytics.provider) {
await TeamAnalytics.provider.shutdown();
TeamAnalytics.provider = undefined;
TeamAnalytics.os = undefined;
TeamAnalytics.extensionVersion = undefined;
TeamAnalytics.uniqueId = "NOT_UNIQUE";
}
}
}

View file

@ -1,54 +0,0 @@
import { Analytics } from "@continuedev/config-types";
import fetch from "node-fetch";
import { ControlPlaneClient } from "../client.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class ContinueProxyAnalyticsProvider
implements IAnalyticsProvider
{
uniqueId?: string;
controlPlaneProxyInfo?: ControlPlaneProxyInfo;
controlPlaneClient?: ControlPlaneClient;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
if (!this.controlPlaneProxyInfo?.workspaceId) {
return;
}
const url = new URL(
`proxy/analytics/${this.controlPlaneProxyInfo.workspaceId}/capture`,
this.controlPlaneProxyInfo?.controlPlaneProxyUrl,
).toString();
void fetch(url, {
method: "POST",
body: JSON.stringify({
event,
properties,
uniqueId: this.uniqueId,
}),
headers: {
Authorization: `Bearer ${await this.controlPlaneClient?.getAccessToken()}`,
},
});
}
async setup(
config: Analytics,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
this.uniqueId = uniqueId;
this.controlPlaneProxyInfo = controlPlaneProxyInfo;
}
async shutdown(): Promise<void> {}
}

View file

@ -1,52 +0,0 @@
import net from "node:net";
import { Analytics } from "@continuedev/config-types";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
private host?: string;
private port?: number;
private uniqueId?: string;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
if (this.host === undefined || this.port === undefined) {
console.warn("LogStashAnalyticsProvider not set up yet.");
}
const payload = {
event,
properties,
uniqueId: this.uniqueId,
};
const client = new net.Socket();
client.connect(this.port!, this.host!, () => {
client.write(JSON.stringify(payload));
client.end();
});
}
async setup(
config: Analytics,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
if (!config.url) {
console.warn("LogStashAnalyticsProvider is missing a URL");
return;
}
const url = new URL(config.url);
this.host = url.hostname;
this.port = parseInt(url.port);
this.uniqueId = uniqueId;
}
async shutdown(): Promise<void> {}
}

View file

@ -1,45 +0,0 @@
import { Analytics } from "@continuedev/config-types";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
client?: any;
uniqueId?: string;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
this.client?.capture({
distinctId: this.uniqueId,
event,
properties,
});
}
async setup(
config: Analytics,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
if (!config || !config.clientKey || !config.url) {
this.client = undefined;
} else {
try {
this.uniqueId = uniqueId;
const { PostHog } = await import("posthog-node");
this.client = new PostHog(config.clientKey, {
host: config.url,
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
}
async shutdown(): Promise<void> {}
}

View file

@ -26,7 +26,7 @@ import { compactConversation } from "./util/conversationCompaction";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
@ -293,11 +293,6 @@ export class Core {
// Note, VsCode's in-process messenger doesn't do anything with this
// It will only show for jetbrains
this.messenger.onError((message, err) => {
void Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
// just to prevent duplicate error messages in jetbrains (same logic in webview protocol)
if (
["llm/streamChat", "chatDescriber/describe"].includes(
@ -1470,10 +1465,6 @@ export class Core {
}
try {
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
const items = await provider.getContextItems(query, {
config,
llm,
@ -1489,14 +1480,6 @@ export class Core {
isInAgentMode: msg.data.isInAgentMode,
});
void Telemetry.capture(
"useContextProvider",
{
name: provider.description.title,
},
true,
);
return items.map((item) => {
const id: ContextItemId = {
providerTitle: provider.description.title,

View file

@ -23,7 +23,7 @@ import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRule
import { gptEditPrompt } from "../llm/templates/edit";
import { defaultApplyPrompt } from "../llm/templates/edit/gpt";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
function constructEditPrompt(
@ -83,15 +83,6 @@ export async function* streamDiffLines(
): AsyncGenerator<DiffLine> {
const { type, prefix, highlighted, suffix, input, language } = options;
void Telemetry.capture(
"inlineEdit",
{
model: llm.model,
provider: llm.providerName,
},
true,
);
// Strip common indentation for the LLM, then add back after generation
let oldLines =
highlighted.length > 0

View file

@ -127,7 +127,6 @@ export class CodebaseIndexer {
try {
await fs.unlink(sqliteFilepath);
} catch (error) {
// Capture indexer system failures to Sentry
Logger.error(error, {
filepath: sqliteFilepath,
});
@ -137,7 +136,6 @@ export class CodebaseIndexer {
try {
await fs.rm(lanceDbFolder, { recursive: true, force: true });
} catch (error) {
// Capture indexer system failures to Sentry
Logger.error(error, {
folderPath: lanceDbFolder,
});

View file

@ -25,7 +25,6 @@ import {
getDocsSqlitePath,
getLanceDbPath,
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import {
ArticleWithChunks,
@ -588,10 +587,6 @@ export default class DocsService {
}
}
void Telemetry.capture("docs_pages_crawled", {
count: processedPages,
});
// Chunk pages based on which crawler was used
const articles: ArticleWithChunks[] = [];
const chunks: Chunk[] = [];
@ -1006,7 +1001,6 @@ export default class DocsService {
}
} else {
addedDocs.push(doc);
void Telemetry.capture("add_docs_config", { url: doc.startUrl });
}
}

View file

@ -31,12 +31,12 @@ import {
ToolOverride,
Usage,
} from "../index.js";
import { isAbortError } from "../util/isAbortError.js";
import { isLemonadeInstalled } from "../util/lemonadeHelper.js";
import { Logger } from "../util/Logger.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
import { TokensBatchingService } from "../util/TokensBatchingService.js";
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
import {
@ -360,13 +360,6 @@ export abstract class BaseLLM implements ILLM {
let generatedTokens = this.countTokens(completion);
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
TokensBatchingService.getInstance().addTokens(
model,
this.providerName,
promptTokens,
generatedTokens,
);
void DevDataSqliteDb.logTokensGenerated(
model,
this.providerName,
@ -394,7 +387,7 @@ export abstract class BaseLLM implements ILLM {
});
return "success";
} else {
if (error === "cancel" || error?.name?.includes("AbortError")) {
if (isAbortError(error)) {
interaction?.logItem({
kind: "cancel",
promptTokens,
@ -485,7 +478,6 @@ export abstract class BaseLLM implements ILLM {
return resp;
} catch (e: any) {
// Capture all fetch errors to Sentry for monitoring
Logger.error(e, {
context: "llm_fetch",
url: String(input),
@ -502,7 +494,7 @@ export abstract class BaseLLM implements ILLM {
`HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
);
} else {
if (e.name !== "AbortError") {
if (!isAbortError(e)) {
// Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
@ -680,7 +672,6 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture FIM (Fill-in-the-Middle) completion failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_fim",
model: completionOptions.model,
@ -811,7 +802,6 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture streaming completion failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_complete",
model: completionOptions.model,
@ -920,7 +910,6 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture completion failures to Sentry
Logger.error(e as Error, {
context: "llm_complete",
model: completionOptions.model,
@ -1305,7 +1294,6 @@ export abstract class BaseLLM implements ILLM {
usage,
);
} catch (e) {
// Capture chat streaming failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_chat",
model: completionOptions.model,

View file

@ -6,7 +6,7 @@ import {
} from "@continuedev/config-yaml";
import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js";
import { Telemetry } from "../../../util/posthog.js";
import { IdeInfoService } from "../../../util/IdeInfoService.js";
import OpenAI from "../OpenAI.js";
import type { Chunk, LLMOptions } from "../../../index.js";
@ -100,13 +100,13 @@ class ContinueProxy extends OpenAI {
protected _getHeaders() {
const headers: any = super._getHeaders();
headers["x-continue-unique-id"] = Telemetry.uniqueId;
headers["x-continue-unique-id"] = IdeInfoService.uniqueId;
headers["user-agent"] = this._getUserAgent();
return headers;
}
private _getUserAgent(): string {
const ideInfo = Telemetry.ideInfo;
const ideInfo = IdeInfoService.ideInfo;
const extensionVersion = ideInfo?.extensionVersion ?? "unknown";
const ideName = ideInfo?.name ?? "unknown";
const ideType = ideInfo?.ideType ?? "unknown";

View file

@ -4,7 +4,7 @@ import { ConfigHandler } from "../config/ConfigHandler";
import { usesCreditsBasedApiKey } from "../config/usesFreeTrialApiKey";
import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import { IMessenger, Message } from "../protocol/messenger";
import { Telemetry } from "../util/posthog";
import { TTS } from "../util/tts";
import { isOutOfStarterCredits } from "./utils/starterCredits";
@ -136,15 +136,6 @@ export async function* llmStreamChat(
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
void checkForOutOfStarterCredits(configHandler, messenger);
if (!next.done) {

View file

@ -1,9 +1,7 @@
import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { getControlPlaneEnvSync } from "../control-plane/env";
import { DataLogger } from "../data/log";
import { Telemetry } from "../util/posthog";
import { NextEditOutcome } from "./types";
export class NextEditLoggingService {
@ -217,39 +215,5 @@ export class NextEditLoggingService {
});
// const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
if (outcome.requestId && outcome.accepted !== undefined) {
void this.logAcceptReject(outcome.requestId, outcome.accepted);
}
void Telemetry.capture("nextEditOutcome", outcome, true);
}
private async logAcceptReject(
requestId: string,
accepted: boolean,
): Promise<void> {
try {
if (!Telemetry.client) {
return;
}
const controlPlaneEnv = getControlPlaneEnvSync("production");
const resp = await fetchwithRequestOptions(
new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
requestId,
accepted,
}),
},
);
const text = await resp.text();
console.debug("Feedback: ", text);
} catch (error: any) {
console.debug(`Error capturing feedback: ${error.message}`);
}
}
}

View file

@ -8,10 +8,9 @@
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
"tsc:check": "tsc -p ./ --noEmit",
"build": "tsc -p ./tsconfig.npm.json",
"build:npm": "npm run build && npm run sentry:sourcemaps",
"build:npm": "npm run build",
"lint": "eslint . --ext ts",
"lint:fix": "eslint . --ext ts --fix",
"sentry:sourcemaps": "sentry-cli sourcemaps inject --org continue-xd --project continue ./dist && sentry-cli sourcemaps upload --org continue-xd --project continue ./dist"
"lint:fix": "eslint . --ext ts --fix"
},
"type": "module",
"author": "Continue Dev, Inc",
@ -68,11 +67,6 @@
"@modelcontextprotocol/sdk": "^1.25.2",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@sentry/cli": "^2.50.2",
"@sentry/core": "^9.43.0",
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^5.0.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -109,7 +103,6 @@
"partial-json": "^0.1.7",
"pg": "^8.11.3",
"plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^24.15.0",
"puppeteer-chromium-resolver": "^23.0.0",
"quick-lru": "^7.0.0",

View file

@ -90,13 +90,11 @@ export class InProcessMessenger<
try {
return listener(msg);
} catch (error) {
// Capture message handling errors to Sentry
Logger.error(error, {
messageType: String(messageType),
messageId: msg.messageId,
});
// Re-throw the original error
throw error;
}
}
@ -141,13 +139,11 @@ export class InProcessMessenger<
});
return response;
} catch (error) {
// Capture message handling errors to Sentry
Logger.error(error, {
messageType: String(messageType),
messageId,
});
// Re-throw the original error
throw error;
}
}
@ -178,13 +174,11 @@ export class InProcessMessenger<
});
return Promise.resolve(response);
} catch (error) {
// Capture message handling errors to Sentry
Logger.error(error, {
messageType: String(messageType),
messageId,
});
// Re-throw the original error
throw error;
}
}

View file

@ -0,0 +1,15 @@
import { IdeInfo } from "../index.js";
export class IdeInfoService {
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
static setup(
uniqueId: string,
ideInfo: IdeInfo,
): void {
IdeInfoService.uniqueId = uniqueId;
IdeInfoService.ideInfo = ideInfo;
}
}

View file

@ -1,5 +1,4 @@
import winston from "winston";
import { captureException } from "./sentry/SentryLogger";
class LoggerClass {
private static instance: LoggerClass;
@ -41,10 +40,6 @@ class LoggerClass {
return LoggerClass.instance;
}
private shouldSendToSentry(): boolean {
return process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "e2e";
}
public log(message: string, meta?: any): void {
this.winston.info(message, meta);
}
@ -76,10 +71,6 @@ class LoggerClass {
}
this.winston.error(errorMessage, context);
if (this.shouldSendToSentry() && error instanceof Error) {
captureException(error, context);
}
}
}

View file

@ -1,106 +0,0 @@
import { Telemetry } from "./posthog.js";
interface TokenBatch {
model: string;
provider: string;
count: number;
totalPromptTokens: number;
totalGeneratedTokens: number;
lastEventTime: number;
}
export class TokensBatchingService {
private static instance: TokensBatchingService;
private batches = new Map<string, TokenBatch>();
private flushTimer: NodeJS.Timeout | null = null;
private readonly BATCH_SIZE_LIMIT = 25;
private readonly FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
static getInstance(): TokensBatchingService {
if (!TokensBatchingService.instance) {
TokensBatchingService.instance = new TokensBatchingService();
}
return TokensBatchingService.instance;
}
private constructor() {
this.startFlushTimer();
}
addTokens(
model: string,
provider: string,
promptTokens: number,
generatedTokens: number,
): void {
const key = `${provider}:${model}`;
if (!this.batches.has(key)) {
this.batches.set(key, {
model,
provider,
count: 0,
totalPromptTokens: 0,
totalGeneratedTokens: 0,
lastEventTime: Date.now(),
});
}
const batch = this.batches.get(key)!;
batch.count++;
batch.totalPromptTokens += promptTokens;
batch.totalGeneratedTokens += generatedTokens;
batch.lastEventTime = Date.now();
// Flush if batch is full
if (batch.count >= this.BATCH_SIZE_LIMIT) {
this.flushBatch(key, batch);
}
}
private flushBatch(key: string, batch: TokenBatch): void {
if (batch.count === 0) return;
void Telemetry.capture(
"tokens_generated_batch",
{
model: batch.model,
provider: batch.provider,
eventCount: batch.count,
totalPromptTokens: batch.totalPromptTokens,
totalGeneratedTokens: batch.totalGeneratedTokens,
avgPromptTokens: Math.round(batch.totalPromptTokens / batch.count),
avgGeneratedTokens: Math.round(
batch.totalGeneratedTokens / batch.count,
),
},
true,
);
this.batches.delete(key);
}
private startFlushTimer(): void {
this.flushTimer = setInterval(() => {
this.flushAllBatches();
}, this.FLUSH_INTERVAL_MS);
// Allow the process to exit if this timer is the only thing keeping it alive
// This prevents test hangs and allows graceful shutdown
this.flushTimer.unref();
}
private flushAllBatches(): void {
for (const [key, batch] of this.batches.entries()) {
this.flushBatch(key, batch);
}
}
shutdown(): void {
if (this.flushTimer) {
clearInterval(this.flushTimer);
this.flushTimer = null;
}
this.flushAllBatches();
}
}

View file

@ -1,155 +0,0 @@
import os from "node:os";
import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
import { IdeInfo } from "../index.js";
import type { PostHog as PostHogType } from "posthog-node";
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
import { TokensBatchingService } from "./TokensBatchingService.js";
export enum PosthogFeatureFlag {
AutocompleteTimeout = "autocomplete-timeout",
RecentlyVisitedRangesNumSurroundingLines = "recently-visited-ranges-num-surrounding-lines",
}
export const EXPERIMENTS: {
[key in PosthogFeatureFlag]: {
[key: string]: { value: any };
};
} = {
[PosthogFeatureFlag.AutocompleteTimeout]: {
control: { value: 150 },
"250": { value: 250 },
"350": { value: 350 },
"450": { value: 450 },
},
[PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: {
control: { value: null },
"5": { value: 5 },
"10": { value: 10 },
"15": { value: 15 },
"20": { value: 20 },
},
};
export class Telemetry {
// Set to undefined whenever telemetry is disabled
static client: PostHogType | undefined = undefined;
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
/**
* Convenience method for capturing errors in a single event
*/
static async captureError(errorName: string, error: unknown) {
if (!(error instanceof Error)) {
return;
}
await Telemetry.capture(
"extension_error_caught",
{
errorName,
message: error.message,
stack: extractMinimalStackTraceInfo(error.stack),
},
false,
);
}
static async capture(
event: string,
properties: { [key: string]: any },
sendToTeam: boolean = false,
isExtensionActivationError: boolean = false,
) {
try {
const augmentedProperties = {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.ideInfo?.extensionVersion,
ideName: Telemetry.ideInfo?.name,
ideType: Telemetry.ideInfo?.ideType,
};
const payload = {
distinctId: Telemetry.uniqueId,
event,
properties: augmentedProperties,
sendFeatureFlags: true,
};
// In cases where an extremely early fatal error occurs, we may not have initialized yet
if (isExtensionActivationError && !Telemetry.client) {
const client = await Telemetry.getTelemetryClient();
client?.capture(payload);
return;
}
if (process.env.NODE_ENV === "test") {
return;
}
Telemetry.client?.capture(payload);
if (sendToTeam) {
void TeamAnalytics.capture(event, properties);
}
} catch (e) {
console.error(`Failed to capture event: ${e}`);
}
}
static shutdownPosthogClient() {
TokensBatchingService.getInstance().shutdown();
Telemetry.client?.shutdown();
}
static async getTelemetryClient(): Promise<PostHogType | undefined> {
try {
const { PostHog } = await import("posthog-node");
return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
host: "https://app.posthog.com",
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) {
Telemetry.uniqueId = uniqueId;
Telemetry.os = os.platform();
Telemetry.ideInfo = ideInfo;
if (!allow || process.env.NODE_ENV === "test") {
Telemetry.client = undefined;
} else if (!Telemetry.client) {
Telemetry.client = await Telemetry.getTelemetryClient();
}
}
private static featureValueCache: Record<string, any> = {};
static async getFeatureFlag(flag: PosthogFeatureFlag) {
const value = Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId);
Telemetry.featureValueCache[flag] = value;
return value;
}
static async getValueForFeatureFlag(flag: PosthogFeatureFlag) {
try {
if (Telemetry.featureValueCache[flag]) {
return Telemetry.featureValueCache[flag];
}
const userGroup = await Telemetry.getFeatureFlag(flag);
if (typeof userGroup === "string") {
return EXPERIMENTS[flag][userGroup].value;
}
return undefined;
} catch {
return undefined;
}
}
}

View file

@ -1,886 +0,0 @@
import { IdeInfo } from "../../index.js";
import {
SentryLogger,
captureException,
captureLog,
createSpan,
initializeSentry,
} from "./SentryLogger";
import { anonymizeSentryEvent } from "./anonymization";
describe("SentryLogger Integration Tests", () => {
const mockIdeInfo: IdeInfo = {
extensionVersion: "1.0.0",
name: "vscode",
ideType: "vscode",
version: "1.0.0",
remoteName: "local",
isPrerelease: false,
};
beforeEach(() => {
// Reset SentryLogger state before each test
SentryLogger.client = undefined;
SentryLogger.scope = undefined;
SentryLogger.allowTelemetry = false;
SentryLogger.uniqueId = "NOT_UNIQUE";
SentryLogger.ideInfo = undefined;
});
afterEach(() => {
// Clean up after each test
SentryLogger.shutdownSentryClient();
});
describe("Telemetry Toggle Behavior", () => {
it("should not initialize when telemetry is disabled", async () => {
await SentryLogger.setup(
false,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.allowTelemetry).toBe(false);
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
expect(SentryLogger.uniqueId).toBe("test-id");
expect(SentryLogger.ideInfo).toBe(mockIdeInfo);
});
it("should not initialize in test environment even when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "test";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
// In the updated implementation, the Continue team member check is used instead of NODE_ENV check
// so we're not setting allowTelemetry to false just because we're in test environment anymore
expect(SentryLogger.allowTelemetry).toBe(true);
// But client and scope should still be initialized
expect(SentryLogger.client).toBeDefined();
expect(SentryLogger.scope).toBeDefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should initialize when telemetry is enabled in non-test environment", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.allowTelemetry).toBe(true);
expect(SentryLogger.uniqueId).toBe("test-id");
expect(SentryLogger.ideInfo).toBe(mockIdeInfo);
expect(SentryLogger.client).toBeDefined();
expect(SentryLogger.scope).toBeDefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle telemetry being disabled after being enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Enable telemetry first
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.allowTelemetry).toBe(true);
expect(SentryLogger.client).toBeDefined();
// Then disable it
await SentryLogger.setup(false, "test-id-2", mockIdeInfo);
expect(SentryLogger.allowTelemetry).toBe(false);
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should not reinitialize if client already exists", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// First setup
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const firstClient = SentryLogger.client;
const firstScope = SentryLogger.scope;
// Second setup should not change the client
await SentryLogger.setup(
true,
"test-id-2",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.client).toBe(firstClient);
expect(SentryLogger.scope).toBe(firstScope);
expect(SentryLogger.uniqueId).toBe("test-id-2"); // ID should update
expect(SentryLogger.ideInfo).toBe(mockIdeInfo); // Info should update
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("Lazy Initialization", () => {
it("should initialize when accessing lazyClient if conditions are met", () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Set up conditions for lazy initialization
SentryLogger.allowTelemetry = true;
SentryLogger.ideInfo = mockIdeInfo;
// Access lazy client should trigger initialization
const client = SentryLogger.lazyClient;
expect(client).toBeDefined();
expect(SentryLogger.client).toBe(client);
expect(SentryLogger.scope).toBeDefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should not initialize if telemetry is disabled", () => {
SentryLogger.allowTelemetry = false;
SentryLogger.ideInfo = mockIdeInfo;
const client = SentryLogger.lazyClient;
expect(client).toBeUndefined();
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
});
it("should not initialize if ideInfo is missing", () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
SentryLogger.allowTelemetry = true;
SentryLogger.ideInfo = undefined;
const client = SentryLogger.lazyClient;
expect(client).toBeUndefined();
expect(SentryLogger.client).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("Shutdown Behavior", () => {
it("should properly shutdown when client exists", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Setup Sentry first
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.client).toBeDefined();
// Shutdown should clean up
SentryLogger.shutdownSentryClient();
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle shutdown gracefully when client is undefined", () => {
expect(() => SentryLogger.shutdownSentryClient()).not.toThrow();
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
});
});
});
describe("Sentry Utility Functions", () => {
const mockIdeInfo: IdeInfo = {
extensionVersion: "1.0.0",
name: "vscode",
ideType: "vscode",
version: "1.0.0",
remoteName: "local",
isPrerelease: false,
};
beforeEach(() => {
// Reset SentryLogger state
SentryLogger.client = undefined;
SentryLogger.scope = undefined;
SentryLogger.allowTelemetry = false;
});
afterEach(() => {
SentryLogger.shutdownSentryClient();
});
describe("initializeSentry", () => {
it("should return undefined when telemetry is disabled", () => {
const result = initializeSentry();
expect(result.client).toBeUndefined();
expect(result.scope).toBeUndefined();
});
it("should return client and scope when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const result = initializeSentry();
expect(result.client).toBeDefined();
expect(result.scope).toBeDefined();
expect(result.client).toBe(SentryLogger.client);
expect(result.scope).toBe(SentryLogger.scope);
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("createSpan", () => {
it("should execute callback normally when telemetry is disabled", () => {
const callback = jest.fn().mockReturnValue("test-result");
const result = createSpan("test.operation", "test span", callback);
expect(result).toBe("test-result");
expect(callback).toHaveBeenCalledTimes(1);
});
it("should execute callback with span when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const callback = jest.fn().mockReturnValue("test-result");
const result = createSpan("test.operation", "test span", callback);
expect(result).toBe("test-result");
expect(callback).toHaveBeenCalledTimes(1);
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle async callbacks", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const asyncCallback = jest.fn().mockResolvedValue("async-result");
const result = await createSpan(
"test.operation",
"test span",
asyncCallback,
);
expect(result).toBe("async-result");
expect(asyncCallback).toHaveBeenCalledTimes(1);
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("captureException", () => {
it("should not throw when telemetry is disabled", () => {
const error = new Error("test error");
expect(() => captureException(error)).not.toThrow();
expect(() => captureException(error, { context: "test" })).not.toThrow();
});
it("should not throw when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const error = new Error("test error");
expect(() => captureException(error)).not.toThrow();
expect(() => captureException(error, { context: "test" })).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle malformed context gracefully", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const error = new Error("test error");
expect(() => captureException(error, null as any)).not.toThrow();
expect(() => captureException(error, undefined)).not.toThrow();
expect(() => captureException(error, { circular: {} })).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("captureLog", () => {
it("should not throw when telemetry is disabled", () => {
expect(() => captureLog("test message")).not.toThrow();
expect(() =>
captureLog("test message", "info", { context: "test" }),
).not.toThrow();
});
it("should not throw when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(() => captureLog("test message")).not.toThrow();
expect(() =>
captureLog("test message", "error", { context: "test" }),
).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle malformed context gracefully", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(() =>
captureLog("test message", "info", null as any),
).not.toThrow();
expect(() =>
captureLog("test message", "warning", undefined),
).not.toThrow();
expect(() =>
captureLog("test message", "error", { circular: {} }),
).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("Integration Tests", () => {
it("should maintain consistent state across utility functions", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Start with telemetry disabled
expect(initializeSentry().client).toBeUndefined();
const callback = jest.fn().mockReturnValue("result");
createSpan("test", "test", callback);
expect(callback).toHaveBeenCalled();
// Enable telemetry
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
// Now utility functions should work with Sentry
const sentryResult = initializeSentry();
expect(sentryResult.client).toBeDefined();
expect(sentryResult.scope).toBeDefined();
// Functions should work without throwing
const callback2 = jest.fn().mockReturnValue("result2");
const spanResult = createSpan("test2", "test2", callback2);
expect(spanResult).toBe("result2");
expect(callback2).toHaveBeenCalled();
const error = new Error("test error");
expect(() => captureException(error, { test: "context" })).not.toThrow();
expect(() =>
captureLog("test log message", "info", { test: "context" }),
).not.toThrow();
// Disable telemetry again
await SentryLogger.setup(
false,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(initializeSentry().client).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
});
});
describe("Sentry Data Anonymization Tests", () => {
describe("anonymizeSentryEvent", () => {
it("should anonymize user file paths in stack traces", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename: "/Users/john/workspace/my-project/src/app.js",
abs_path: "/Users/john/workspace/my-project/src/app.js",
function: "myFunction",
lineno: 42,
vars: { secret: "password123" },
pre_context: ["const secret = 'password123'"],
post_context: ["console.log(secret)"],
context_line: "throw new Error('test')",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.pre_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.post_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
).toBe("<code>");
});
it("should anonymize all absolute file paths equally", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename: "/Users/dev/continue/core/util/sentry.js",
abs_path: "/Users/dev/continue/core/util/sentry.js",
function: "captureException",
lineno: 42,
vars: { secret: "password123" },
pre_context: ["const secret = 'password123'"],
post_context: ["console.log(secret)"],
context_line: "throw new Error('test')",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.pre_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.post_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
).toBe("<code>");
});
it("should preserve node_modules package names for debugging", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename:
"/Users/dev/project/node_modules/@sentry/node/index.js",
abs_path:
"/Users/dev/project/node_modules/@sentry/node/index.js",
function: "init",
lineno: 123,
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("node_modules/@sentry/<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
});
it("should hash user IDs", () => {
const event: any = {
user: {
id: "real-machine-id-12345",
username: "john.doe",
email: "john@example.com",
ip_address: "192.168.1.100",
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result?.user?.id).not.toBe("real-machine-id-12345");
expect(result?.user?.id).toMatch(/^[a-f0-9]{8}$/); // Should be 8-char hash
expect(result?.user?.username).toBeUndefined();
expect(result?.user?.email).toBeUndefined();
expect(result?.user?.ip_address).toBeUndefined();
});
it("should preserve breadcrumbs unchanged", () => {
const event: any = {
breadcrumbs: [
{
message:
"File opened: /Users/john/Documents/secret-project/config.js",
category: "file",
data: {
filename: "/Users/john/Documents/secret-project/config.js",
action: "open",
},
},
{
message: "Error in module initialization",
category: "error",
data: {
module: "auth",
error: "Connection failed",
},
},
],
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// Breadcrumbs are preserved as-is in our minimalist approach
expect(result?.breadcrumbs?.[0]?.message).toBe(
"File opened: /Users/john/Documents/secret-project/config.js",
);
expect(result?.breadcrumbs?.[0]?.data?.filename).toBe(
"/Users/john/Documents/secret-project/config.js",
);
expect(result?.breadcrumbs?.[0]?.data?.action).toBe("open");
expect(result?.breadcrumbs?.[1]?.message).toBe(
"Error in module initialization",
);
expect(result?.breadcrumbs?.[1]?.data?.module).toBe("auth");
expect(result?.breadcrumbs?.[1]?.data?.error).toBe("Connection failed");
});
it("should preserve tags unchanged", () => {
const event: any = {
tags: {
username: "john.doe",
user_id: "12345",
workspace: "/Users/john/workspace",
project_path: "/path/to/project",
environment: "production",
version: "1.2.3",
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// Tags are preserved as-is in our minimalist approach
expect(result?.tags?.username).toBe("john.doe");
expect(result?.tags?.user_id).toBe("12345");
expect(result?.tags?.workspace).toBe("/Users/john/workspace");
expect(result?.tags?.project_path).toBe("/path/to/project");
expect(result?.tags?.environment).toBe("production");
expect(result?.tags?.version).toBe("1.2.3");
});
it("should preserve extra data unchanged", () => {
const event: any = {
extra: {
path: "/Users/john/secret-project",
filename: "config.js",
directory: "/home/user/workspace",
workspace: "/Users/john/workspace",
user: "john.doe",
home: "/Users/john",
config_file: "/some/long/path/to/config.json",
error_code: 500,
timestamp: "2023-01-01T00:00:00Z",
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// Extra data is preserved as-is in our minimalist approach
expect(result?.extra?.path).toBe("/Users/john/secret-project");
expect(result?.extra?.filename).toBe("config.js");
expect(result?.extra?.directory).toBe("/home/user/workspace");
expect(result?.extra?.workspace).toBe("/Users/john/workspace");
expect(result?.extra?.user).toBe("john.doe");
expect(result?.extra?.home).toBe("/Users/john");
expect(result?.extra?.config_file).toBe("/some/long/path/to/config.json");
expect(result?.extra?.error_code).toBe(500);
expect(result?.extra?.timestamp).toBe("2023-01-01T00:00:00Z");
});
it("should anonymize thread stack traces", () => {
const event: any = {
threads: {
values: [
{
id: "main",
name: "MainThread",
stacktrace: {
frames: [
{
filename: "/Users/john/workspace/app.js",
abs_path: "/Users/john/workspace/app.js",
function: "main",
lineno: 1,
vars: { apiKey: "secret-key-123" },
context_line: "const apiKey = 'secret-key-123'",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
).toBeUndefined();
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
).toBe("<code>");
});
it("should remove OS environment variables", () => {
const event: any = {
contexts: {
os: {
name: "macOS",
version: "12.6",
environment: {
HOME: "/Users/john",
USER: "john",
PATH: "/usr/local/bin:/usr/bin",
},
},
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result?.contexts?.os?.name).toBe("macOS");
expect(result?.contexts?.os?.version).toBe("12.6");
expect(result?.contexts?.os?.environment).toBeUndefined();
});
it("should handle events with no sensitive data", () => {
const event: any = {
message: "Simple error message",
level: "error",
timestamp: 1234567890,
tags: {
component: "auth",
level: "error",
},
extra: {
error_code: 404,
retry_count: 3,
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result?.message).toBe("Simple error message");
expect(result?.level).toBe("error");
expect(result?.timestamp).toBe(1234567890);
expect(result?.tags?.component).toBe("auth");
expect(result?.extra?.error_code).toBe(404);
});
it("should handle malformed events gracefully", () => {
const malformedEvent: any = {
exception: {
values: null,
},
user: null,
breadcrumbs: "not-an-array",
tags: null,
extra: null,
};
const result = anonymizeSentryEvent(malformedEvent);
expect(result).not.toBeNull();
});
it("should handle anonymization errors by returning null", () => {
// Create a circular reference that would cause JSON serialization issues
const circularEvent: any = {
message: "Test event",
};
circularEvent.circular = circularEvent;
// Mock the anonymization to throw an error
const originalConsoleError = console.error;
console.error = jest.fn();
const result = anonymizeSentryEvent(circularEvent);
// Should not throw, but should return null for safety
expect(result).not.toBeNull(); // Actually, our function might handle this case
console.error = originalConsoleError;
});
it("should anonymize all absolute paths regardless of format", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename:
"C:\\Users\\dev\\continue\\extensions\\vscode\\src\\extension.js",
abs_path:
"C:\\Users\\dev\\continue\\extensions\\vscode\\src\\extension.js",
},
{
filename: "/home/dev/continue/core/util/sentry.js",
abs_path: "/home/dev/continue/core/util/sentry.js",
},
{
filename: "relative/path/file.js",
abs_path: "/absolute/path/file.js",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// All absolute paths get anonymized equally
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[1]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[2]?.filename,
).toBe("relative/path/file.js"); // Relative path preserved
// All abs_path fields cleared
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[1]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[2]?.abs_path,
).toBe("");
});
});
});

View file

@ -1,263 +0,0 @@
import { Extras, type Integration, type Event } from "@sentry/core";
import * as Sentry from "@sentry/node";
import os from "node:os";
import { IdeInfo } from "../../index.js";
import { isContinueTeamMember } from "../isContinueTeamMember.js";
import { anonymizeSentryEvent } from "./anonymization.js";
import { SENTRY_DSN } from "./constants.js";
export class SentryLogger {
static client: Sentry.NodeClient | undefined = undefined;
static scope: Sentry.Scope | undefined = undefined;
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
static allowTelemetry: boolean = false;
private static initializeSentryClient(release: string): {
client: Sentry.NodeClient | undefined;
scope: Sentry.Scope | undefined;
} {
try {
// For shared environments like VSCode extensions, we need to avoid global state pollution
// Filter out integrations that use global state
// See https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/
// Filter integrations that use the global variable
const integrations = Sentry.getDefaultIntegrations({}).filter(
(defaultIntegration: Integration) => {
// Remove integrations that might interfere with shared environments
return ![
"OnUncaughtException",
"OnUnhandledRejection",
"ContextLines",
"LocalVariables",
].includes(defaultIntegration.name);
},
);
// Create client manually without polluting global state
const client = new Sentry.NodeClient({
dsn: SENTRY_DSN,
release,
environment: process.env.NODE_ENV,
transport: Sentry.makeNodeTransport,
stackParser: Sentry.defaultStackParser,
// For basic error tracking, a lower sample rate should be fine
sampleRate: 0.1,
tracesSampleRate: 0.1,
// Privacy-conscious default
sendDefaultPii: false,
// Strip sensitive data and add basic properties before sending events
beforeSend(event: Event) {
// First apply anonymization
const anonymizedEvent = anonymizeSentryEvent(event);
if (!anonymizedEvent) return null;
// Add basic properties similar to PostHog telemetry
if (!anonymizedEvent.tags) anonymizedEvent.tags = {};
if (!anonymizedEvent.extra) anonymizedEvent.extra = {};
// Add OS information
if (SentryLogger.os) {
anonymizedEvent.tags.os = SentryLogger.os;
}
// Add ideInfo properties spread out as top-level properties
if (SentryLogger.ideInfo) {
anonymizedEvent.tags.extensionVersion =
SentryLogger.ideInfo.extensionVersion;
anonymizedEvent.tags.ideName = SentryLogger.ideInfo.name;
anonymizedEvent.tags.ideType = SentryLogger.ideInfo.ideType;
anonymizedEvent.tags.ideVersion = SentryLogger.ideInfo.version;
anonymizedEvent.tags.remoteName = SentryLogger.ideInfo.remoteName;
anonymizedEvent.tags.isPrerelease =
SentryLogger.ideInfo.isPrerelease;
}
return anonymizedEvent;
},
// Use filtered integrations for Node.js/VSCode shared environment
integrations,
// Enable structured logging
_experiments: {
enableLogs: true,
},
});
// Create a new scope and set the client
const scope = new Sentry.Scope();
scope.setClient(client);
// Initialize the client after setting it on the scope
client.init();
return { client, scope };
} catch (error) {
console.error("Failed to initialize Sentry client:", error);
return { client: undefined, scope: undefined };
}
}
static async setup(
allowAnonymousTelemetry: boolean,
uniqueId: string,
ideInfo: IdeInfo,
userEmail?: string,
) {
// TODO: Remove Continue team member check once Sentry is ready for all users
SentryLogger.allowTelemetry =
allowAnonymousTelemetry && isContinueTeamMember(userEmail);
SentryLogger.uniqueId = uniqueId;
SentryLogger.ideInfo = ideInfo;
SentryLogger.os = os.platform();
if (!SentryLogger.allowTelemetry) {
SentryLogger.client = undefined;
SentryLogger.scope = undefined;
} else if (!SentryLogger.client) {
const { client, scope } = SentryLogger.initializeSentryClient(
ideInfo.extensionVersion,
);
SentryLogger.client = client;
SentryLogger.scope = scope;
}
}
private static ensureInitialized(): void {
if (!SentryLogger.allowTelemetry || SentryLogger.client) {
return;
}
if (SentryLogger.ideInfo) {
const { client, scope } = SentryLogger.initializeSentryClient(
SentryLogger.ideInfo.extensionVersion,
);
SentryLogger.client = client;
SentryLogger.scope = scope;
}
}
static get lazyClient(): Sentry.NodeClient | undefined {
SentryLogger.ensureInitialized();
return SentryLogger.client;
}
static get lazyScope(): Sentry.Scope | undefined {
SentryLogger.ensureInitialized();
return SentryLogger.scope;
}
static shutdownSentryClient() {
if (SentryLogger.client) {
void SentryLogger.client.close();
SentryLogger.client = undefined;
SentryLogger.scope = undefined;
}
}
}
/**
* Initialize Sentry for error tracking, performance monitoring, and structured logging.
* Returns the Sentry client and scope, or undefined objects if telemetry is disabled.
*/
export function initializeSentry(): {
client: Sentry.NodeClient | undefined;
scope: Sentry.Scope | undefined;
} {
return {
client: SentryLogger.lazyClient,
scope: SentryLogger.lazyScope,
};
}
// Export utility functions for using Sentry throughout the application
/**
* Create a custom span for performance monitoring
*
* @param operation The operation category (e.g., "http.client", "ui.click", "db.query")
* @param name A descriptive name for the span
* @param callback The function to execute within the span
* @returns The result of the callback function
*/
export function createSpan<T>(
operation: string,
name: string,
callback: () => T | Promise<T>,
): T | Promise<T> {
const client = SentryLogger.lazyClient;
if (!client) {
return callback();
}
// Use withScope from Sentry to isolate the span context
return Sentry.withScope((isolatedScope: Sentry.Scope) => {
isolatedScope.setClient(client);
return Sentry.startSpan(
{
op: operation,
name,
},
() => callback(),
);
});
}
/**
* Capture an exception and send it to Sentry
*
* @param error The error to capture
* @param context Additional context information
*/
export function captureException(error: Error, context?: Record<string, any>) {
const scope = SentryLogger.lazyScope;
if (!scope) {
return;
}
try {
// Add context to scope if provided
if (context) {
scope.setExtras(context);
}
// Use scope's captureException to avoid global state
scope.captureException(error);
} catch (e) {
console.error(`Failed to capture exception to Sentry: ${e}`);
}
}
/**
* Capture a structured log message and send it to Sentry
*
* @param message The log message
* @param level The severity level (default: 'info')
* @param context Additional context information
*/
export function captureLog(
message: string,
level: Sentry.SeverityLevel = "info",
context?: Extras,
) {
const scope = SentryLogger.lazyScope;
if (!scope) {
return;
}
try {
// Add context to scope if provided
if (context) {
scope.setExtras(context);
}
// Use scope's captureMessage to avoid global state
scope.captureMessage(message, level);
} catch (e) {
console.error(`Failed to capture log to Sentry: ${e}`);
}
}

View file

@ -1,174 +0,0 @@
import {
anonymizeFilePath,
anonymizeSentryEvent,
anonymizeStackTrace,
anonymizeUserInfo,
} from "./anonymization";
describe("Sentry Anonymization Utilities", () => {
describe("anonymizeFilePath", () => {
it("should anonymize absolute paths but preserve node_modules package names", () => {
expect(anonymizeFilePath("/Users/john/workspace/app.js")).toBe("<file>");
expect(anonymizeFilePath("/home/user/project/file.py")).toBe("<file>");
expect(anonymizeFilePath("C:\\Users\\john\\Documents\\code.go")).toBe(
"<file>",
);
expect(anonymizeFilePath("/project/node_modules/react/index.js")).toBe(
"node_modules/react/<file>",
);
});
it("should keep relative paths unchanged", () => {
expect(anonymizeFilePath("src/app.js")).toBe("src/app.js");
expect(anonymizeFilePath("./utils/helper.py")).toBe("./utils/helper.py");
expect(anonymizeFilePath("package/main.go")).toBe("package/main.go");
});
it("should handle empty or undefined paths", () => {
expect(anonymizeFilePath("")).toBe("");
expect(anonymizeFilePath(undefined as any)).toBe(undefined);
expect(anonymizeFilePath(null as any)).toBe(null);
});
});
describe("anonymizeStackTrace", () => {
it("should anonymize stack frame filenames", () => {
const frames = [
{
filename: "/Users/john/project/app.js",
abs_path: "/Users/john/project/app.js",
function: "myFunction",
lineno: 42,
vars: { secret: "password123" },
pre_context: ['const secret = "password123"'],
post_context: ["console.log(secret)"],
context_line: 'throw new Error("test")',
},
];
const result = anonymizeStackTrace(frames);
expect(result[0].filename).toBe("<file>");
expect(result[0].abs_path).toBe(""); // Always cleared like Rasa
expect(result[0].vars).toBeUndefined();
expect(result[0].pre_context).toBeUndefined();
expect(result[0].post_context).toBeUndefined();
expect(result[0].context_line).toBe("<code>");
expect(result[0].function).toBe("myFunction"); // Preserve function name
expect(result[0].lineno).toBe(42); // Preserve line number
});
it("should handle non-array input", () => {
expect(anonymizeStackTrace(null as any)).toBe(null);
expect(anonymizeStackTrace(undefined as any)).toBe(undefined);
expect(anonymizeStackTrace("not-array" as any)).toBe("not-array");
});
});
describe("anonymizeUserInfo", () => {
it("should hash user ID and remove other info", () => {
const user = {
id: "real-machine-id-12345",
username: "john.doe",
email: "john@example.com",
ip_address: "192.168.1.100",
};
const result = anonymizeUserInfo(user);
expect(result.id).not.toBe("real-machine-id-12345");
expect(result.id).toMatch(/^[a-f0-9]{8}$/); // 8-char hash
expect(result.username).toBeUndefined();
expect(result.email).toBeUndefined();
expect(result.ip_address).toBeUndefined();
});
it("should handle null/undefined user", () => {
expect(anonymizeUserInfo(null)).toBe(null);
expect(anonymizeUserInfo(undefined)).toBe(undefined);
});
});
describe("anonymizeSentryEvent (integration)", () => {
it("should anonymize events with user file paths", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename: "/Users/john/workspace/app.js",
abs_path: "/Users/john/workspace/app.js",
vars: { secret: "password" },
context_line: 'throw new Error("test")',
},
],
},
},
],
},
user: {
id: "machine-id-12345",
username: "john",
},
contexts: {
os: {
environment: { HOME: "/Users/john" },
},
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result.exception.values[0].stacktrace.frames[0].filename).toBe(
"<file>",
);
expect(result.exception.values[0].stacktrace.frames[0].abs_path).toBe("");
expect(
result.exception.values[0].stacktrace.frames[0].vars,
).toBeUndefined();
expect(result.exception.values[0].stacktrace.frames[0].context_line).toBe(
"<code>",
);
expect(result.user.id).toMatch(/^[a-f0-9]{8}$/);
expect(result.user.username).toBeUndefined();
expect(result.contexts.os.environment).toBeUndefined();
});
it("should handle malformed events gracefully", () => {
const malformedEvent: any = {
exception: {
values: null,
},
user: null,
breadcrumbs: "not-an-array",
tags: null,
extra: null,
};
const result = anonymizeSentryEvent(malformedEvent);
expect(result).not.toBeNull(); // Should not crash
});
it("should return null on anonymization errors", () => {
// Create a circular reference that would cause issues
const circularEvent: any = {
message: "Test event",
};
circularEvent.circular = circularEvent;
// Mock console.error to avoid noise in tests
const originalConsoleError = console.error;
console.error = jest.fn();
const result = anonymizeSentryEvent(circularEvent);
// Should handle gracefully without crashing
expect(result).not.toBeNull(); // Our implementation might handle this
console.error = originalConsoleError;
});
});
});

View file

@ -1,133 +0,0 @@
import * as Sentry from "@sentry/node";
import { type Event } from "@sentry/core";
/**
* Minimalist Sentry anonymization utilities
*/
// Browser-compatible hash function (avoids Node.js crypto dependency)
function simpleHash(input: string): string {
let hash = 0;
for (let i = 0; i < input.length; i++) {
const char = input.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash).toString(16).substring(0, 8);
}
/**
* Anonymize file paths - keep package names, remove user paths
*/
export function anonymizeFilePath(filePath: string): string {
if (!filePath) return filePath;
const normalized = filePath.replace(/\\/g, "/");
// Keep node_modules package names for debugging
if (normalized.includes("node_modules")) {
const match = normalized.match(/node_modules\/([^\/]+)/);
if (match) {
return `node_modules/${match[1]}/<file>`;
}
}
// Replace absolute paths with generic identifier
if (normalized.startsWith("/") || normalized.match(/^[A-Za-z]:/)) {
return "<file>";
}
return normalized;
}
/**
* Clean stack trace frames - remove sensitive data but keep the event
*/
export function anonymizeStackTrace(frames: any[]): any[] {
if (!Array.isArray(frames)) return frames;
return frames.map((frame) => ({
...frame,
filename: frame.filename
? anonymizeFilePath(frame.filename)
: frame.filename,
abs_path: "",
// Remove local variables and source code context
vars: undefined,
pre_context: undefined,
post_context: undefined,
context_line: frame.context_line ? "<code>" : frame.context_line,
}));
}
/**
* Anonymize user information - hash ID, remove PII
*/
export function anonymizeUserInfo(user: any): any {
if (!user) return user;
return {
id: user.id ? simpleHash(String(user.id)) : user.id,
username: undefined,
email: undefined,
ip_address: undefined,
};
}
/**
* Main anonymization function - minimalist approach like Rasa
*/
export function anonymizeSentryEvent(event: any): any | null {
try {
// Deep copy to avoid mutating the original event
const anonymized = structuredClone(event);
// Clean exception stack traces
if (anonymized.exception?.values) {
anonymized.exception.values = anonymized.exception.values.map(
(exception: any) => ({
...exception,
stacktrace: exception.stacktrace
? {
...exception.stacktrace,
frames: exception.stacktrace.frames
? anonymizeStackTrace(exception.stacktrace.frames)
: exception.stacktrace.frames,
}
: exception.stacktrace,
}),
);
}
// Clean thread stack traces
if (anonymized.threads?.values) {
anonymized.threads.values = anonymized.threads.values.map(
(thread: any) => ({
...thread,
stacktrace: thread.stacktrace
? {
...thread.stacktrace,
frames: thread.stacktrace.frames
? anonymizeStackTrace(thread.stacktrace.frames)
: thread.stacktrace.frames,
}
: thread.stacktrace,
}),
);
}
// Anonymize user info
if (anonymized.user) {
anonymized.user = anonymizeUserInfo(anonymized.user);
}
// Remove OS environment variables
if (anonymized.contexts?.os?.environment) {
anonymized.contexts.os.environment = undefined;
}
return anonymized;
} catch (error) {
console.error("Error anonymizing Sentry event:", error);
return null; // Drop event if anonymization fails
}
}

View file

@ -1,5 +0,0 @@
/**
* Sentry configuration constants
*/
export const SENTRY_DSN =
"https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016";

View file

@ -337,9 +337,6 @@
"integrations": {
"ga4": {
"measurementId": "G-M3JWW8N2XQ"
},
"posthog": {
"apiKey": "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs"
}
},
"custom": {

View file

@ -45,7 +45,6 @@
},
"homepage": "https://continue.dev",
"dependencies": {
"@sentry/profiling-node": "^9.47.1",
"fdir": "^6.4.2",
"find-up": "^8.0.0",
"fzf": "^0.5.2",
@ -69,7 +68,6 @@
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
"@sentry/node": "^9.43.0",
"@testing-library/react": "^16.3.0",
"@types/date-fns": "^2.5.3",
"@types/diff": "^7.0.2",
@ -120,7 +118,6 @@
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"prettier": "^3.6.2",
"prettier-plugin-tailwindcss": "^0.6.14",
"react": "^19.1.0",

View file

@ -9,7 +9,6 @@ import { processCommandFlags } from "../flags/flagProcessor.js";
import { safeStderr, safeStdout } from "../init.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
import { sentryService } from "../sentry.js";
import { initializeServices, services } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
import {
@ -23,7 +22,6 @@ import {
updateSessionTitle,
} from "../session.js";
import { streamChatResponse } from "../stream/streamChatResponse.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { gracefulExit } from "../util/exit.js";
@ -427,12 +425,6 @@ async function processMessage(
);
}
sentryService.captureException(error, {
context: "chat_response",
isHeadless,
chatHistoryLength: services.chatHistory.getHistory().length,
});
// In headless mode, re-throw the error to bubble up to main error handler
// This preserves downstream logic like telemetry cleanup
if (isHeadless) {
@ -561,7 +553,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
try {
// Record session start
telemetryService.recordSessionStart();
await posthogService.capture("sessionStart", {});
// Start active time tracking
telemetryService.startActiveTime();
@ -639,11 +630,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
}
sentryService.captureException(err, {
context: "chat_command_fatal",
headless: options.headless,
});
// Stop active time tracking BEFORE graceful exit
telemetryService.stopActiveTime();

View file

@ -3,7 +3,6 @@ import type { ChatHistoryItem } from "core/index.js";
import express, { Request, Response } from "express";
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { posthogService } from "src/telemetry/posthogService.js";
import { prependPrompt } from "src/util/promptProcessor.js";
import { getAccessToken, getAssistantSlug } from "../auth/workos.js";
@ -75,8 +74,6 @@ export function shouldQueueInitialPrompt(
// eslint-disable-next-line max-statements
export async function serve(prompt?: string, options: ServeOptions = {}) {
await posthogService.capture("sessionStart", {});
// Set agent ID for error reporting if provided
setAgentId(options.id);

View file

@ -15,7 +15,7 @@ import {
getOrganizationId,
} from "./auth/workos.js";
import { env } from "./env.js";
import { posthogService } from "./telemetry/posthogService.js";
import { getUniqueId } from "./util/uniqueId.js";
import { getVersion } from "./version.js";
/**
@ -37,7 +37,7 @@ function mergeUserAgentIntoRequestOptions(
headers: {
...requestOptions?.headers,
"user-agent": getUserAgent(),
"x-continue-unique-id": posthogService.uniqueId,
"x-continue-unique-id": getUniqueId(),
},
};
}

View file

@ -19,9 +19,7 @@ import {
validateFlags,
} from "./flags/flagValidator.js";
import { configureConsoleForHeadless, safeStderr } from "./init.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
import { posthogService } from "./telemetry/posthogService.js";
import { post } from "./util/apiClient.js";
import { markUnhandledError } from "./util/errorState.js";
import { gracefulExit } from "./util/exit.js";
@ -205,8 +203,6 @@ addCommonOptions(program)
"Enable beta Subagent tool for invoking subagents",
)
.action(async (prompt, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "cn" });
// Handle piped input - detect it early and decide on mode
let stdinInput = null;
@ -311,8 +307,6 @@ program
.command("login")
.description("Authenticate with Continue")
.action(async () => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "login" });
await login();
});
@ -321,8 +315,6 @@ program
.command("logout")
.description("Log out from Continue")
.action(async () => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "logout" });
await logout();
});
@ -332,8 +324,6 @@ program
.description("List recent chat sessions and select one to resume")
.option("--json", "Output in JSON format")
.action(async (options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "ls" });
await listSessionsCommand({
format: options.json ? "json" : undefined,
});
@ -370,11 +360,6 @@ addCommonOptions(
"Specify the repository URL to use in the remote environment",
)
.action(async (prompt: string | undefined, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", {
command: "remote",
flagS: options.start,
});
await remote(prompt, options);
});
@ -397,8 +382,6 @@ program
"Enable beta UploadArtifact tool for uploading screenshots, videos, and logs",
)
.action(async (prompt, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "serve" });
// Merge parent options with subcommand options
const mergedOptions = mergeParentOptions(program, options);
@ -416,8 +399,6 @@ program
.description("Test remote TUI mode with a local server")
.option("--url <url>", "Server URL (default: http://localhost:8000)")
.action(async (prompt: string | undefined, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "remote-test" });
await remoteTest(prompt, options.url);
});
@ -426,7 +407,6 @@ program
.command("checks [action] [pr-url]")
.description("Show CI check statuses for a PR")
.action(async (action: string | undefined, prUrl: string | undefined) => {
await posthogService.capture("cliCommand", { command: "checks" });
await checks(action, prUrl);
});
@ -442,7 +422,6 @@ program
.option("--review-agents <agents...>", "Specific review agents to run")
.option("--verbose", "Enable verbose logging")
.action(async (options) => {
await posthogService.capture("cliCommand", { command: "review" });
await review(options);
});
@ -468,10 +447,7 @@ export async function runCli(): Promise<void> {
program.parse();
} catch (error) {
console.error(error);
sentryService.captureException(
error instanceof Error ? error : new Error(String(error)),
);
process.exit(1);
process.exit(1);
}
process.on("SIGTERM", async () => {

View file

@ -1,52 +0,0 @@
/**
* Optional profiling integration loader
* This module handles the optional @sentry/profiling-node dependency
* which contains native bindings and may not be available in all environments
*/
let profilingIntegration: any = null;
let profilingLoadAttempted = false;
/**
* Lazy load the profiling integration
*/
async function loadProfilingIntegration() {
if (profilingLoadAttempted) {
return profilingIntegration;
}
profilingLoadAttempted = true;
try {
// Try to load the native profiling module if available
const profilingModule = await import("@sentry/profiling-node");
profilingIntegration = profilingModule.nodeProfilingIntegration;
} catch {
// Profiling module not available - this is fine, profiling is optional
// The CLI will work without it, just without performance profiling
}
return profilingIntegration;
}
/**
* Returns the profiling integration if available, or a no-op function
* Note: This is now async to handle lazy loading
*/
export async function getProfilingIntegration() {
const integration = await loadProfilingIntegration();
if (integration) {
return integration();
}
// Return empty object as a no-op integration
return {};
}
/**
* Check if profiling is available
* Note: This is now async to handle lazy loading
*/
export async function isProfilingAvailable(): Promise<boolean> {
await loadProfilingIntegration();
return profilingIntegration !== null;
}

View file

@ -1,183 +0,0 @@
import * as Sentry from "@sentry/node";
import {
getProfilingIntegration,
isProfilingAvailable,
} from "./sentry-profiling.js";
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 async initialize() {
if (this.initialized || !this.config.dsn) {
return;
}
try {
const integrations = [];
const profilingIntegration = await getProfilingIntegration();
if (
profilingIntegration &&
Object.keys(profilingIntegration).length > 0
) {
integrations.push(profilingIntegration);
}
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,
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,
profilingAvailable: await isProfilingAvailable(),
});
} 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>,
level?: "info" | "warning" | "error" | "debug" | "fatal",
) {
if (!this.isEnabled()) return;
Sentry.withScope((scope) => {
if (level) {
scope.setLevel(level);
}
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

@ -4,7 +4,6 @@ import * as workosModule from "./auth/workos.js";
import { services } from "./services/index.js";
import * as sessionModule from "./session.js";
import { handleSlashCommands } from "./slashCommands.js";
import { posthogService } from "./telemetry/posthogService.js";
import * as versionModule from "./version.js";
// Mock all dependencies
@ -15,7 +14,6 @@ vi.mock("./version.js", () => ({
compareVersions: vi.fn(() => "same"),
}));
vi.mock("./session.js");
vi.mock("./telemetry/posthogService.js");
vi.mock("./services/index.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("./services/index.js")>();
@ -43,9 +41,6 @@ describe("handleSlashCommands - /info", () => {
// Mock process.cwd
vi.spyOn(process, "cwd").mockReturnValue("/test/working/directory");
// Mock posthog
vi.mocked(posthogService.capture).mockReturnValue(Promise.resolve());
// Mock version
vi.mocked(versionModule.getVersion).mockReturnValue("1.2.3");

View file

@ -33,13 +33,6 @@ vi.mock("./auth/workos.js", () => ({
loadAuthConfig: vi.fn(),
}));
// Mock telemetry
vi.mock("./telemetry/posthogService.js", () => ({
posthogService: {
capture: vi.fn(),
},
}));
// Mock commands
vi.mock("./commands/commands.js", () => ({
getAllSlashCommands: vi.fn(() => []),

View file

@ -11,7 +11,6 @@ import { handleInit } from "./commands/init.js";
import { handleInfoSlashCommand } from "./infoScreen.js";
import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
import { getCurrentSession, updateSessionTitle } from "./session.js";
import { posthogService } from "./telemetry/posthogService.js";
import { telemetryService } from "./telemetry/telemetryService.js";
import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
@ -143,8 +142,6 @@ async function handleFork() {
}
function handleTitle(args: string[]) {
posthogService.capture("useSlashCommand", { name: "title" });
const title = args.join(" ").trim();
if (!title) {
return {
@ -173,6 +170,10 @@ function handleJobs() {
return { openJobsSelector: true };
}
function handleSessions() {
return { openSessionSelector: true };
}
const commandHandlers: Record<string, CommandHandler> = {
help: handleHelp,
clear: () => {
@ -202,13 +203,13 @@ const commandHandlers: Record<string, CommandHandler> = {
title: handleTitle,
rename: handleTitle,
init: (args, assistant) => {
posthogService.capture("useSlashCommand", { name: "init" });
return handleInit(args, assistant);
},
update: () => {
return { openUpdateSelector: true };
},
jobs: handleJobs,
sessions: handleSessions,
};
export async function handleSlashCommands(
@ -224,7 +225,6 @@ export async function handleSlashCommands(
const [command, ...args] = input.slice(1).split(" ");
telemetryService.recordSlashCommand(command);
posthogService.capture("useSlashCommand", { name: command });
const handler = commandHandlers[command];
if (handler) {

View file

@ -34,12 +34,6 @@ vi.mock("../telemetry/telemetryService.js", () => ({
},
}));
vi.mock("../telemetry/posthogService.js", () => ({
posthogService: {
capture: vi.fn(),
},
}));
vi.mock("../util/logger.js", () => ({
logger: {
info: vi.fn(),

View file

@ -17,7 +17,6 @@ import {
services,
} from "../services/index.js";
import { trackSessionUsage } from "../session.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
executeToolCall,
@ -366,45 +365,6 @@ export function recordStreamTelemetry(options: {
costUsd: cost,
});
// Mirror core metrics to PostHog for product analytics
const cacheReadTokens =
fullUsage?.prompt_tokens_details?.cache_read_tokens ?? 0;
const cacheWriteTokens =
fullUsage?.prompt_tokens_details?.cache_write_tokens ?? 0;
try {
posthogService.capture("apiRequest", {
model: model.model,
durationMs: totalDuration,
inputTokens: actualInputTokens,
outputTokens: actualOutputTokens,
costUsd: cost,
cacheReadTokens,
cacheWriteTokens,
});
// Emit prompt_cache_metrics for the Prompt Cache Performance dashboard.
// total_prompt_tokens must include ALL input token types: non-cached input
// tokens (prompt_tokens) + cache reads + cache writes. Anthropic's
// `input_tokens` field only counts non-cached tokens, so using it alone as
// the denominator produces ratios >> 1 when caching works well.
if (fullUsage?.prompt_tokens_details) {
const totalPromptTokens =
(fullUsage.prompt_tokens ?? 0) + cacheReadTokens + cacheWriteTokens;
const cacheHitRate =
totalPromptTokens > 0 ? cacheReadTokens / totalPromptTokens : 0;
posthogService.capture("prompt_cache_metrics", {
model: model.model,
cache_read_tokens: cacheReadTokens,
cache_write_tokens: cacheWriteTokens,
total_prompt_tokens: totalPromptTokens,
cache_hit_rate: cacheHitRate,
tool_count: tools?.length ?? 0,
});
}
} catch {}
return cost;
}
@ -480,14 +440,6 @@ export async function preprocessStreamedToolCalls(
errorReason,
// modelName, TODO
});
void posthogService.capture("tool_call_outcome", {
succeeded: false,
toolName: toolCall.name,
errorReason,
duration_ms: duration,
// model: options.modelName, TODO
});
// Add error to chat history
errorChatEntries.push({
role: "tool",

View file

@ -10,7 +10,6 @@ import type {
import { pruneLastMessage } from "../compaction.js";
import { services } from "../services/index.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { applyChatCompletionToolOverrides } from "../tools/applyToolOverrides.js";
import { ToolCall } from "../tools/index.js";
@ -371,15 +370,6 @@ export async function processStreamingResponse(
error: error.message || String(error),
});
try {
posthogService.capture("apiRequest", {
model: model.model,
durationMs: errorDuration,
success: false,
error: error.message || String(error),
});
} catch {}
if (error.name === "AbortError" || abortController?.signal.aborted) {
logger.debug("Stream aborted by user");
return {

View file

@ -1,103 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { PosthogService } from "./posthogService.js";
describe("PosthogService Error Handling", () => {
let posthogService: PosthogService;
let consoleSpy: any;
beforeEach(() => {
posthogService = new PosthogService();
// Spy on console methods but don't mock them - we want to test they don't crash
consoleSpy = vi.spyOn(console, "debug").mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
});
it("should handle network errors gracefully during capture", async () => {
// Mock the PostHog client to throw a network error
const mockClient = {
capture: vi.fn().mockImplementation(() => {
throw new Error("Network error: SSL wrong version number");
}),
};
// Mock the getClient method to return our mock client
vi.spyOn(posthogService as any, "getClient").mockResolvedValue(mockClient);
// This should not throw an error
await expect(
posthogService.capture("test_event", { test: "data" }),
).resolves.toBeUndefined();
// Verify the client capture was called
expect(mockClient.capture).toHaveBeenCalledWith({
distinctId: expect.any(String),
event: "test_event",
properties: expect.objectContaining({
test: "data",
os: expect.any(String),
extensionVersion: expect.any(String),
ideName: "cn",
ideType: "cli",
}),
sendFeatureFlags: true,
});
});
it("should handle errors gracefully during shutdown", async () => {
// Mock the PostHog client to throw an error during shutdown
const mockClient = {
shutdown: vi.fn().mockImplementation(() => {
throw new Error("Network error during shutdown");
}),
};
// Mock the getClient method to return our mock client
vi.spyOn(posthogService as any, "getClient").mockResolvedValue(mockClient);
// This should not throw an error
await expect(posthogService.shutdown()).resolves.toBeUndefined();
// Verify the client shutdown was called
expect(mockClient.shutdown).toHaveBeenCalled();
});
it("should handle getClient errors gracefully", async () => {
// Mock the getClient method to throw an error
vi.spyOn(posthogService as any, "getClient").mockRejectedValue(
new Error("Failed to initialize PostHog client"),
);
// This should not throw an error
await expect(
posthogService.capture("test_event", { test: "data" }),
).resolves.toBeUndefined();
});
it("should not capture when service is disabled", async () => {
// Mock environment variable to disable telemetry
const originalEnv = process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY;
process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0";
// Create a new service instance to pick up the env var
const disabledService = new PosthogService();
// Mock the getClient method
const getClientSpy = vi.spyOn(disabledService as any, "getClient");
await disabledService.capture("test_event", { test: "data" });
// Verify getClient was called but would return undefined due to disabled state
expect(getClientSpy).toHaveBeenCalled();
// Restore environment
if (originalEnv === undefined) {
delete process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY;
} else {
process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = originalEnv;
}
});
});

View file

@ -1,189 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { machineIdSync } from "node-machine-id";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// Mock the auth module and node-machine-id
vi.mock("../auth/workos.js", () => ({
loadAuthConfig: vi.fn(),
isAuthenticatedConfig: vi.fn(),
}));
vi.mock("node-machine-id", () => {
const mockFn = vi.fn(() => "test-machine-id");
return {
default: {
machineIdSync: mockFn,
},
machineIdSync: mockFn,
};
});
// Mock dns/promises for connection checks
vi.mock("dns/promises", () => {
const lookup = vi.fn();
return { default: { lookup } };
});
// eslint-disable-next-line import/order
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
import { PosthogService } from "./posthogService.js";
describe("PosthogService", () => {
let tempDir: string;
beforeEach(() => {
// Create a temporary directory for each test
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "posthog-test-"));
// Mock os.homedir to return our temp directory
vi.spyOn(os, "homedir").mockReturnValue(tempDir);
// Clear environment variable
delete process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY;
// Reset all mocks
vi.clearAllMocks();
});
afterEach(() => {
// Clean up temp directory
fs.rmSync(tempDir, { recursive: true, force: true });
// Restore mocks
vi.restoreAllMocks();
});
describe("uniqueId generation", () => {
it("should use Continue user id when signed in", () => {
const mockUserId = "user123";
vi.mocked(loadAuthConfig).mockReturnValue({ userId: mockUserId } as any);
vi.mocked(isAuthenticatedConfig).mockReturnValue(true);
const service = new PosthogService();
// Access private field for testing
const uniqueId = (service as any).uniqueId;
expect(uniqueId).toBe(mockUserId);
expect(loadAuthConfig).toHaveBeenCalled();
expect(isAuthenticatedConfig).toHaveBeenCalled();
});
it("should use machine id when not signed in", () => {
const mockMachineId = "test-machine-id";
vi.mocked(loadAuthConfig).mockReturnValue(null);
vi.mocked(isAuthenticatedConfig).mockReturnValue(false);
vi.mocked(machineIdSync).mockReturnValue(mockMachineId);
const service = new PosthogService();
// Access private field for testing
const uniqueId = (service as any).uniqueId;
expect(uniqueId).toBe(mockMachineId);
expect(loadAuthConfig).toHaveBeenCalled();
expect(isAuthenticatedConfig).toHaveBeenCalled();
expect(machineIdSync).toHaveBeenCalled();
});
it("should use machine id when auth config is environment-based", () => {
const mockMachineId = "test-machine-id";
vi.mocked(loadAuthConfig).mockReturnValue({
accessToken: "token",
} as any);
vi.mocked(isAuthenticatedConfig).mockReturnValue(false);
vi.mocked(machineIdSync).mockReturnValue(mockMachineId);
const service = new PosthogService();
// Access private field for testing
const uniqueId = (service as any).uniqueId;
expect(uniqueId).toBe(mockMachineId);
expect(machineIdSync).toHaveBeenCalled();
});
});
describe("telemetry enabled/disabled", () => {
it("should be enabled by default", () => {
const service = new PosthogService();
expect(service.isEnabled).toBe(true);
});
it("should be disabled when CONTINUE_ALLOW_ANONYMOUS_TELEMETRY is 0", () => {
process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0";
const service = new PosthogService();
expect(service.isEnabled).toBe(false);
});
});
describe("hasInternetConnection and offline client", () => {
let service: PosthogService;
beforeEach(() => {
service = new PosthogService();
});
it("returns false on DNS error, caches and refetches", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockRejectedValueOnce(new Error("offline"));
const first = await (service as any).hasInternetConnection();
expect(first).toBe(false);
dns.lookup.mockResolvedValueOnce({
address: "1.1.1.1",
family: 4,
} as any);
await (service as any).hasInternetConnection();
const second = (service as any)._hasInternetConnection;
expect(second).toBe(true);
expect(dns.lookup).toHaveBeenCalledTimes(2);
});
it("getClient returns undefined when offline", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockRejectedValueOnce(new Error("offline"));
const client = await (service as any).getClient();
expect(client).toBeUndefined();
expect(dns.lookup).toHaveBeenCalledTimes(1);
});
it("returns false when DNS resolves to 0.0.0.0 (blocked)", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockResolvedValueOnce({
address: "0.0.0.0",
family: 4,
} as any);
const result = await (service as any).hasInternetConnection();
expect(result).toBe(false);
expect(dns.lookup).toHaveBeenCalledTimes(1);
});
it("returns false when DNS resolves to localhost", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockResolvedValueOnce({
address: "127.0.0.1",
family: 4,
} as any);
const result = await (service as any).hasInternetConnection();
expect(result).toBe(false);
expect(dns.lookup).toHaveBeenCalledTimes(1);
});
it("returns true when DNS resolves to valid address", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockResolvedValueOnce({
address: "1.1.1.1",
family: 4,
} as any);
const result = await (service as any).hasInternetConnection();
expect(result).toBe(true);
expect(dns.lookup).toHaveBeenCalledTimes(1);
});
});
});

View file

@ -1,173 +0,0 @@
import dns from "dns/promises";
import os from "node:os";
import node_machine_id from "node-machine-id";
import type { PostHog as PostHogType } from "posthog-node";
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
import { loggers } from "../logging.js";
import { isHeadlessMode, isServe } from "../util/cli.js";
import { isGitHubActions } from "../util/git.js";
import { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
export class PosthogService {
private _os: string | undefined;
private _uniqueId: string | undefined;
private _telemetryBlocked: boolean = false;
constructor() {
// Initialization is now lazy to avoid issues with mocking in tests
}
private get os(): string {
if (!this._os) {
this._os = os.platform();
}
return this._os;
}
public get uniqueId(): string {
if (!this._uniqueId) {
this._uniqueId = this.getEventUserId();
}
return this._uniqueId;
}
private _hasInternetConnection: boolean | undefined = undefined;
private async hasInternetConnection() {
const refetchConnection = async () => {
try {
const result = await dns.lookup("app.posthog.com");
const isValidAddress =
result.address !== "0.0.0.0" && !result.address.startsWith("127.");
this._hasInternetConnection = isValidAddress;
this._telemetryBlocked = !isValidAddress;
if (!isValidAddress) {
logger.debug(
"DNS lookup returned invalid address for PostHog, skipping telemetry",
);
}
} catch {
this._hasInternetConnection = false;
this._telemetryBlocked = false;
}
};
if (typeof this._hasInternetConnection !== "undefined") {
void refetchConnection(); // check in background if connection became available
return this._hasInternetConnection;
}
await refetchConnection();
return this._hasInternetConnection;
}
get isEnabled() {
if (process.env.CONTINUE_TELEMETRY_ENABLED === "0") {
return false;
}
if (process.env.CONTINUE_TELEMETRY_ENABLED === "1") {
return true;
}
return process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY !== "0";
}
private _client: PostHogType | undefined;
private async getClient() {
if (!(await this.hasInternetConnection())) {
this._client = undefined;
if (this._telemetryBlocked && this.isEnabled) {
loggers.warning(
"Telemetry appears to be blocked by your network. To disable telemetry entirely, set CONTINUE_TELEMETRY_ENABLED=0",
);
} else if (this.isEnabled) {
logger.warn("No internet connection, skipping telemetry");
}
} else if (this.isEnabled) {
if (!this._client) {
const { PostHog } = await import("posthog-node");
this._client = new PostHog(
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
{
host: "https://app.posthog.com",
},
);
logger.debug("Initialized telemetry");
}
} else {
this._client = undefined;
}
return this._client;
}
/**
* - Continue user id from environment (when running as agent)
* - Continue user id if signed in locally
* - Unique machine id if not signed in
*/
private getEventUserId(): string {
// When running as an agent, use the user ID from the environment
if (process.env.CONTINUE_USER_ID) {
return process.env.CONTINUE_USER_ID;
}
const authConfig = loadAuthConfig();
if (isAuthenticatedConfig(authConfig)) {
return authConfig.userId;
}
// Fall back to unique machine id if not signed in
return node_machine_id.machineIdSync();
}
async capture(event: string, properties: { [key: string]: any }) {
try {
const client = await this.getClient();
if (!client) {
return;
}
const augmentedProperties = {
...properties,
os: this.os,
extensionVersion: getVersion(),
ideName: "cn",
ideType: "cli",
isHeadless: isHeadlessMode(),
isGitHubCI: isGitHubActions(),
isServe: isServe(),
};
const payload = {
distinctId: this.uniqueId,
event,
properties: augmentedProperties,
sendFeatureFlags: true,
};
client?.capture(payload);
} catch (e) {
logger.debug(`Failed to capture telemetry event '${event}': ${e}`);
}
}
async shutdown() {
try {
const client = await this.getClient();
if (client) {
// Set a timeout for shutdown to prevent hanging
const shutdownPromise = client.shutdown();
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Shutdown timeout")), 5000),
);
await Promise.race([shutdownPromise, timeoutPromise]);
}
} catch (e) {
logger.debug(`Failed to shutdown PostHog client: ${e}`);
}
}
}
export const posthogService = new PosthogService();

View file

@ -22,12 +22,6 @@ vi.mock("../telemetry/telemetryService.js", () => ({
},
}));
vi.mock("../telemetry/posthogService.js", () => ({
posthogService: {
capture: vi.fn(),
},
}));
// Mock logger
vi.mock("../util/logger.js", () => ({
logger: {

View file

@ -2,7 +2,6 @@
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { ChatCompletionTool } from "openai/resources.mjs";
import { posthogService } from "src/telemetry/posthogService.js";
import { isModelCapable } from "src/utils/modelCapability.js";
import {
@ -250,12 +249,6 @@ export async function executeToolCall(
durationMs: duration,
toolParameters: JSON.stringify(toolCall.arguments),
});
void posthogService.capture("tool_call_outcome", {
succeeded: true,
toolName: toolCall.name,
duration_ms: duration,
});
logger.debug("Tool execution completed", {
toolName: toolCall.name,
resultLength: result?.length || 0,
@ -278,13 +271,6 @@ export async function executeToolCall(
errorReason,
toolParameters: JSON.stringify(toolCall.arguments),
});
void posthogService.capture("tool_call_outcome", {
succeeded: false,
toolName: toolCall.name,
duration_ms: duration,
errorReason,
});
throw error;
}
}

View file

@ -1,6 +1,5 @@
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { sentryService } from "../sentry.js";
import {
ApiRequestError,
AuthenticationRequiredError,
@ -58,18 +57,6 @@ export const reportFailureTool: Tool = {
throw new ContinueError(ContinueErrorReason.Unspecified, errorMessage);
}
// Capture failure in Sentry with context
sentryService.captureException(
new Error(trimmedMessage),
{
agent_failure: {
agentId,
errorMessage: trimmedMessage,
},
},
"fatal",
);
await post(`agents/${agentId}/status`, {
status: "FAILED",
errorMessage: trimmedMessage,

View file

@ -3,22 +3,6 @@ vi.mock("./hooks/useTerminalSize.js", () => ({
useTerminalSize: () => ({ columns: 80, rows: 24 }),
}));
// Mock sentry to prevent initialization issues
vi.mock("../sentry.js", () => ({
sentryService: {
captureException: vi.fn(),
captureMessage: vi.fn(),
setUser: vi.fn(),
setTag: vi.fn(),
setContext: vi.fn(),
addBreadcrumb: vi.fn(),
startSpan: vi.fn(),
flush: vi.fn(),
close: vi.fn(),
isEnabled: vi.fn().mockReturnValue(false),
},
}));
import { render } from "ink-testing-library";
import React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

View file

@ -8,7 +8,6 @@ import { logger } from "src/util/logger.js";
import { DEFAULT_SESSION_TITLE } from "../../constants/session.js";
import { loadSession, startNewSession } from "../../session.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { processImagePlaceholder } from "./useChat.imageProcessing.js";
@ -36,9 +35,6 @@ export async function initChatHistory(
* Handle /config command
*/
export function handleConfigCommand(onShowConfigSelector: () => void): void {
posthogService.capture("useSlashCommand", {
name: "config",
});
onShowConfigSelector();
}
@ -233,10 +229,6 @@ export async function formatMessageWithFiles(
export function trackUserMessage(message: string, model?: any): void {
telemetryService.startActiveTime();
telemetryService.logUserPrompt(message.length, message);
posthogService.capture("chat", {
model: model?.name,
provider: model?.provider,
});
}
interface HandleSpecialCommandsOptions {

View file

@ -1,7 +1,6 @@
import type { ChatHistoryItem } from "core/index.js";
import { services } from "../../services/index.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { logger } from "../../util/logger.js";
import { RemoteServerState } from "./useChat.types.js";
@ -135,10 +134,6 @@ export async function handleRemoteExit(
remoteUrl: string,
exit: () => void,
): Promise<void> {
posthogService.capture("useSlashCommand", {
name: "exit",
});
try {
const response = await fetch(`${remoteUrl}/exit`, {
method: "POST",

View file

@ -1,6 +1,5 @@
import type { ChatHistoryItem } from "core/index.js";
import { sentryService } from "../sentry.js";
import { backgroundJobService } from "../services/BackgroundJobService.js";
import { getSessionUsage } from "../session.js";
import { telemetryService } from "../telemetry/telemetryService.js";
@ -212,13 +211,6 @@ export async function gracefulExit(code: number = 0): Promise<void> {
logger.debug("Telemetry shutdown error (ignored)", err as any);
}
try {
// Flush Sentry (best effort)
await sentryService.flush();
} catch (err) {
logger.debug("Sentry flush error (ignored)", err as any);
}
// If we're trying to exit with success (0) but had unhandled errors,
// exit with 1 instead to signal failure
const finalCode = code === 0 && hadUnhandledError() ? 1 : code;

View file

@ -6,7 +6,6 @@ import chalk from "chalk";
import winston from "winston";
import { env } from "../env.js";
import { sentryService } from "../sentry.js";
const { combine, timestamp, printf, errors } = winston.format;
@ -150,7 +149,6 @@ export const logger = {
info: (message: string, meta?: any) => winstonLogger.info(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) {
@ -159,17 +157,10 @@ export const logger = {
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

View file

@ -0,0 +1,26 @@
import node_machine_id from "node-machine-id";
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
let _uniqueId: string | undefined;
/**
* - Continue user id from environment (when running as agent)
* - Continue user id if signed in locally
* - Unique machine id if not signed in
*/
export function getUniqueId(): string {
if (!_uniqueId) {
if (process.env.CONTINUE_USER_ID) {
_uniqueId = process.env.CONTINUE_USER_ID;
} else {
const authConfig = loadAuthConfig();
if (isAuthenticatedConfig(authConfig)) {
_uniqueId = authConfig.userId;
} else {
_uniqueId = node_machine_id.machineIdSync();
}
}
}
return _uniqueId;
}

View file

@ -15,7 +15,6 @@ plugins {
id("org.jetbrains.intellij.platform") version "2.7.2"
id("org.jetbrains.changelog") version "2.1.2"
id("org.jetbrains.qodana") version "0.1.13"
id("io.sentry.jvm.gradle") version "5.8.0"
}
group = pluginGroup
@ -47,7 +46,6 @@ dependencies {
testFramework(TestFrameworkType.Platform)
testFramework(TestFrameworkType.Starter, "243.21565.193", configurationName = "testIntegrationImplementation")
}
implementation("com.posthog.java:posthog:1.2.0")
testImplementation("junit:junit:4.13.2")
testImplementation("io.mockk:mockk:1.14.2") {

View file

@ -1,6 +1,5 @@
package com.github.continuedev.continueintellijextension.auth
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
@ -90,7 +89,7 @@ class ContinueAuthService {
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(sessionInfo)
} catch (e: Exception) {
service<ContinueSentryService>().report(e, "Exception while refreshing token ${e.message}")
}
}

View file

@ -1,7 +1,5 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import kotlinx.coroutines.CoroutineScope
@ -26,7 +24,6 @@ class CoreMessengerManager(
log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds")
coreMessenger.restart()
} catch (e: Exception) {
service<ContinuePostHogService>().capture("jetbrains_core_start_error", mapOf("error" to e))
}
}
}

View file

@ -7,7 +7,6 @@ import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.github.continuedev.continueintellijextension.protocol.*
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@ -462,7 +461,7 @@ class IdeProtocolClient(
}
} catch (exception: Exception) {
val exceptionMessage = "Error handling message of type $messageType: $exception"
service<ContinueSentryService>().report(exception, exceptionMessage)
ide.showToast(ToastType.ERROR, exceptionMessage)
}
}

View file

@ -4,7 +4,6 @@ import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.*
@ -433,7 +432,6 @@ class IntelliJIDE(
return results.split("\n")
} catch (exception: Exception) {
val message = "Error executing ripgrep: ${exception.message}"
service<ContinueSentryService>().report(exception, message)
showToast(ToastType.ERROR, message)
return emptyList()
}
@ -480,7 +478,6 @@ class IntelliJIDE(
return ExecUtil.execAndGetOutput(command).stdout
} catch (exception: Exception) {
val message = "Error executing ripgrep: ${exception.message}"
service<ContinueSentryService>().report(exception, message)
showToast(ToastType.ERROR, message)
return "Error: Unable to execute ripgrep command."
}

View file

@ -1,12 +1,9 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.github.continuedev.continueintellijextension.proxy.ProxySettings
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
import com.github.continuedev.continueintellijextension.utils.getOS
import com.intellij.openapi.components.service
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.io.File
@ -51,8 +48,7 @@ class ContinueBinaryProcess(
err = err.substring(doneIndex + delimiter.length)
}
}
service<ContinueSentryService>().reportMessage("Core process exited with output: $err")
service<ContinuePostHogService>().capture("jetbrains_core_exit", mapOf("error" to err))
}
private companion object {

View file

@ -1,7 +1,5 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
@ -32,13 +30,11 @@ class ContinueProcessHandler(
log.debug("Handle: $line")
handleMessage(line)
} catch (e: Exception) {
service<ContinueSentryService>().report(e, "Error handling message: $line")
}
} else
delay(100)
}
} catch (e: IOException) {
service<ContinueSentryService>().report(e)
}
}
scope.launch(Dispatchers.IO) {

View file

@ -1,7 +1,6 @@
package com.github.continuedev.continueintellijextension.error
import com.intellij.diagnostic.IdeaReportingEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
@ -24,12 +23,6 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() {
// todo: IdeaReportingEvent is deprecated; migrate to IdeaLoggingEvent + figure out how to read attachments
val event = events.filterIsInstance<IdeaReportingEvent>()
.firstOrNull() ?: return false
service<ContinueSentryService>().report(
throwable = event.data.throwable,
message = additionalInfo ?: event.data.message,
attachments = event.data.allAttachments,
ignoreTelemetrySettings = true
)
} catch (_: Exception) {
consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED))
return false

View file

@ -1,32 +0,0 @@
package com.github.continuedev.continueintellijextension.error
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.posthog.java.PostHog
@Service
class ContinuePostHogService(
private val telemetryStatus: ContinueTelemetryStatus = service<ContinueTelemetryStatusService>(),
private val posthog: PostHog = PostHog.Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build()
) {
private val log = Logger.getInstance(ContinuePostHogService::class.java)
private val distinctId: String = getMachineUniqueID()
fun capture(eventName: String, properties: Map<String, *>) {
if (!telemetryStatus.allowAnonymousTelemetry) {
log.warn("PostHog capture was ignored because telemetry is disabled")
return
}
try {
posthog.capture(distinctId, eventName, properties)
log.warn("Telemetry sent to PostHog: $eventName")
} catch (_: Exception) {
}
}
private companion object {
private const val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs"
}
}

View file

@ -1,79 +0,0 @@
package com.github.continuedev.continueintellijextension.error
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.jcef.JBCefApp
import io.sentry.Hint
import io.sentry.Sentry
import io.sentry.SentryEvent
import io.sentry.protocol.Message
private typealias SentryAttachment = io.sentry.Attachment
@Service
class ContinueSentryService(
private val telemetryStatus: ContinueTelemetryStatus = service<ContinueTelemetryStatusService>()
) {
private val log = Logger.getInstance(ContinueSentryService::class.java.simpleName)
init {
Sentry.init { config ->
config.dsn = SENTRY_DSN
config.environment = recognizeEnvironment()
config.isSendDefaultPii = false
config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
config.setTag("jcef_supported", JBCefApp.isSupported().toString())
config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version)
config.setTag("system", SystemInfo.OS_NAME)
config.setTag("system_version", SystemInfo.OS_VERSION)
}
}
fun report(
throwable: Throwable,
message: String? = null,
attachments: List<Attachment>? = null,
ignoreTelemetrySettings: Boolean = false
) {
if (!ignoreTelemetrySettings && !telemetryStatus.allowAnonymousTelemetry) {
log.warn("Sentry report was ignored because telemetry is disabled", throwable)
return
}
val sentryEvent = SentryEvent()
sentryEvent.throwable = throwable
sentryEvent.message = Message().apply { this.message = message }
val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) })
Sentry.captureEvent(sentryEvent, hint)
log.warn("Exception sent to Sentry", throwable)
}
fun reportMessage(
message: String,
) {
if (!telemetryStatus.allowAnonymousTelemetry) {
log.warn("Sentry message report was ignored because telemetry is disabled: $message")
return
}
Sentry.captureMessage(message)
log.warn("Message sent to Sentry: $message")
}
private companion object {
private const val PLUGIN_ID = "com.github.continuedev.continueintellijextension"
private const val SENTRY_DSN =
"https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016"
private fun recognizeEnvironment() =
when {
System.getProperty("robot-server.port") != null -> "e2e"
System.getProperty("idea.is.internal").toBoolean() -> "dev"
else -> "production"
}
}
}

View file

@ -1,5 +0,0 @@
package com.github.continuedev.continueintellijextension.error
interface ContinueTelemetryStatus {
val allowAnonymousTelemetry: Boolean
}

View file

@ -1,44 +0,0 @@
package com.github.continuedev.continueintellijextension.error
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.ProjectManager
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.seconds
@Service
class ContinueTelemetryStatusService : ContinueTelemetryStatus {
private val scope = CoroutineScope(Dispatchers.Default)
@Volatile
override var allowAnonymousTelemetry: Boolean = DISABLED_FALLBACK
private set
init {
scope.launch {
while (isActive) {
poolTelemetryStatus()
delay(10.seconds)
}
}
}
private fun poolTelemetryStatus() {
// this works, but ideally, the project should be a dependency injected via constructor
val project = ProjectManager.getInstance().openProjects.firstOrNull()
?: return
val coreMessenger = project.service<ContinuePluginService>().coreMessenger
?: return
coreMessenger.request("config/getSerializedProfileInfo", null, null) { response ->
allowAnonymousTelemetry =
response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
?: DISABLED_FALLBACK
}
}
private companion object {
const val DISABLED_FALLBACK = false
}
}

View file

@ -2,7 +2,6 @@ package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.google.gson.Gson
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
@ -136,7 +135,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
}
} catch (e: Exception) {
// Catch all exceptions including JsonSyntaxException
service<ContinueSentryService>().report(e, "Unexpected exception during remote config sync")
}
}
}

View file

@ -1,29 +0,0 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
import com.github.continuedev.continueintellijextension.error.ContinueTelemetryStatus
import com.posthog.java.PostHog
import io.mockk.mockk
import io.mockk.verify
import junit.framework.TestCase
class ContinuePostHogServiceTest : TestCase() {
fun `test report when telemetry is enabled`() {
val postHog = mockk<PostHog>(relaxed = true)
val service = ContinuePostHogService(TestTelemetryService(true), postHog)
service.capture("test", mapOf("test" to "test"))
verify { postHog.capture(any(), any(), any()) }
}
fun `test don't report when telemetry is disabled`() {
val postHog = mockk<PostHog>(relaxed = true)
val service = ContinuePostHogService(TestTelemetryService(false), postHog)
service.capture("test", mapOf("test" to "test"))
verify(exactly = 0) { postHog.capture(any(), any(), any()) }
}
private class TestTelemetryService(
override val allowAnonymousTelemetry: Boolean
) : ContinueTelemetryStatus
}

View file

@ -3317,12 +3317,8 @@
"properties": {
"provider": {
"type": "string",
"enum": ["posthog", "logstash"],
"description": "The 3rd party analytics provider to use.",
"default": "posthog",
"markdownEnumDescriptions": [
"### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field."
]
"enum": ["logstash"],
"description": "The 3rd party analytics provider to use."
},
"url": {
"type": "string",
@ -3335,18 +3331,6 @@
},
"required": ["provider"],
"allOf": [
{
"if": {
"properties": {
"provider": {
"enum": ["posthog"]
}
}
},
"then": {
"required": ["clientKey"]
}
},
{
"if": {
"properties": {

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.3.32",
"version": "1.3.33",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -759,7 +759,6 @@
"ncp": "^2.0.0",
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"posthog-node": "^3.6.3",
"react-markdown": "^8.0.7",
"react-redux": "^8.0.5",
"read-last-lines": "^1.8.0",
@ -767,9 +766,9 @@
"socket.io-client": "^4.7.2",
"strip-ansi": "^7.1.0",
"svg-builder": "^2.0.0",
"systeminformation": "^5.30.0",
"systeminformation": "^5.30.8",
"tailwindcss": "^3.3.2",
"undici": "^6.21.3",
"undici": "^6.24.0",
"uuid": "^9.0.1",
"uuidv4": "^6.2.13",
"vectordb": "0.4.20",

View file

@ -1,9 +1,8 @@
import { getContinueRcPath, getTsConfigPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { VsCodeExtension } from "../extension/VsCodeExtension";
import { getExtensionVersion, isUnsupportedPlatform } from "../util/util";
import { isUnsupportedPlatform } from "../util/util";
import { GlobalContext } from "core/util/GlobalContext";
import { VsCodeContinueApi } from "./api";
@ -23,16 +22,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
void vscode.window.showInformationMessage(
`Continue detected that you are using ${platformTarget}. Due to native dependencies, Continue may not be able to start`,
);
void Telemetry.capture(
"unsupported_platform_activation_attempt",
{
platform: platformTarget,
extensionVersion: getExtensionVersion(),
reason: platformCheck.reason,
},
true,
);
}
// Add necessary files
@ -47,13 +36,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
// Load Continue configuration
if (!context.globalState.get("hasBeenInstalled")) {
void context.globalState.update("hasBeenInstalled", true);
void Telemetry.capture(
"install",
{
extensionVersion: getExtensionVersion(),
},
true,
);
}
// Register config.yaml schema by removing old entries and adding new one (uri.fsPath changes with each version)

View file

@ -15,7 +15,6 @@ export class RecentlyVisitedRangesService {
string,
Array<AutocompleteCodeSnippet & { timestamp: number }>
>;
// Default value, we override in initWithPostHog
private numSurroundingLines = 20;
private maxRecentFiles = 3;
private maxSnippetsPerFile = 3;
@ -29,22 +28,6 @@ export class RecentlyVisitedRangesService {
max: this.maxRecentFiles,
});
void this.initWithPostHog();
}
private async initWithPostHog() {
// TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364
// const recentlyVisitedRangesNumSurroundingLines =
// await Telemetry.getValueForFeatureFlag(
// PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines,
// );
// if (recentlyVisitedRangesNumSurroundingLines) {
// this.isEnabled = true;
// this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines;
// }
// vscode.window.onDidChangeTextEditorSelection(
// this.cacheCurrentSelectionContext,
// );
}
private cacheCurrentSelectionContext = async (

View file

@ -16,7 +16,6 @@ import {
getConfigYamlPath,
setConfigFilePermissions,
} from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import * as YAML from "yaml";
@ -59,18 +58,6 @@ function getFullScreenTab() {
);
}
type TelemetryCaptureParams = Parameters<typeof Telemetry.capture>;
/**
* Helper method to add the `isCommandEvent` to all telemetry captures
*/
function captureCommandTelemetry(
commandName: TelemetryCaptureParams[0],
properties: TelemetryCaptureParams[1] = {},
) {
Telemetry.capture(commandName, { isCommandEvent: true, ...properties });
}
function focusGUI() {
const fullScreenTab = getFullScreenTab();
if (fullScreenTab) {
@ -184,7 +171,6 @@ const getCommandsMap: (
return {
"continue.acceptDiff": async (newFileUri?: string, streamId?: string) => {
captureCommandTelemetry("acceptDiff");
void processDiff(
"accept",
sidebar,
@ -197,7 +183,6 @@ const getCommandsMap: (
},
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) => {
captureCommandTelemetry("rejectDiff");
void processDiff(
"reject",
sidebar,
@ -209,36 +194,28 @@ const getCommandsMap: (
);
},
"continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
captureCommandTelemetry("acceptVerticalDiffBlock");
verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index);
},
"continue.rejectVerticalDiffBlock": (fileUri?: string, index?: number) => {
captureCommandTelemetry("rejectVerticalDiffBlock");
verticalDiffManager.acceptRejectVerticalDiffBlock(false, fileUri, index);
},
"continue.quickFix": async (
range: vscode.Range,
diagnosticMessage: string,
) => {
captureCommandTelemetry("quickFix");
const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`;
addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt);
vscode.commands.executeCommand("continue.continueGUIView.focus");
},
// Passthrough for telemetry purposes
"continue.defaultQuickAction": async (args: QuickEditShowParams) => {
captureCommandTelemetry("defaultQuickAction");
vscode.commands.executeCommand("continue.focusEdit", args);
},
"continue.customQuickActionSendToChat": async (
prompt: string,
range: vscode.Range,
) => {
captureCommandTelemetry("customQuickActionSendToChat");
addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt);
vscode.commands.executeCommand("continue.continueGUIView.focus");
@ -247,8 +224,6 @@ const getCommandsMap: (
prompt: string,
range: vscode.Range,
) => {
captureCommandTelemetry("customQuickActionStreamInlineEdit");
streamInlineEdit("docstring", prompt, range);
},
"continue.codebaseForceReIndex": async () => {
@ -341,50 +316,39 @@ const getCommandsMap: (
// QuickEditShowParams are passed from CodeLens, temp fix
// until we update to new params specific to Edit
"continue.focusEdit": async (args?: QuickEditShowParams) => {
captureCommandTelemetry("focusEdit");
focusGUI();
sidebar.webviewProtocol?.request("focusEdit", undefined);
},
"continue.exitEditMode": async () => {
captureCommandTelemetry("exitEditMode");
editDecorationManager.clear();
void sidebar.webviewProtocol?.request("exitEditMode", undefined);
},
"continue.generateRule": async () => {
captureCommandTelemetry("generateRule");
focusGUI();
void sidebar.webviewProtocol?.request("generateRule", undefined);
},
"continue.writeCommentsForCode": async () => {
captureCommandTelemetry("writeCommentsForCode");
streamInlineEdit(
"comment",
"Write comments for this code. Do not change anything about the code itself.",
);
},
"continue.writeDocstringForCode": async () => {
captureCommandTelemetry("writeDocstringForCode");
void streamInlineEdit(
"docstring",
"Write a docstring for this code. Do not change anything about the code itself.",
);
},
"continue.fixCode": async () => {
captureCommandTelemetry("fixCode");
streamInlineEdit(
"fix",
"Fix this code. If it is already 100% correct, simply rewrite the code.",
);
},
"continue.optimizeCode": async () => {
captureCommandTelemetry("optimizeCode");
streamInlineEdit("optimize", "Optimize this code");
},
"continue.fixGrammar": async () => {
captureCommandTelemetry("fixGrammar");
streamInlineEdit(
"fixGrammar",
"If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.",
@ -394,12 +358,9 @@ const getCommandsMap: (
consoleView.clearLog();
},
"continue.viewLogs": async () => {
captureCommandTelemetry("viewLogs");
vscode.commands.executeCommand("workbench.action.toggleDevTools");
},
"continue.debugTerminal": async () => {
captureCommandTelemetry("debugTerminal");
const terminalContents = await ide.getTerminalContents();
vscode.commands.executeCommand("continue.continueGUIView.focus");
@ -416,8 +377,6 @@ const getCommandsMap: (
// Commands without keyboard shortcuts
"continue.addModel": () => {
captureCommandTelemetry("addModel");
vscode.commands.executeCommand("continue.continueGUIView.focus");
sidebar.webviewProtocol?.request("addModel", undefined);
},
@ -535,8 +494,6 @@ const getCommandsMap: (
nextEditLoggingService.reject(completionId);
},
"continue.toggleTabAutocompleteEnabled": () => {
captureCommandTelemetry("toggleTabAutocompleteEnabled");
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
const enabled = config.get("enableTabAutocomplete");
const pauseOnBattery = config.get<boolean>(
@ -571,8 +528,6 @@ const getCommandsMap: (
}
},
"continue.forceAutocomplete": async () => {
captureCommandTelemetry("forceAutocomplete");
// 1. Explicitly hide any existing suggestion. This clears VS Code's cache for the current position.
await vscode.commands.executeCommand("editor.action.inlineSuggest.hide");
@ -583,8 +538,6 @@ const getCommandsMap: (
},
"continue.openTabAutocompleteConfigMenu": async () => {
captureCommandTelemetry("openTabAutocompleteConfigMenu");
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
const quickPick = vscode.window.createQuickPick();
@ -744,8 +697,6 @@ const getCommandsMap: (
});
},
"continue.enterEnterpriseLicenseKey": async () => {
captureCommandTelemetry("enterEnterpriseLicenseKey");
const licenseKey = await vscode.window.showInputBox({
prompt: "Enter your enterprise license key",
password: true,
@ -780,8 +731,6 @@ const getCommandsMap: (
}
},
"continue.toggleNextEditEnabled": async () => {
captureCommandTelemetry("toggleNextEditEnabled");
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
const tabAutocompleteEnabled = config.get<boolean>(
"enableTabAutocomplete",
@ -823,8 +772,6 @@ const getCommandsMap: (
vscode.commands.executeCommand("continue.newSession");
// Full screen not open - open it
captureCommandTelemetry("openInNewWindow");
// Create the full screen panel
let panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
@ -872,8 +819,6 @@ const getCommandsMap: (
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
},
"continue.forceNextEdit": async () => {
captureCommandTelemetry("forceNextEdit");
// This is basically the same logic as forceAutocomplete.
// I'm writing a new command KV pair here in case we diverge in features.

View file

@ -3,12 +3,8 @@
*/
import { setupCa } from "core/util/ca";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { SentryLogger } from "core/util/sentry/SentryLogger";
import { getExtensionVersion } from "./util/util";
export { default as buildTimestamp } from "./.buildTimestamp";
async function dynamicImportAndActivate(context: vscode.ExtensionContext) {
@ -20,15 +16,6 @@ async function dynamicImportAndActivate(context: vscode.ExtensionContext) {
export function activate(context: vscode.ExtensionContext) {
return dynamicImportAndActivate(context).catch((e) => {
console.log("Error activating extension: ", e);
Telemetry.capture(
"vscode_extension_activation_error",
{
stack: extractMinimalStackTraceInfo(e.stack),
message: e.message,
},
false,
true,
);
vscode.window
.showWarningMessage(
"Error activating the Continue extension.",
@ -46,15 +33,4 @@ export function activate(context: vscode.ExtensionContext) {
});
}
export function deactivate() {
void Telemetry.capture(
"deactivate",
{
extensionVersion: getExtensionVersion(),
},
true,
);
Telemetry.shutdownPosthogClient();
SentryLogger.shutdownSentryClient();
}
export function deactivate() {}

View file

@ -1,5 +1,4 @@
import { ContinueConfig, QuickActionConfig } from "core";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick";
@ -20,10 +19,6 @@ export function subscribeToVSCodeQuickActionsSettings(listener: Function) {
const configKey = `${CONTINUE_WORKSPACE_KEY}.${ENABLE_QUICK_ACTIONS_KEY}`;
if (e.affectsConfiguration(configKey)) {
Telemetry.capture("VSCode Quick Actions Settings Changed", {
enabled: quickActionsEnabledStatus(),
});
listener();
}
});

View file

@ -2,7 +2,6 @@
import { IDE, ILLM, RuleWithSource } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { DataLogger } from "core/data/log";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
@ -161,13 +160,6 @@ export class QuickEdit {
return;
}
Telemetry.capture("quickEditSelection", {
selection: {
label: selectedLabel,
value: selectedValue,
},
});
const prompt = await this.handleSelect({
selectedLabel,
selectedValue,

View file

@ -1,7 +1,5 @@
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { Message } from "core/protocol/messenger";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { Telemetry } from "core/util/posthog";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
@ -134,16 +132,6 @@ export class VsCodeWebviewProtocol
this.request("setupLocalConfig", undefined);
}
});
} else {
Telemetry.capture(
"webview_protocol_error",
{
messageType: msg.messageType,
errorMsg: message.split("\n\n")[0],
stack: extractMinimalStackTraceInfo(e.stack),
},
false,
);
}
}
}

View file

@ -23,8 +23,6 @@
"@modelcontextprotocol/ext-apps": "^1.0.1",
"@panzoom/panzoom": "^4.6.0",
"@reduxjs/toolkit": "^2.11.2",
"@sentry/react": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@tiptap/core": "^2.27.0",
"@tiptap/extension-document": "^2.27.0",
"@tiptap/extension-dropcursor": "^2.27.0",
@ -53,7 +51,6 @@
"mermaid": "^11.10.0",
"minisearch": "^7.0.2",
"mustache": "^4.2.0",
"posthog-js": "^1.310.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",

View file

@ -6,7 +6,6 @@ import { CustomScrollbarDiv } from ".";
import { AuthProvider } from "../context/Auth";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { LocalStorageProvider } from "../context/LocalStorage";
import TelemetryProviders from "../hooks/TelemetryProviders";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { setCodeToEdit } from "../redux/slices/editState";
@ -25,7 +24,7 @@ import {
useOnboardingCard,
} from "./OnboardingCard";
import OSRContextMenu from "./OSRContextMenu";
import PostHogPageView from "./PosthogPageView";
const LayoutTopDiv = styled(CustomScrollbarDiv)`
height: 100%;
@ -237,7 +236,6 @@ const Layout = () => {
return (
<LocalStorageProvider>
<AuthProvider>
<TelemetryProviders>
<LayoutTopDiv>
{showStagingIndicator && (
<span
@ -269,7 +267,6 @@ const Layout = () => {
/>
<GridDiv>
<PostHogPageView />
<Outlet />
{/* The fatal error for chat is shown below input */}
{!isHome && <FatalErrorIndicator />}
@ -277,7 +274,6 @@ const Layout = () => {
</div>
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
</LayoutTopDiv>
</TelemetryProviders>
</AuthProvider>
</LocalStorageProvider>
);

View file

@ -1,12 +1,10 @@
import { OnboardingModes } from "core/protocol/core";
import { usePostHog } from "posthog-js/react";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
import { useOnboardingCard } from "./useOnboardingCard";
export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) {
const posthog = usePostHog();
const ideMessenger = useContext(IdeMessengerContext);
const { close: closeOnboardingCard } = useOnboardingCard();
@ -23,12 +21,6 @@ export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) {
});
if (onboardingStatus === "Started") {
// Telemetry
posthog.capture("Onboarding Step", { status: "Completed" });
posthog.capture("onboardingSelection", {
mode,
});
// Local state
setLocalStorage("onboardingStatus", "Completed");

View file

@ -1,31 +0,0 @@
import { usePostHog } from "posthog-js/react";
import { useEffect } from "react";
import { useLocation, useSearchParams } from "react-router-dom";
/**
* This is copied from here: https://posthog.com/tutorials/single-page-app-pageviews#tracking-pageviews-in-nextjs-app-router
* They don't have a non-NextJS doc for React apps.
*/
export default function PostHogPageView() {
const { pathname } = useLocation();
const [searchParams] = useSearchParams();
const posthog = usePostHog();
// Track pageviews
useEffect(() => {
if (pathname && posthog) {
let url = window.origin + pathname;
if (searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture("$pageview", {
$current_url: url,
pathname,
});
}
}, [pathname, searchParams, posthog]);
return null;
}

View file

@ -1,6 +1,5 @@
import { InformationCircleIcon } from "@heroicons/react/24/outline";
import { IndexingStatus, SiteIndexingConfig } from "core";
import { usePostHog } from "posthog-js/react";
import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { Input, SecondaryButton } from "..";
@ -12,7 +11,6 @@ import { ToolTip } from "../gui/Tooltip";
import DocsIndexingPeeks from "../../pages/config/sections/docs/DocsIndexingPeeks";
function AddDocsDialog() {
const posthog = usePostHog();
const dispatch = useDispatch();
const titleRef = useRef<HTMLInputElement>(null);
@ -63,8 +61,6 @@ function AddDocsDialog() {
setStartUrl("");
setFaviconUrl("");
posthog.capture("add_docs_gui", { url: startUrl });
// Optimistic status update
dispatch(
updateIndexingStatus({

View file

@ -1,10 +1,8 @@
import { usePostHog } from "posthog-js/react";
import { Button, Input, SecondaryButton } from "..";
import { useAppDispatch } from "../../redux/hooks";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
export default function FeedbackDialog() {
const posthog = usePostHog();
const dispatch = useAppDispatch();
return (
@ -23,10 +21,6 @@ export default function FeedbackDialog() {
<form
onSubmit={(e: any) => {
e.preventDefault();
posthog?.capture("user_interest_form", {
name: e.target.elements[0].value,
email: e.target.elements[1].value,
});
dispatch(
setDialogMessage(
<div className="p-6 text-center">

View file

@ -10,7 +10,6 @@ import { Decoration, DecorationSet } from "@tiptap/pm/view";
import { useEditor } from "@tiptap/react";
import { InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { usePostHog } from "posthog-js/react";
import { useRef } from "react";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { useSubmenuContextProviders } from "../../../../context/SubmenuContextProviders";
@ -84,8 +83,6 @@ export function createEditorConfig(options: {
}) {
const { props, ideMessenger, dispatch } = options;
const posthog = usePostHog();
const { getSubmenuContextItems } = useSubmenuContextProviders();
const defaultModel = useAppSelector(selectSelectedChatModel);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
@ -247,8 +244,6 @@ export function createEditorConfig(options: {
},
"Mod-Enter": () => {
posthog.capture("gui_use_active_file_enter");
onEnter({
useCodebase: false,
noContext: !!useActiveFile,
@ -257,8 +252,6 @@ export function createEditorConfig(options: {
return true;
},
"Alt-Enter": () => {
posthog.capture("gui_use_active_file_enter");
onEnter({
useCodebase: false,
noContext: !!useActiveFile,

View file

@ -1,6 +1,6 @@
import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core";
import { stripImages } from "core/util/messageContent";
import posthog from "posthog-js";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { renderMcpPrompt } from "./renderMcpPrompt";
import { getRenderedV1Prompt } from "./renderPromptv1";
@ -37,16 +37,6 @@ export async function renderSlashCommandPrompt(
return NO_COMMAND;
}
try {
posthog.capture("useSlashCommand", {
name: command.name,
source: command.source,
isLegacy: command.isLegacy,
});
} catch (e) {
console.error(e);
}
const nonTextParts = parts.filter((part) => part.type !== "text");
const textParts = parts.filter((part) => part.type === "text");
const slashedParts: MessagePart[] = [...nonTextParts];

View file

@ -1,306 +0,0 @@
import { createStore } from "@reduxjs/toolkit";
import * as Sentry from "@sentry/react";
import { render, screen } from "@testing-library/react";
import posthog from "posthog-js";
import React from "react";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AuthProvider } from "../context/Auth";
import TelemetryProviders from "./TelemetryProviders";
// Mock Sentry
vi.mock("@sentry/react", () => ({
init: vi.fn(),
setUser: vi.fn(),
getClient: vi.fn(),
getCurrentScope: vi.fn(() => ({
clear: vi.fn(),
})),
browserTracingIntegration: vi.fn(() => ({ name: "BrowserTracing" })),
replayIntegration: vi.fn(() => ({ name: "Replay" })),
feedbackIntegration: vi.fn(() => ({ name: "Feedback" })),
contextLinesIntegration: vi.fn(() => ({ name: "ContextLines" })),
ErrorBoundary: ({ children }: { children: React.ReactNode }) => (
<div data-testid="sentry-error-boundary">{children}</div>
),
}));
// Mock PostHog
vi.mock("posthog-js", () => ({
default: {
init: vi.fn(),
identify: vi.fn(),
opt_in_capturing: vi.fn(),
opt_out_capturing: vi.fn(),
},
}));
// Mock PostHog React provider
vi.mock("posthog-js/react", () => ({
PostHogProvider: ({ children }: { children: React.ReactNode }) => (
<div data-testid="posthog-provider">{children}</div>
),
}));
// Mock the Auth context
vi.mock("../context/Auth", () => ({
AuthProvider: ({ children }: { children: React.ReactNode }) => (
<div data-testid="auth-provider">{children}</div>
),
useAuth: () => ({
session: {
account: {
id: "test@continue.dev", // Mock Continue team member email
},
},
}),
}));
// Mock isContinueTeamMember utility
vi.mock("../util/isContinueTeamMember", () => ({
isContinueTeamMember: vi.fn(() => true), // Mock as Continue team member
}));
// Mock window.vscMachineId
Object.defineProperty(window, "vscMachineId", {
value: "test-machine-id",
writable: true,
});
// Create a minimal Redux store for testing
const createTestStore = (allowAnonymousTelemetry: boolean) => {
return createStore(
(
state = {
config: {
config: {
allowAnonymousTelemetry,
},
},
},
) => state,
);
};
// Mock persistor
const mockPersistor = {
persist: vi.fn(),
purge: vi.fn(),
flush: vi.fn(),
pause: vi.fn(),
getState: vi.fn(() => ({
bootstrapped: true,
registry: [],
})),
dispatch: vi.fn(),
subscribe: vi.fn(),
};
const TestWrapper: React.FC<{
children: React.ReactNode;
allowAnonymousTelemetry: boolean;
}> = ({ children, allowAnonymousTelemetry }) => {
const store = createTestStore(allowAnonymousTelemetry);
return (
<Provider store={store}>
<PersistGate loading={null} persistor={mockPersistor}>
<AuthProvider>{children}</AuthProvider>
</PersistGate>
</Provider>
);
};
describe("TelemetryProviders", () => {
const mockSentry = Sentry as any;
const mockPosthog = posthog as any;
beforeEach(() => {
vi.clearAllMocks();
// Reset NODE_ENV to test
process.env.NODE_ENV = "test";
});
afterEach(() => {
vi.clearAllMocks();
});
describe("when telemetry is enabled", () => {
it("should initialize both PostHog and Sentry", () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
render(
<TestWrapper allowAnonymousTelemetry={true}>
<TelemetryProviders>
<div data-testid="test-child">Test Child</div>
</TelemetryProviders>
</TestWrapper>,
);
// Verify PostHog initialization
expect(mockPosthog.init).toHaveBeenCalledWith(
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
expect.objectContaining({
api_host: "https://app.posthog.com",
disable_session_recording: true,
autocapture: false,
capture_pageleave: false,
capture_pageview: false,
}),
);
expect(mockPosthog.identify).toHaveBeenCalledWith("test-machine-id");
expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
// Verify Sentry initialization
expect(mockSentry.init).toHaveBeenCalledWith(
expect.objectContaining({
dsn: "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016",
environment: "development",
tracesSampleRate: 0.25,
}),
);
expect(mockSentry.setUser).toHaveBeenCalledWith({
id: expect.stringMatching(/^[a-f0-9]{8}$/), // Should be 8-char hash
email: undefined,
username: undefined,
ip_address: undefined,
});
// Verify children are rendered
expect(screen.getByTestId("test-child")).toBeInTheDocument();
expect(screen.getByTestId("posthog-provider")).toBeInTheDocument();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("when telemetry is disabled", () => {
it("should disable PostHog and clear Sentry scope", () => {
const mockClear = vi.fn();
const mockClose = vi.fn();
const mockClient = { close: mockClose };
mockSentry.getCurrentScope.mockReturnValue({ clear: mockClear });
mockSentry.getClient.mockReturnValue(mockClient);
render(
<TestWrapper allowAnonymousTelemetry={false}>
<TelemetryProviders>
<div data-testid="test-child">Test Child</div>
</TelemetryProviders>
</TestWrapper>,
);
// Verify PostHog is disabled
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
expect(mockPosthog.init).not.toHaveBeenCalled();
expect(mockPosthog.identify).not.toHaveBeenCalled();
expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();
// Verify Sentry is properly disabled
expect(mockSentry.getClient).toHaveBeenCalled();
expect(mockClose).toHaveBeenCalled();
expect(mockSentry.getCurrentScope).toHaveBeenCalled();
expect(mockClear).toHaveBeenCalled();
expect(mockSentry.init).not.toHaveBeenCalled();
expect(mockSentry.setUser).not.toHaveBeenCalled();
// Verify children are still rendered
expect(screen.getByTestId("test-child")).toBeInTheDocument();
expect(screen.getByTestId("posthog-provider")).toBeInTheDocument();
});
});
describe("provider structure", () => {
it("should wrap children with PostHogProvider", () => {
render(
<TestWrapper allowAnonymousTelemetry={false}>
<TelemetryProviders>
<div data-testid="nested-child">
<span data-testid="deeply-nested">Deep content</span>
</div>
</TelemetryProviders>
</TestWrapper>,
);
// Verify the provider structure is maintained
expect(screen.getByTestId("posthog-provider")).toBeInTheDocument();
expect(screen.getByTestId("nested-child")).toBeInTheDocument();
expect(screen.getByTestId("deeply-nested")).toBeInTheDocument();
});
it("should handle missing vscMachineId gracefully", () => {
// Temporarily modify vscMachineId
const originalMachineId = window.vscMachineId;
(window as any).vscMachineId = undefined;
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
render(
<TestWrapper allowAnonymousTelemetry={true}>
<TelemetryProviders>
<div data-testid="test-child">Test Child</div>
</TelemetryProviders>
</TestWrapper>,
);
// Should still initialize but with anonymized ID (hashed "anonymous")
expect(mockSentry.setUser).toHaveBeenCalledWith({
id: expect.stringMatching(/^[a-f0-9]{8}$/), // Should be 8-char hash
email: undefined,
username: undefined,
ip_address: undefined,
});
// Restore
(window as any).vscMachineId = originalMachineId;
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("telemetry toggle behavior", () => {
it("should maintain proper state when telemetry setting changes", () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// First render with telemetry enabled
const { rerender } = render(
<TestWrapper allowAnonymousTelemetry={true}>
<TelemetryProviders>
<div data-testid="test-child">Test Child</div>
</TelemetryProviders>
</TestWrapper>,
);
expect(mockSentry.init).toHaveBeenCalled();
expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
// Clear mocks and rerender with telemetry disabled
vi.clearAllMocks();
const mockClear = vi.fn();
const mockClose = vi.fn();
const mockClient = { close: mockClose };
mockSentry.getCurrentScope.mockReturnValue({ clear: mockClear });
mockSentry.getClient.mockReturnValue(mockClient);
rerender(
<TestWrapper allowAnonymousTelemetry={false}>
<TelemetryProviders>
<div data-testid="test-child">Test Child</div>
</TelemetryProviders>
</TestWrapper>,
);
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
expect(mockClose).toHaveBeenCalled();
expect(mockClear).toHaveBeenCalled();
expect(mockSentry.init).not.toHaveBeenCalled();
process.env.NODE_ENV = originalNodeEnv;
});
});
});

View file

@ -1,130 +0,0 @@
import * as Sentry from "@sentry/react";
import { HubSessionInfo } from "core/control-plane/AuthTypes";
import {
anonymizeSentryEvent,
anonymizeUserInfo,
} from "core/util/sentry/anonymization";
import { SENTRY_DSN } from "core/util/sentry/constants";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { PropsWithChildren, useEffect } from "react";
import { useAuth } from "../context/Auth";
import { useAppSelector } from "../redux/hooks";
import { isPrerelease } from "../util/index";
import { isContinueTeamMember } from "../util/isContinueTeamMember";
import { getLocalStorage } from "../util/localStorage";
const SAMPLE_REATE = 0.1;
const TRACES_SAMPLE_RATE = 0.25;
const TelemetryProviders = ({ children }: PropsWithChildren) => {
const allowAnonymousTelemetry = useAppSelector(
(store) => store?.config?.config?.allowAnonymousTelemetry,
);
const { session } = useAuth();
// TODO: Remove Continue team member check once Sentry is ready for all users
const hasContinueEmail = isContinueTeamMember(
(session as HubSessionInfo)?.account?.id,
);
useEffect(() => {
// PostHog depends only on allowAnonymousTelemetry
if (allowAnonymousTelemetry) {
// Initialize PostHog (existing logic)
posthog.init("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
api_host: "https://app.posthog.com",
disable_session_recording: true,
autocapture: false,
// We need to manually track pageviews since we're a SPA
capture_pageleave: false,
capture_pageview: false,
});
posthog.identify(window.vscMachineId);
posthog.opt_in_capturing();
} else {
// Disable PostHog
posthog.opt_out_capturing();
}
// Sentry depends on both allowAnonymousTelemetry and hasContinueEmail
if (allowAnonymousTelemetry && hasContinueEmail) {
// Initialize Sentry (new for GUI - enhanced React setup)
Sentry.init({
dsn: SENTRY_DSN,
environment: process.env.NODE_ENV,
integrations: [
// Performance monitoring
Sentry.browserTracingIntegration(),
],
// For basic error tracking, a lower sample rate should be fine
sampleRate: SAMPLE_REATE,
tracesSampleRate: TRACES_SAMPLE_RATE,
// Privacy-conscious default
sendDefaultPii: false,
// Strip sensitive data and add basic properties
beforeSend(event: Sentry.Event) {
// Apply comprehensive anonymization using shared logic
const anonymizedEvent = anonymizeSentryEvent(event);
if (!anonymizedEvent) return null;
// Add basic properties available in GUI environment
if (!anonymizedEvent.tags) anonymizedEvent.tags = {};
// Add environment information
anonymizedEvent.tags.environment = process.env.NODE_ENV;
// Add ideInfo properties spread out as top-level properties (like PostHog)
const extensionVersion = getLocalStorage("extensionVersion");
const ideType = getLocalStorage("ide");
if (extensionVersion) {
anonymizedEvent.tags.extensionVersion = extensionVersion;
}
if (ideType) {
anonymizedEvent.tags.ideType = ideType;
}
// Add isPrerelease information
anonymizedEvent.tags.isPrerelease = isPrerelease();
return anonymizedEvent;
},
});
// Set anonymized user context for Sentry
const anonymizedUser = anonymizeUserInfo({
id: window.vscMachineId || "anonymous",
});
Sentry.setUser(anonymizedUser);
} else {
// Disable Sentry properly - close the client to stop all network requests
try {
const client = Sentry.getClient();
if (client) {
client.close();
}
Sentry.getCurrentScope().clear();
} catch (error) {
console.error("Error disabling Sentry:", error);
}
}
}, [allowAnonymousTelemetry, hasContinueEmail]);
// Conditionally wrap with ErrorBoundary when telemetry is enabled and user is Continue team member
const content =
allowAnonymousTelemetry && hasContinueEmail ? (
<Sentry.ErrorBoundary showDialog={false}>{children}</Sentry.ErrorBoundary>
) : (
children
);
// Only PostHog needs a provider wrapper - Sentry works globally once initialized
return <PostHogProvider client={posthog}>{content}</PostHogProvider>;
};
export default TelemetryProviders;

View file

@ -1,5 +1,4 @@
import { SlashCommandDescWithSource } from "core";
import { usePostHog } from "posthog-js/react";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import {
@ -10,7 +9,6 @@ import {
export function useBookmarkedSlashCommands() {
const dispatch = useAppDispatch();
const posthog = usePostHog();
const bookmarkedCommands = useAppSelector(selectBookmarkedSlashCommands);
const isCommandBookmarked = (commandName: string): boolean => {
@ -20,10 +18,6 @@ export function useBookmarkedSlashCommands() {
const toggleBookmark = (command: SlashCommandDescWithSource) => {
const isBookmarked = isCommandBookmarked(command.name);
posthog.capture("toggle_bookmarked_slash_command", {
isBookmarked,
});
if (isBookmarked) {
dispatch(
unbookmarkSlashCommand({

View file

@ -1,5 +1,4 @@
import { IndexingProgressUpdate } from "core";
import { usePostHog } from "posthog-js/react";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
@ -25,7 +24,6 @@ export function getProgressPercentage(
function IndexingProgress() {
const ideMessenger = useContext(IdeMessengerContext);
const posthog = usePostHog();
const dispatch = useDispatch();
const [paused, setPaused] = useState<boolean | undefined>(undefined);
const [update, setUpdate] = useState<IndexingProgressUpdate>({
@ -71,7 +69,6 @@ function IndexingProgress() {
"the Command Palette, and type out 'Continue: Force Codebase Re-Indexing'"
}
onConfirm={() => {
posthog.capture("rebuild_index_clicked");
ideMessenger.post("index/forceReIndex", {
shouldClearIndexes: true,
});

View file

@ -2,7 +2,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ContextItem, McpUiState } from "core";
import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import posthog from "posthog-js";
import { callClientTool } from "../../util/clientTools/callClientTool";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
@ -34,18 +34,8 @@ export const callToolById = createAsyncThunk<
return;
}
// Track tool call acceptance and start timing
const startTime = Date.now();
const selectedChatModel = selectSelectedChatModel(state);
posthog.capture("tool_call_decision", {
model: selectedChatModel,
decision: isAutoApproved ? "auto_accept" : "accept",
toolName: toolCallState.toolCall.function.name,
toolCallId: toolCallId,
});
if (!selectedChatModel) {
throw new Error("No model selected");
}
@ -129,16 +119,6 @@ export const callToolById = createAsyncThunk<
);
}
// Capture telemetry for tool call execution outcome with duration
const duration_ms = Date.now() - startTime;
posthog.capture("tool_call_outcome", {
model: selectedChatModel,
succeeded: !error,
toolName: toolCallState.toolCall.function.name,
errorReason: error?.reason,
duration_ms: duration_ms,
});
if (streamResponse) {
if (error) {
logToolUsage(toolCallState, false, false, extra.ideMessenger, output);

View file

@ -1,12 +1,11 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import posthog from "posthog-js";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
cancelToolCall as cancelToolCallAction,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCallById } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
const DEFAULT_USER_REJECTION_MESSAGE = `The user skipped the tool call.
@ -20,20 +19,8 @@ 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);
if (toolCallState) {
// Track tool call rejection
posthog.capture("tool_call_decision", {
model: selectedChatModel,
decision: "reject",
toolName: toolCallState.toolCall.function.name,
toolCallId: toolCallId,
});
}
if (continueAfterToolRejection) {
// Update tool call output with rejection message

View file

@ -1,6 +1,6 @@
import { ToolCallState } from "core";
import { ContinueErrorReason } from "core/util/errors";
import posthog from "posthog-js";
import { IIdeMessenger } from "../../context/IdeMessenger";
import {
errorToolCall,
@ -33,13 +33,6 @@ export async function preprocessToolCalls(
errorReason = ContinueErrorReason.Unknown;
}
if (errorReason) {
posthog.capture("tool_call_outcome", {
// model: , TODO
succeeded: false,
toolName: tcState.toolCall.function.name,
errorReason,
duration_ms: 0, // preprocessing is more or less instantaneous
});
dispatch(
errorToolCall({
toolCallId: tcState.toolCallId,

View file

@ -22,10 +22,11 @@ import { ThunkApiType } from "../store";
import { constructMessages } from "../util/constructMessages";
import { modelSupportsNativeTools } from "core/llm/toolSupport";
import { applyToolOverrides } from "core/tools/applyToolOverrides";
import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage";
import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks";
import posthog from "posthog-js";
import {
selectCurrentToolCalls,
selectPendingToolCalls,
@ -93,8 +94,20 @@ export const streamNormalInput = createAsyncThunk<
throw new Error("No chat model selected");
}
// Get tools and filter them based on the selected model
const activeTools = selectActiveTools(state);
// Get tools and apply model-level overrides (disabled, description, etc.)
let activeTools = selectActiveTools(state);
if (selectedChatModel.toolOverrides?.length) {
const { tools: overriddenTools, errors } = applyToolOverrides(
activeTools,
selectedChatModel.toolOverrides,
);
activeTools = overriddenTools;
for (const error of errors) {
if (!error.fatal) {
console.warn(`Tool override warning: ${error.message}`);
}
}
}
// Use the centralized selector to determine if system message tools should be used
const useNativeTools = state.config.config.experimental
@ -243,15 +256,6 @@ export const streamNormalInput = createAsyncThunk<
}
} catch (e) {
const toolCallsToCancel = selectCurrentToolCalls(getState());
posthog.capture("stream_premature_close_error", {
duration: (Date.now() - start) / 1000,
model: selectedChatModel.model,
provider: selectedChatModel.underlyingProviderName,
context: legacySlashCommandData ? "slash_command" : "regular_chat",
...(legacySlashCommandData && {
command: legacySlashCommandData.command.name,
}),
});
if (
toolCallsToCancel.length > 0 &&
e instanceof Error &&

View file

@ -23,13 +23,6 @@ import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
// Removed: shouldAutoEnableSystemMessageTools - let it run naturally
// Additional mocks for streamResponseThunk
vi.mock("posthog-js", () => ({
default: {
capture: vi.fn(),
},
}));
vi.mock("uuid", () => ({
v4: vi.fn(() => "mock-uuid-123"),
}));
@ -44,13 +37,11 @@ vi.mock(
import { ModelDescription } from "core";
import { serializeTool } from "core/tools";
import { grepSearchTool } from "core/tools/definitions";
import posthog from "posthog-js";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
import { RootState } from "../store";
const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage);
const mockPosthog = vi.mocked(posthog);
const mockResolveEditorContent = vi.mocked(resolveEditorContent);
const mockClaudeModel: ModelDescription = {

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