refactor: Integrate Posthog into Feature Flags & Telemetry & Error Services (#5275)
* refactor: posthog services: feature flags + error + telemtry - Convert PostHogClientProvider to singleton with lifecycle management - Update ErrorServices to use PostHogClientProvider - Update Telementry Service - Update and enable Feature Flags service * replace logger * fix imports - part 1 * update distinct ID * update * update * clean up * revert autoformat * fix merge conflicts * clean up autoformat * revert autoformatter * clean up logs
This commit is contained in:
23 files changed
+374
-362
No files matched your search
@@ -7,7 +7,7 @@ import { ApiHandler } from "../"
|
||||
import { ApiHandlerOptions, geminiDefaultModelId, GeminiModelId, geminiModels, ModelInfo } from "@shared/api"
|
||||
import { convertAnthropicMessageToGemini } from "../transform/gemini-format"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
import { telemetryService } from "@services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
|
||||
// Define a default TTL for the cache (e.g., 15 minutes in seconds)
|
||||
const DEFAULT_CACHE_TTL_SECONDS = 900
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { clineEnvConfig } from "@/config"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { AuthService } from "@/services/auth/AuthService"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { PostHogClientProvider, telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { getCwd, getDesktopDir } from "@/utils/path"
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
@@ -37,7 +37,6 @@ import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceC
|
||||
import { sendStateUpdate } from "./state/subscribeToState"
|
||||
import { sendAddToInputEvent } from "./ui/subscribeToAddToInput"
|
||||
import { getLatestAnnouncementId } from "@/utils/announcements"
|
||||
|
||||
/*
|
||||
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
|
||||
|
||||
@@ -359,7 +358,7 @@ export class Controller {
|
||||
// Get current API configuration from cache
|
||||
const currentApiConfiguration = this.cacheService.getApiConfiguration()
|
||||
|
||||
let updatedConfig = { ...currentApiConfiguration }
|
||||
const updatedConfig = { ...currentApiConfiguration }
|
||||
|
||||
if (planActSeparateModelsSetting) {
|
||||
// Only update the current mode's provider
|
||||
@@ -744,7 +743,7 @@ export class Controller {
|
||||
const latestAnnouncementId = getLatestAnnouncementId(this.context)
|
||||
const shouldShowAnnouncement = lastShownAnnouncementId !== latestAnnouncementId
|
||||
const platform = process.platform as Platform
|
||||
const distinctId = telemetryService.distinctId
|
||||
const distinctId = PostHogClientProvider.getInstance().distinctId
|
||||
const version = this.context.extension?.packageJSON?.version ?? ""
|
||||
const uriScheme = vscode.env.uriScheme
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import path from "path"
|
||||
import fs from "fs/promises"
|
||||
import { fileExistsAtPath } from "@utils/fs"
|
||||
import { GlobalFileNames } from "@core/storage/disk"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
|
||||
/**
|
||||
* Refreshes the Groq models and returns the updated model list
|
||||
@@ -111,7 +112,12 @@ export async function refreshGroqModels(controller: Controller, request: EmptyRe
|
||||
errorMessage = error.message
|
||||
}
|
||||
|
||||
console.error("Groq API Error:", errorMessage)
|
||||
telemetryService.captureProviderApiError({
|
||||
taskId: controller.task?.taskId || "",
|
||||
errorMessage,
|
||||
errorStatus: error.status,
|
||||
model: "groq",
|
||||
})
|
||||
|
||||
// If we failed to fetch models, try to read cached models first
|
||||
const cachedModels = await readGroqModels(controller)
|
||||
@@ -181,7 +187,7 @@ async function readGroqModels(controller: Controller): Promise<Record<string, Pa
|
||||
*/
|
||||
function isValidChatModel(rawModel: any): boolean {
|
||||
// Check if model is active (if the property exists)
|
||||
if (rawModel.hasOwnProperty("active") && !rawModel.active) {
|
||||
if (Object.hasOwn(rawModel, "active") && !rawModel.active) {
|
||||
return false
|
||||
}
|
||||
// Filter out non-chat models (whisper, TTS, guard models, etc.)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { Controller } from ".."
|
||||
import { Empty, StringRequest } from "@shared/proto/cline/common"
|
||||
import { updateGlobalState } from "@/core/storage/state"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Controller } from ".."
|
||||
import { Empty, StringRequest } from "@shared/proto/cline/common"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
|
||||
/**
|
||||
* Handles task feedback submission (thumbs up/down)
|
||||
|
||||
@@ -4,7 +4,7 @@ import { EmptyRequest, Empty } from "@shared/proto/cline/common"
|
||||
import { getAllExtensionState, getGlobalState, updateGlobalState } from "../../storage/state"
|
||||
import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels"
|
||||
import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplaceCatalog"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models"
|
||||
import { McpMarketplaceCatalog } from "@shared/mcp"
|
||||
import { refreshOpenRouterModels } from "../models/refreshOpenRouterModels"
|
||||
@@ -55,7 +55,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
|
||||
// Shared models: update both plan and act modes
|
||||
const planModelId = apiConfiguration.planModeOpenRouterModelId
|
||||
const actModelId = apiConfiguration.actModeOpenRouterModelId
|
||||
let updatedConfig = { ...apiConfiguration }
|
||||
const updatedConfig = { ...apiConfiguration }
|
||||
|
||||
// Update plan mode model info if we have a model ID
|
||||
if (planModelId && response.models[planModelId]) {
|
||||
@@ -101,7 +101,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
|
||||
// Shared models: update both plan and act modes
|
||||
const planModelId = apiConfiguration.planModeGroqModelId
|
||||
const actModelId = apiConfiguration.actModeGroqModelId
|
||||
let updatedConfig = { ...apiConfiguration }
|
||||
const updatedConfig = { ...apiConfiguration }
|
||||
|
||||
// Update plan mode model info if we have a model ID
|
||||
if (planModelId && response.models[planModelId]) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as vscode from "vscode"
|
||||
import type { Controller } from "../index"
|
||||
import type { EmptyRequest } from "@shared/proto/cline/common"
|
||||
import { Empty } from "@shared/proto/cline/common"
|
||||
import { telemetryService } from "../../../services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
|
||||
/**
|
||||
* Opens the Cline walkthrough in VSCode
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { showSystemNotification } from "@/integrations/notifications"
|
||||
import { listFiles } from "@/services/glob/list-files"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { regexSearchFiles } from "@/services/ripgrep"
|
||||
import { parseSourceCodeForDefinitionsTopLevel } from "@/services/tree-sitter"
|
||||
import { findLast, findLastIndex, parsePartialArrayString } from "@/shared/array"
|
||||
@@ -108,7 +108,12 @@ export class ToolExecutor {
|
||||
type: ClineAsk,
|
||||
text?: string,
|
||||
partial?: boolean,
|
||||
) => Promise<{ response: ClineAskResponse; text?: string; images?: string[]; files?: string[] }>,
|
||||
) => Promise<{
|
||||
response: ClineAskResponse
|
||||
text?: string
|
||||
images?: string[]
|
||||
files?: string[]
|
||||
}>,
|
||||
private saveCheckpoint: (isAttemptCompletionMessage?: boolean) => Promise<void>,
|
||||
private sayAndCreateMissingParamError: (toolName: ToolUseName, paramName: string, relPath?: string) => Promise<any>,
|
||||
private removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise<void>,
|
||||
@@ -472,7 +477,7 @@ export class ToolExecutor {
|
||||
case "write_to_file":
|
||||
case "replace_in_file": {
|
||||
const relPath: string | undefined = block.params.path
|
||||
let content: string | undefined = block.params.content // for write_to_file
|
||||
const content: string | undefined = block.params.content // for write_to_file
|
||||
let diff: string | undefined = block.params.diff // for replace_in_file
|
||||
if (!relPath || (!content && !diff)) {
|
||||
// checking for content/diff ensures relPath is complete
|
||||
@@ -1212,7 +1217,7 @@ export class ToolExecutor {
|
||||
if (this.context) {
|
||||
await this.browserSession.dispose()
|
||||
|
||||
let useWebp = this.api ? !modelDoesntSupportWebp(this.api) : true
|
||||
const useWebp = this.api ? !modelDoesntSupportWebp(this.api) : true
|
||||
this.browserSession = new BrowserSession(this.context, this.browserSettings, useWebp)
|
||||
} else {
|
||||
console.warn("no controller context available for browserSession")
|
||||
|
||||
+14
-14
@@ -14,7 +14,7 @@ import { BrowserSession } from "@services/browser/BrowserSession"
|
||||
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
|
||||
import { listFiles } from "@services/glob/list-files"
|
||||
import { Logger } from "@services/logging/Logger"
|
||||
import { telemetryService } from "@services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { ApiConfiguration } from "@shared/api"
|
||||
import { findLast, findLastIndex } from "@shared/array"
|
||||
import { AutoApprovalSettings } from "@shared/AutoApprovalSettings"
|
||||
@@ -38,7 +38,7 @@ import * as vscode from "vscode"
|
||||
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { ClineErrorType } from "@/services/error/ClineError"
|
||||
import { ErrorService } from "@/services/error/ErrorService"
|
||||
import { errorService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { parseAssistantMessageV2, parseAssistantMessageV3, ToolUseName } from "@core/assistant-message"
|
||||
import {
|
||||
checkIsAnthropicContextWindowError,
|
||||
@@ -1678,7 +1678,10 @@ export class Task {
|
||||
}
|
||||
}
|
||||
|
||||
private async getCurrentProviderInfo(): Promise<{ modelId: string; providerId: string }> {
|
||||
private async getCurrentProviderInfo(): Promise<{
|
||||
modelId: string
|
||||
providerId: string
|
||||
}> {
|
||||
const modelId = this.api.getModel()?.id
|
||||
const apiConfig = this.cacheService.getApiConfiguration()
|
||||
const providerId = (this.mode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider) as string
|
||||
@@ -1687,7 +1690,9 @@ export class Task {
|
||||
|
||||
async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
|
||||
// Wait for MCP servers to be connected before generating system prompt
|
||||
await pWaitFor(() => this.mcpHub.isConnecting !== true, { timeout: 10_000 }).catch(() => {
|
||||
await pWaitFor(() => this.mcpHub.isConnecting !== true, {
|
||||
timeout: 10_000,
|
||||
}).catch(() => {
|
||||
console.error("MCP servers failed to connect in time")
|
||||
})
|
||||
|
||||
@@ -1780,17 +1785,12 @@ export class Task {
|
||||
const isOpenRouterContextWindowError = checkIsOpenRouterContextWindowError(error) && isOpenRouter
|
||||
const isAnthropicContextWindowError = checkIsAnthropicContextWindowError(error) && isAnthropic
|
||||
const { modelId, providerId } = await this.getCurrentProviderInfo()
|
||||
const clineError = ErrorService.toClineError(error, modelId, providerId)
|
||||
const clineError = errorService.toClineError(error, modelId, providerId)
|
||||
|
||||
// Capture provider failure telemetry using clineError
|
||||
// TODO: Move into ErrorService
|
||||
telemetryService.captureProviderApiError({
|
||||
taskId: this.taskId,
|
||||
model: modelInfo.id,
|
||||
errorMessage: clineError.message,
|
||||
errorStatus: clineError._error?.status,
|
||||
requestId: clineError._error?.request_id,
|
||||
})
|
||||
// TODO: Move into errorService
|
||||
errorService.logMessage(clineError.message)
|
||||
errorService.logException(clineError)
|
||||
|
||||
if (isAnthropic && isAnthropicContextWindowError && !this.taskState.didAutomaticallyRetryFailedApiRequest) {
|
||||
this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
|
||||
@@ -2397,7 +2397,7 @@ export class Task {
|
||||
// abandoned happens when extension is no longer waiting for the cline instance to finish aborting (error is thrown here when any function in the for loop throws due to this.abort)
|
||||
if (!this.taskState.abandoned) {
|
||||
this.abortTask() // if the stream failed, there's various states the task could be in (i.e. could have streamed some tools the user may have executed), so we just resort to replicating a cancel task
|
||||
const clineError = ErrorService.toClineError(error, this.api.getModel().id)
|
||||
const clineError = errorService.toClineError(error, this.api.getModel().id)
|
||||
const errorMessage = clineError.serialize()
|
||||
|
||||
await abortStream("streaming_failed", errorMessage)
|
||||
|
||||
+23
-29
@@ -1,11 +1,11 @@
|
||||
// The module 'vscode' contains the VS Code extensibility API
|
||||
// Import the module and reference it with the alias vscode in your code below
|
||||
import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider"
|
||||
import { WebviewProviderType as WebviewProviderTypeEnum } from "@shared/proto/cline/ui"
|
||||
|
||||
import assert from "node:assert"
|
||||
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
|
||||
import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider"
|
||||
import { WebviewProviderType as WebviewProviderTypeEnum } from "@shared/proto/cline/ui"
|
||||
import pWaitFor from "p-wait-for"
|
||||
import { v4 as uuidv4 } from "uuid"
|
||||
import * as vscode from "vscode"
|
||||
import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToAccountButtonClicked"
|
||||
import { sendChatButtonClickedEvent } from "./core/controller/ui/subscribeToChatButtonClicked"
|
||||
@@ -19,24 +19,23 @@ import {
|
||||
} from "./core/storage/state-migrations"
|
||||
import { WebviewProvider } from "./core/webview"
|
||||
import { createClineAPI } from "./exports"
|
||||
import { ErrorService } from "./services/error/ErrorService"
|
||||
import { Logger } from "./services/logging/Logger"
|
||||
import { posthogClientProvider } from "./services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "./services/posthog/telemetry/TelemetryService"
|
||||
import { PostHogClientProvider } from "./services/posthog/PostHogClientProvider"
|
||||
import { cleanupTestMode, initializeTestMode } from "./services/test/TestMode"
|
||||
import { WebviewProviderType } from "./shared/webview/types"
|
||||
import "./utils/path" // necessary to have access to String.prototype.toPosix
|
||||
|
||||
import type { ExtensionContext } from "vscode"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client"
|
||||
import { readTextFromClipboard, writeTextToClipboard } from "@/utils/env"
|
||||
import { ExtensionContext } from "vscode"
|
||||
import { FileContextTracker } from "./core/context/context-tracking/FileContextTracker"
|
||||
import { sendFocusChatInputEvent } from "./core/controller/ui/subscribeToFocusChatInput"
|
||||
import { VscodeDiffViewProvider } from "./hosts/vscode/VscodeDiffViewProvider"
|
||||
import { VscodeWebviewProvider } from "./hosts/vscode/VscodeWebviewProvider"
|
||||
import { GitCommitGenerator } from "./integrations/git/commit-message-generator"
|
||||
import { AuthService } from "./services/auth/AuthService"
|
||||
import { telemetryService } from "./services/posthog/PostHogClientProvider"
|
||||
import { ShowMessageType } from "./shared/proto/host/window"
|
||||
import { SharedUriHandler } from "./services/uri/SharedUriHandler"
|
||||
import { getLatestAnnouncementId } from "./utils/announcements"
|
||||
@@ -54,7 +53,10 @@ https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/framewo
|
||||
export async function activate(context: vscode.ExtensionContext) {
|
||||
maybeSetupHostProviders(context)
|
||||
|
||||
ErrorService.initialize()
|
||||
// Initialize PostHog client provider
|
||||
const distinctId = context.globalState.get<string>("cline.distinctId")
|
||||
PostHogClientProvider.getInstance(distinctId)
|
||||
|
||||
Logger.log("Cline extension activated")
|
||||
|
||||
// Migrate custom instructions to global Cline rules (one-time cleanup)
|
||||
@@ -102,7 +104,10 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
: `Welcome to Cline v${currentVersion}`
|
||||
await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus")
|
||||
await new Promise((resolve) => setTimeout(resolve, 200))
|
||||
HostProvider.window.showMessage({ type: ShowMessageType.INFORMATION, message })
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.INFORMATION,
|
||||
message,
|
||||
})
|
||||
}
|
||||
// Always update the main version tracker for the next launch.
|
||||
await context.globalState.update("clineVersion", currentVersion)
|
||||
@@ -112,15 +117,7 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
console.error(`Error during post-update actions: ${errorMessage}, Stack trace: ${error.stack}`)
|
||||
}
|
||||
|
||||
// backup id in case vscMachineID doesn't work
|
||||
let installId = context.globalState.get<string>("installId")
|
||||
|
||||
if (!installId) {
|
||||
installId = uuidv4()
|
||||
await context.globalState.update("installId", installId)
|
||||
}
|
||||
|
||||
telemetryService.captureExtensionActivated(installId)
|
||||
telemetryService.captureExtensionActivated()
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand("cline.plusButtonClicked", async (webview: any) => {
|
||||
@@ -337,7 +334,7 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
await vscode.commands.executeCommand("workbench.action.terminal.copySelection")
|
||||
|
||||
// Get copied content
|
||||
let terminalContents = (await readTextFromClipboard()).trim()
|
||||
const terminalContents = (await readTextFromClipboard()).trim()
|
||||
|
||||
// Restore original clipboard content
|
||||
await writeTextToClipboard(tempCopyBuffer)
|
||||
@@ -553,7 +550,7 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
let activeWebviewProvider: WebviewProvider | undefined = WebviewProvider.getVisibleInstance()
|
||||
|
||||
// If a tab is visible and active, ensure it's fully revealed (might be redundant but safe)
|
||||
if (activeWebviewProvider?.getWebview() && activeWebviewProvider.getWebview().hasOwnProperty("reveal")) {
|
||||
if (activeWebviewProvider?.getWebview() && Object.hasOwn(activeWebviewProvider.getWebview(), "reveal")) {
|
||||
const panelView = activeWebviewProvider.getWebview() as vscode.WebviewPanel
|
||||
panelView.reveal(panelView.viewColumn)
|
||||
} else if (!activeWebviewProvider) {
|
||||
@@ -568,7 +565,7 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
const tabInstances = WebviewProvider.getTabInstances()
|
||||
if (tabInstances.length > 0) {
|
||||
const potentialTabInstance = tabInstances[tabInstances.length - 1] // Get the most recent one
|
||||
if (potentialTabInstance.getWebview() && potentialTabInstance.getWebview().hasOwnProperty("reveal")) {
|
||||
if (potentialTabInstance.getWebview() && Object.hasOwn(potentialTabInstance.getWebview(), "reveal")) {
|
||||
const panelView = potentialTabInstance.getWebview() as vscode.WebviewPanel
|
||||
panelView.reveal(panelView.viewColumn)
|
||||
activeWebviewProvider = potentialTabInstance
|
||||
@@ -585,7 +582,7 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
() => {
|
||||
const visibleInstance = WebviewProvider.getVisibleInstance()
|
||||
// Ensure a boolean is returned
|
||||
return !!(visibleInstance?.getWebview() && visibleInstance.getWebview().hasOwnProperty("reveal"))
|
||||
return !!(visibleInstance?.getWebview() && Object.hasOwn(visibleInstance.getWebview(), "reveal"))
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
)
|
||||
@@ -654,12 +651,8 @@ function maybeSetupHostProviders(context: ExtensionContext) {
|
||||
if (!HostProvider.isInitialized()) {
|
||||
console.log("Setting up vscode host providers...")
|
||||
|
||||
const createWebview = function (type: WebviewProviderType) {
|
||||
return new VscodeWebviewProvider(context, type)
|
||||
}
|
||||
const createDiffView = function () {
|
||||
return new VscodeDiffViewProvider()
|
||||
}
|
||||
const createWebview = (type: WebviewProviderType) => new VscodeWebviewProvider(context, type)
|
||||
const createDiffView = () => new VscodeDiffViewProvider()
|
||||
const outputChannel = vscode.window.createOutputChannel("Cline")
|
||||
context.subscriptions.push(outputChannel)
|
||||
|
||||
@@ -672,12 +665,13 @@ function maybeSetupHostProviders(context: ExtensionContext) {
|
||||
|
||||
// This method is called when your extension is deactivated
|
||||
export async function deactivate() {
|
||||
PostHogClientProvider.getInstance().dispose()
|
||||
|
||||
// Dispose all webview instances
|
||||
await WebviewProvider.disposeAllInstances()
|
||||
|
||||
// Clean up test mode
|
||||
cleanupTestMode()
|
||||
await posthogClientProvider.shutdown()
|
||||
|
||||
Logger.log("Cline extension deactivated")
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { fileExistsAtPath } from "@utils/fs"
|
||||
import fs from "fs/promises"
|
||||
import { globby } from "globby"
|
||||
import * as path from "path"
|
||||
import simpleGit, { SimpleGit } from "simple-git"
|
||||
import { fileExistsAtPath } from "@utils/fs"
|
||||
import simpleGit, { type SimpleGit } from "simple-git"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { getLfsPatterns, writeExcludesFile } from "./CheckpointExclusions"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
|
||||
interface CheckpointAddResult {
|
||||
success: boolean
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import fs from "fs/promises"
|
||||
import * as path from "path"
|
||||
import simpleGit from "simple-git"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { GitOperations } from "./CheckpointGitOperations"
|
||||
import { getShadowGitPath, getWorkingDirectory, hashWorkingDir } from "./CheckpointUtils"
|
||||
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import vscode from "vscode"
|
||||
import { clineEnvConfig } from "@/config"
|
||||
import { Controller } from "@/core/controller"
|
||||
import { getRequestRegistry, type StreamingResponseHandler } from "@/core/controller/grpc-handler"
|
||||
import { storeSecret } from "@/core/storage/state"
|
||||
import { telemetryService } from "@services/posthog/telemetry/TelemetryService"
|
||||
import { featureFlagsService, telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { AuthState, UserInfo } from "@shared/proto/cline/account"
|
||||
import { type EmptyRequest, String } from "@shared/proto/cline/common"
|
||||
import { AuthHandler } from "@/hosts/external/AuthHandler"
|
||||
import { FirebaseAuthProvider } from "./providers/FirebaseAuthProvider"
|
||||
import { openExternal } from "@/utils/env"
|
||||
import { FEATURE_FLAGS } from "@/shared/services/feature-flags/feature-flags"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
|
||||
const DefaultClineAccountURI = `${clineEnvConfig.appBaseUrl}/auth`
|
||||
@@ -234,12 +232,7 @@ export class AuthService {
|
||||
this._clineAuthInfo = await this._provider.provider.signIn(this._controller, token, provider)
|
||||
this._authenticated = true
|
||||
|
||||
if (this._clineAuthInfo) {
|
||||
telemetryService.identifyAccount(this._clineAuthInfo.userInfo)
|
||||
}
|
||||
|
||||
await this.sendAuthStatusUpdate()
|
||||
// return this._clineAuthInfo
|
||||
} catch (error) {
|
||||
console.error("Error signing in with custom token:", error)
|
||||
throw error
|
||||
@@ -267,7 +260,6 @@ export class AuthService {
|
||||
this._clineAuthInfo = await this._provider.provider.retrieveClineAuthInfo(this._controller)
|
||||
if (this._clineAuthInfo) {
|
||||
this._authenticated = true
|
||||
telemetryService.identifyAccount(this._clineAuthInfo.userInfo)
|
||||
await this.sendAuthStatusUpdate()
|
||||
} else {
|
||||
console.warn("No user found after restoring auth token")
|
||||
@@ -332,6 +324,15 @@ export class AuthService {
|
||||
false, // Not the last message
|
||||
)
|
||||
|
||||
// Identify the user in telemetry if available
|
||||
// Fetch the feature flags for the user
|
||||
if (this._clineAuthInfo?.userInfo?.id) {
|
||||
telemetryService.identifyAccount(this._clineAuthInfo.userInfo)
|
||||
for (const flag of Object.values(FEATURE_FLAGS)) {
|
||||
await featureFlagsService?.isFeatureFlagEnabled(flag)
|
||||
}
|
||||
}
|
||||
|
||||
// Update the state in the webview
|
||||
if (controller) {
|
||||
await controller.postStateToWebview()
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { getSecret, storeSecret } from "@/core/storage/state"
|
||||
import { ErrorService } from "@/services/error/ErrorService"
|
||||
import { errorService } from "@services/posthog/PostHogClientProvider"
|
||||
import axios from "axios"
|
||||
import { initializeApp } from "firebase/app"
|
||||
import { GithubAuthProvider, GoogleAuthProvider, User, getAuth, signInWithCredential } from "firebase/auth"
|
||||
import { ExtensionContext } from "vscode"
|
||||
import { ClineAccountUserInfo, ClineAuthInfo } from "../AuthService"
|
||||
import { GithubAuthProvider, GoogleAuthProvider, getAuth, type OAuthCredential, signInWithCredential, User } from "firebase/auth"
|
||||
import { jwtDecode } from "jwt-decode"
|
||||
import type { ExtensionContext } from "vscode"
|
||||
import { clineEnvConfig } from "@/config"
|
||||
import type { ClineAccountUserInfo, ClineAuthInfo } from "../AuthService"
|
||||
import { Controller } from "@/core/controller"
|
||||
|
||||
export class FirebaseAuthProvider {
|
||||
@@ -90,8 +89,8 @@ export class FirebaseAuthProvider {
|
||||
// return userCredential.user
|
||||
} catch (error) {
|
||||
console.error("Firebase restore token error", error)
|
||||
ErrorService.logMessage("Firebase restore token error", "error")
|
||||
ErrorService.logException(error)
|
||||
errorService.logMessage("Firebase restore token error", "error")
|
||||
errorService.logException(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -103,7 +102,7 @@ export class FirebaseAuthProvider {
|
||||
*/
|
||||
async signIn(controller: Controller, token: string, provider: string): Promise<ClineAuthInfo | null> {
|
||||
try {
|
||||
let credential
|
||||
let credential: OAuthCredential
|
||||
switch (provider) {
|
||||
case "google":
|
||||
credential = GoogleAuthProvider.credential(token)
|
||||
@@ -126,16 +125,16 @@ export class FirebaseAuthProvider {
|
||||
try {
|
||||
controller.cacheService.setSecret("clineAccountId", userCredential.refreshToken)
|
||||
} catch (error) {
|
||||
ErrorService.logMessage("Firebase store token error", "error")
|
||||
ErrorService.logException(error)
|
||||
errorService.logMessage("Firebase store token error", "error")
|
||||
errorService.logException(error)
|
||||
throw error
|
||||
}
|
||||
|
||||
// userCredential = await this._signInWithCredential(context, credential)
|
||||
return await this.retrieveClineAuthInfo(controller)
|
||||
} catch (error) {
|
||||
ErrorService.logMessage("Firebase sign-in error", "error")
|
||||
ErrorService.logException(error)
|
||||
errorService.logMessage("Firebase sign-in error", "error")
|
||||
errorService.logException(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import { BrowserSettings } from "@shared/BrowserSettings"
|
||||
import { discoverChromeInstances, testBrowserConnection, isPortOpen } from "./BrowserDiscovery"
|
||||
import * as chromeLauncher from "chrome-launcher"
|
||||
import { Controller } from "@core/controller"
|
||||
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import os from "os"
|
||||
|
||||
interface PCRStats {
|
||||
@@ -88,7 +88,10 @@ export class BrowserSession {
|
||||
// First check browserSettings (from UI, stored in global state)
|
||||
await this.migrateChromeExecutablePathSetting()
|
||||
if (this.browserSettings.chromeExecutablePath && (await fileExistsAtPath(this.browserSettings.chromeExecutablePath))) {
|
||||
return { path: this.browserSettings.chromeExecutablePath, isBundled: false }
|
||||
return {
|
||||
path: this.browserSettings.chromeExecutablePath,
|
||||
isBundled: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Then try to find system Chrome
|
||||
@@ -554,8 +557,8 @@ export class BrowserSession {
|
||||
const minStableSizeIterations = 3
|
||||
|
||||
while (checkCounts++ <= maxChecks) {
|
||||
let html = await page.content()
|
||||
let currentHTMLSize = html.length
|
||||
const html = await page.content()
|
||||
const currentHTMLSize = html.length
|
||||
|
||||
// let bodyHTMLSize = await page.evaluate(() => document.body.innerHTML.length)
|
||||
console.info("last: ", lastHTMLSize, " <> curr: ", currentHTMLSize)
|
||||
|
||||
@@ -1,103 +1,55 @@
|
||||
import * as Sentry from "@sentry/browser"
|
||||
import * as vscode from "vscode"
|
||||
import { telemetryService } from "../posthog/telemetry/TelemetryService"
|
||||
import * as pkg from "../../../package.json"
|
||||
import type { PostHogClientProvider } from "../posthog/PostHogClientProvider"
|
||||
import { ClineError } from "./ClineError"
|
||||
|
||||
let telemetryLevel = vscode.workspace.getConfiguration("telemetry").get<string>("telemetryLevel", "all")
|
||||
let isTelemetryEnabled = ["all", "error"].includes(telemetryLevel)
|
||||
|
||||
vscode.workspace.onDidChangeConfiguration(() => {
|
||||
telemetryLevel = vscode.workspace.getConfiguration("telemetry").get<string>("telemetryLevel", "all")
|
||||
isTelemetryEnabled = ["all", "error"].includes(telemetryLevel)
|
||||
ErrorService.toggleEnabled(isTelemetryEnabled)
|
||||
if (isTelemetryEnabled) {
|
||||
ErrorService.setLevel(telemetryLevel as "error" | "all")
|
||||
}
|
||||
})
|
||||
|
||||
const isDev = process.env.IS_DEV === "true"
|
||||
|
||||
export class ErrorService {
|
||||
private static serviceEnabled: boolean
|
||||
private static serviceLevel: string
|
||||
private posthogProvider: PostHogClientProvider
|
||||
|
||||
static initialize() {
|
||||
// Initialize sentry
|
||||
Sentry.init({
|
||||
dsn: "https://7936780e3f0f0290fcf8d4a395c249b7@o4509028819664896.ingest.us.sentry.io/4509052955983872",
|
||||
environment: process.env.NODE_ENV,
|
||||
release: `cline@${pkg.version}`,
|
||||
integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration()],
|
||||
beforeSend(event) {
|
||||
// TelemetryService keeps track of whether the user has opted in to telemetry/error reporting
|
||||
const isUserManuallyOptedIn = telemetryService.isTelemetryEnabled()
|
||||
if (isUserManuallyOptedIn && ErrorService.isEnabled() && !isDev) {
|
||||
return event
|
||||
}
|
||||
return null
|
||||
},
|
||||
constructor(posthogProvider: PostHogClientProvider, _distinctId: string) {
|
||||
this.posthogProvider = posthogProvider
|
||||
}
|
||||
|
||||
public logException(error: Error | ClineError): void {
|
||||
const errorDetails = {
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
name: error.name,
|
||||
extension_version: pkg.version,
|
||||
is_dev: isDev,
|
||||
}
|
||||
|
||||
if (error instanceof ClineError) {
|
||||
Object.assign(errorDetails, {
|
||||
modelId: error.modelId,
|
||||
providerId: error.providerId,
|
||||
serialized_error: error.serialize(),
|
||||
})
|
||||
}
|
||||
|
||||
this.posthogProvider.log("extension.error", {
|
||||
error_type: "exception",
|
||||
...errorDetails,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
|
||||
ErrorService.toggleEnabled(true)
|
||||
ErrorService.setLevel("error")
|
||||
console.error("[ErrorService] Logging", error)
|
||||
}
|
||||
|
||||
static toggleEnabled(state: boolean) {
|
||||
if (state === false) {
|
||||
ErrorService.serviceEnabled = false
|
||||
return
|
||||
}
|
||||
// If we are trying to enable the service, check that we are allowed to.
|
||||
if (isTelemetryEnabled) {
|
||||
ErrorService.serviceEnabled = true
|
||||
}
|
||||
public logMessage(message: string, level: "error" | "warning" | "log" | "debug" | "info" = "log"): void {
|
||||
this.posthogProvider.log("extension.message", {
|
||||
message: message.substring(0, 500),
|
||||
level,
|
||||
extension_version: pkg.version,
|
||||
is_dev: isDev,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
static setLevel(level: "error" | "all") {
|
||||
switch (telemetryLevel) {
|
||||
case "error": {
|
||||
if (level === "error") {
|
||||
ErrorService.serviceLevel = level
|
||||
}
|
||||
break
|
||||
}
|
||||
default: {
|
||||
ErrorService.serviceLevel = level
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static logException(error: Error | ClineError): void {
|
||||
// Don't log if telemetry is off
|
||||
const isUserManuallyOptedIn = telemetryService.isTelemetryEnabled()
|
||||
if (!isUserManuallyOptedIn || !ErrorService.isEnabled()) {
|
||||
return
|
||||
}
|
||||
// Log the error to Sentry
|
||||
Sentry.captureException(error)
|
||||
}
|
||||
|
||||
static logMessage(message: string, level: "error" | "warning" | "log" | "debug" | "info" = "log"): void {
|
||||
// Don't log if telemetry is off
|
||||
const isUserManuallyOptedIn = telemetryService.isTelemetryEnabled()
|
||||
if (!isUserManuallyOptedIn || !ErrorService.isEnabled()) {
|
||||
return
|
||||
}
|
||||
if (ErrorService.serviceLevel === "error" && level === "error") {
|
||||
// Log the message if allowed
|
||||
Sentry.captureMessage(message, { level })
|
||||
return
|
||||
}
|
||||
// Log the message if allowed
|
||||
Sentry.captureMessage(message, { level })
|
||||
}
|
||||
|
||||
static isEnabled(): boolean {
|
||||
return ErrorService.serviceEnabled
|
||||
}
|
||||
|
||||
static toClineError(rawError: any, modelId?: string, providerId?: string): ClineError {
|
||||
return ClineError.transform(rawError, modelId, providerId)
|
||||
public toClineError(rawError: unknown, modelId?: string, providerId?: string): ClineError {
|
||||
const transformed = ClineError.transform(rawError, modelId, providerId)
|
||||
this.logException(transformed)
|
||||
return transformed
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { ErrorService } from "../error/ErrorService"
|
||||
import { errorService } from "../posthog/PostHogClientProvider"
|
||||
|
||||
/**
|
||||
* Simple logging utility for the extension's backend code.
|
||||
*/
|
||||
export class Logger {
|
||||
public readonly channelName = "Cline Dev Logger"
|
||||
static error(message: string, error?: Error) {
|
||||
Logger.#output("ERROR", message, error)
|
||||
ErrorService.logMessage(message, "error")
|
||||
error && ErrorService.logException(error)
|
||||
errorService.logMessage(message, "error")
|
||||
error && errorService.logException(error)
|
||||
}
|
||||
static warn(message: string) {
|
||||
Logger.#output("WARN", message)
|
||||
ErrorService.logMessage(message, "warning")
|
||||
errorService.logMessage(message, "warning")
|
||||
}
|
||||
static log(message: string) {
|
||||
Logger.#output("LOG", message)
|
||||
|
||||
@@ -1,31 +1,149 @@
|
||||
import { PostHog } from "posthog-node"
|
||||
import { v4 as uuidv4 } from "uuid"
|
||||
import * as vscode from "vscode"
|
||||
import { posthogConfig } from "../../shared/services/config/posthog-config"
|
||||
import type { ClineAccountUserInfo } from "../auth/AuthService"
|
||||
import { ErrorService } from "../error/ErrorService"
|
||||
import { FeatureFlagsService } from "./feature-flags/FeatureFlagsService"
|
||||
import { TelemetryService } from "./telemetry/TelemetryService"
|
||||
|
||||
class PostHogClientProvider {
|
||||
private static instance: PostHogClientProvider
|
||||
private client: PostHog
|
||||
const ENV_ID = vscode?.env?.machineId ?? process?.env?.UUID ?? uuidv4()
|
||||
|
||||
private constructor() {
|
||||
interface TelemetrySettings {
|
||||
cline: boolean
|
||||
host: boolean
|
||||
level?: "all" | "off" | "error" | "crash"
|
||||
}
|
||||
|
||||
export class PostHogClientProvider {
|
||||
private static _instance: PostHogClientProvider | null = null
|
||||
|
||||
public static getInstance(id?: string): PostHogClientProvider {
|
||||
if (!PostHogClientProvider._instance) {
|
||||
PostHogClientProvider._instance = new PostHogClientProvider(id)
|
||||
}
|
||||
return PostHogClientProvider._instance
|
||||
}
|
||||
|
||||
protected telemetrySettings: TelemetrySettings = {
|
||||
cline: true,
|
||||
host: true,
|
||||
level: "all",
|
||||
}
|
||||
|
||||
public readonly client: PostHog
|
||||
|
||||
public readonly featureFlags: FeatureFlagsService
|
||||
public readonly telemetry: TelemetryService
|
||||
public readonly error: ErrorService
|
||||
|
||||
private constructor(public distinctId = ENV_ID) {
|
||||
// Initialize PostHog client
|
||||
this.client = new PostHog(posthogConfig.apiKey, {
|
||||
host: posthogConfig.host,
|
||||
enableExceptionAutocapture: false,
|
||||
enableExceptionAutocapture: true,
|
||||
})
|
||||
|
||||
vscode.env.onDidChangeTelemetryEnabled((isTelemetryEnabled) => {
|
||||
this.telemetrySettings.host = isTelemetryEnabled
|
||||
})
|
||||
|
||||
if (vscode?.env?.isTelemetryEnabled === false) {
|
||||
this.telemetrySettings.host = false
|
||||
}
|
||||
|
||||
const config = vscode.workspace.getConfiguration("cline")
|
||||
if (config.get("telemetrySetting") === "disabled") {
|
||||
this.telemetrySettings.cline = false
|
||||
}
|
||||
|
||||
this.telemetrySettings.level = this.telemetryLevel
|
||||
|
||||
// Initialize services
|
||||
this.telemetry = new TelemetryService(this)
|
||||
this.error = new ErrorService(this, this.distinctId)
|
||||
this.featureFlags = new FeatureFlagsService(
|
||||
(flag: string) => this.client.getFeatureFlag(flag, this.distinctId),
|
||||
(flag: string) => this.client.getFeatureFlagPayload(flag, this.distinctId),
|
||||
)
|
||||
}
|
||||
|
||||
private get isTelemetryEnabled(): boolean {
|
||||
return this.telemetrySettings.cline && this.telemetrySettings.host
|
||||
}
|
||||
|
||||
/** Whether telemetry is currently enabled based on user and VSCode settings */
|
||||
private get telemetryLevel(): TelemetrySettings["level"] {
|
||||
if (!vscode?.env?.isTelemetryEnabled) {
|
||||
return "off"
|
||||
}
|
||||
const config = vscode.workspace.getConfiguration("telemetry")
|
||||
return config?.get<TelemetrySettings["level"]>("telemetryLevel") || "all"
|
||||
}
|
||||
|
||||
public toggleOptIn(optIn: boolean): void {
|
||||
if (optIn && !this.telemetrySettings.cline) {
|
||||
this.client.optIn()
|
||||
}
|
||||
if (!optIn && this.telemetrySettings.cline) {
|
||||
this.client.optOut()
|
||||
}
|
||||
this.telemetrySettings.cline = optIn
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies the accounts user
|
||||
* If userInfo is provided, it will use that to identify the user.
|
||||
* Otherwise, it will use the DISTINCT_ID as the distinct ID.
|
||||
* @param userInfo The user's information
|
||||
*/
|
||||
public identifyAccount(userInfo?: ClineAccountUserInfo, properties: Record<string, unknown> = {}): void {
|
||||
if (!this.isTelemetryEnabled) {
|
||||
return
|
||||
}
|
||||
if (userInfo && userInfo?.id !== this.distinctId) {
|
||||
this.client.identify({
|
||||
distinctId: userInfo.id,
|
||||
properties: {
|
||||
uuid: userInfo.id,
|
||||
email: userInfo.email,
|
||||
name: userInfo.displayName,
|
||||
...properties,
|
||||
alias: this.distinctId,
|
||||
},
|
||||
})
|
||||
this.distinctId = userInfo.id
|
||||
}
|
||||
}
|
||||
|
||||
public log(event: string, properties?: Record<string, unknown>): void {
|
||||
if (!this.isTelemetryEnabled || this.telemetryLevel === "off") {
|
||||
return
|
||||
}
|
||||
// Filter events based on telemetry level
|
||||
if (this.telemetryLevel === "error") {
|
||||
if (!event.includes("error")) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
this.client.capture({
|
||||
distinctId: this.distinctId,
|
||||
event,
|
||||
properties,
|
||||
})
|
||||
}
|
||||
|
||||
public static getInstance(): PostHogClientProvider {
|
||||
if (!PostHogClientProvider.instance) {
|
||||
PostHogClientProvider.instance = new PostHogClientProvider()
|
||||
}
|
||||
return PostHogClientProvider.instance
|
||||
}
|
||||
|
||||
public getClient(): PostHog {
|
||||
return this.client
|
||||
}
|
||||
|
||||
public async shutdown(): Promise<void> {
|
||||
await this.client.shutdown()
|
||||
public dispose(): void {
|
||||
this.client.shutdown().catch((error) => console.error("Error shutting down PostHog client:", error))
|
||||
}
|
||||
}
|
||||
|
||||
export const posthogClientProvider = PostHogClientProvider.getInstance()
|
||||
const getFeatureFlagsService = (): FeatureFlagsService => PostHogClientProvider.getInstance().featureFlags
|
||||
const getErrorService = (): ErrorService => PostHogClientProvider.getInstance().error
|
||||
const getTelemetryService = (): TelemetryService => PostHogClientProvider.getInstance().telemetry
|
||||
|
||||
// Service accessors
|
||||
export const featureFlagsService = getFeatureFlagsService()
|
||||
export const errorService = getErrorService()
|
||||
export const telemetryService = getTelemetryService()
|
||||
@@ -1,40 +1,45 @@
|
||||
import { PostHog } from "posthog-node"
|
||||
import { posthogClientProvider } from "../PostHogClientProvider"
|
||||
|
||||
class FeatureFlagsService {
|
||||
private static instance: FeatureFlagsService
|
||||
private readonly client: PostHog
|
||||
|
||||
private constructor() {
|
||||
// Get the shared client
|
||||
this.client = posthogClientProvider.getClient()
|
||||
}
|
||||
|
||||
public static getInstance(): FeatureFlagsService {
|
||||
if (!FeatureFlagsService.instance) {
|
||||
FeatureFlagsService.instance = new FeatureFlagsService()
|
||||
}
|
||||
return FeatureFlagsService.instance
|
||||
/**
|
||||
* FeatureFlagsService provides feature flag functionality that works independently
|
||||
* of telemetry settings. Feature flags are always available to ensure proper
|
||||
* functionality of the extension regardless of user's telemetry preferences.
|
||||
*/
|
||||
export class FeatureFlagsService {
|
||||
public constructor(
|
||||
private readonly getFeatureFlag: (flag: string) => Promise<boolean | string | undefined>,
|
||||
private readonly getFeatureFlagPayload: (flag: string) => Promise<unknown>,
|
||||
) {
|
||||
console.log("[FeatureFlagsService] Initialized with distinctId:")
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a feature flag is enabled
|
||||
* This method works regardless of telemetry settings to ensure feature flags
|
||||
* can control extension behavior independently of user privacy preferences.
|
||||
*
|
||||
* @param flagName The feature flag key
|
||||
* @returns Boolean indicating if the feature is enabled
|
||||
*/
|
||||
public async isFeatureFlagEnabled(flagName: string): Promise<boolean> {
|
||||
try {
|
||||
const payload = await this.client.getFeatureFlagPayload(flagName, "_irrelevant_" /* optional params */)
|
||||
if (payload && typeof payload === "object" && "enabled" in payload) {
|
||||
return Boolean(payload.enabled)
|
||||
}
|
||||
console.warn(`Feature flag ${flagName} not found or missing enabled property.`)
|
||||
return false
|
||||
const flagEnabled = await this.getFeatureFlag(flagName)
|
||||
return flagEnabled === true
|
||||
} catch (error) {
|
||||
console.error(`Error checking if feature flag ${flagName} is enabled:`, error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const featureFlagsService = FeatureFlagsService.getInstance()
|
||||
/**
|
||||
* Get the feature flag payload for advanced use cases
|
||||
* @param flagName The feature flag key
|
||||
* @returns The feature flag payload or null if not found
|
||||
*/
|
||||
public async getPayload(flagName: string): Promise<unknown> {
|
||||
try {
|
||||
return await this.getFeatureFlagPayload(flagName)
|
||||
} catch (error) {
|
||||
console.error(`Error retrieving feature flag payload for ${flagName}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PostHog } from "posthog-node"
|
||||
import * as vscode from "vscode"
|
||||
import { version as extensionVersion } from "../../../../package.json"
|
||||
import { HostProvider } from "@hosts/host-provider"
|
||||
@@ -6,7 +5,7 @@ import { ShowMessageType } from "@shared/proto/host/window"
|
||||
|
||||
import type { TaskFeedbackType } from "@shared/WebviewMessage"
|
||||
import type { BrowserSettings } from "@shared/BrowserSettings"
|
||||
import { posthogClientProvider } from "../PostHogClientProvider"
|
||||
import type { PostHogClientProvider } from "../PostHogClientProvider"
|
||||
import { Mode } from "@/shared/storage/types"
|
||||
import { ClineAccountUserInfo } from "@/services/auth/AuthService"
|
||||
|
||||
@@ -28,7 +27,7 @@ type TelemetryCategory = "checkpoints" | "browser"
|
||||
*/
|
||||
const MAX_ERROR_MESSAGE_LENGTH = 500
|
||||
|
||||
class TelemetryService {
|
||||
export class TelemetryService {
|
||||
// Map to control specific telemetry categories (event types)
|
||||
private telemetryCategoryEnabled: Map<TelemetryCategory, boolean> = new Map([
|
||||
["checkpoints", false], // Checkpoints telemetry disabled
|
||||
@@ -41,6 +40,7 @@ class TelemetryService {
|
||||
|
||||
USER: {
|
||||
OPT_OUT: "user.opt_out",
|
||||
TELEMETRY_ENABLED: "user.telemetry_enabled",
|
||||
EXTENSION_ACTIVATED: "user.extension_activated",
|
||||
},
|
||||
TASK: {
|
||||
@@ -94,31 +94,18 @@ class TelemetryService {
|
||||
},
|
||||
}
|
||||
|
||||
/** Singleton instance of the TelemetryService */
|
||||
private static instance: TelemetryService
|
||||
/** PostHog client instance for sending analytics events */
|
||||
private client: PostHog
|
||||
/** Unique identifier for the current VSCode instance */
|
||||
public distinctId: string = vscode.env.machineId
|
||||
/** Whether telemetry is currently enabled based on user and VSCode settings */
|
||||
private telemetryEnabled: boolean = false
|
||||
/** Current version of the extension */
|
||||
private readonly version: string = extensionVersion
|
||||
/** Whether the extension is running in development mode */
|
||||
private readonly isDev = process.env.IS_DEV
|
||||
|
||||
/**
|
||||
* Private constructor to enforce singleton pattern
|
||||
* Initializes PostHog client with configuration
|
||||
* Constructor that accepts a PostHogClientProvider instance
|
||||
* @param provider PostHogClientProvider instance for sending analytics events
|
||||
*/
|
||||
private constructor() {
|
||||
this.client = posthogClientProvider.getClient()
|
||||
}
|
||||
|
||||
private setDistinctId(installId: string) {
|
||||
if (this.distinctId === "someValue.machineId") {
|
||||
this.distinctId = installId
|
||||
}
|
||||
public constructor(private provider: PostHogClientProvider) {
|
||||
this.capture({ event: TelemetryService.EVENTS.USER.TELEMETRY_ENABLED })
|
||||
console.info("[TelemetryService] Initialized with PostHogClientProvider")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,13 +115,9 @@ class TelemetryService {
|
||||
*/
|
||||
public async updateTelemetryState(didUserOptIn: boolean): Promise<void> {
|
||||
// First check global telemetry level - telemetry should only be enabled when level is "all"
|
||||
const telemetryLevel = vscode.workspace.getConfiguration("telemetry").get<string>("telemetryLevel", "all")
|
||||
const globalTelemetryEnabled = telemetryLevel === "all"
|
||||
|
||||
// We only enable telemetry if global vscode telemetry is enabled
|
||||
if (globalTelemetryEnabled) {
|
||||
this.telemetryEnabled = didUserOptIn
|
||||
} else {
|
||||
if (!vscode.env.isTelemetryEnabled) {
|
||||
// Only show warning if user has opted in to Cline telemetry but VS Code telemetry is disabled
|
||||
if (didUserOptIn) {
|
||||
void HostProvider.window
|
||||
@@ -152,34 +135,9 @@ class TelemetryService {
|
||||
}
|
||||
})
|
||||
}
|
||||
this.telemetryEnabled = false
|
||||
}
|
||||
|
||||
// Update PostHog client state based on telemetry preference
|
||||
if (this.telemetryEnabled) {
|
||||
this.client.optIn()
|
||||
this.client.identify({ distinctId: this.distinctId })
|
||||
} else {
|
||||
this.client.capture({
|
||||
distinctId: this.distinctId,
|
||||
event: TelemetryService.EVENTS.USER.OPT_OUT,
|
||||
properties: this.addProperties({}),
|
||||
})
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000)) // Delay 1 second before opting out
|
||||
this.client.optOut()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates the singleton instance of TelemetryService
|
||||
* @returns The TelemetryService instance
|
||||
*/
|
||||
public static getInstance(): TelemetryService {
|
||||
if (!TelemetryService.instance) {
|
||||
TelemetryService.instance = new TelemetryService()
|
||||
}
|
||||
return TelemetryService.instance
|
||||
this.provider.toggleOptIn(didUserOptIn)
|
||||
}
|
||||
|
||||
private addProperties(properties: any): any {
|
||||
@@ -194,28 +152,16 @@ class TelemetryService {
|
||||
* Captures a telemetry event if telemetry is enabled
|
||||
* @param event The event to capture with its properties
|
||||
*/
|
||||
public capture(event: { event: string; properties?: any }): void {
|
||||
if (!this.telemetryEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
public capture(event: { event: string; properties?: unknown }): void {
|
||||
const propertiesWithVersion = this.addProperties(event.properties)
|
||||
|
||||
const capturedEvent = {
|
||||
event: event.event,
|
||||
properties: propertiesWithVersion,
|
||||
}
|
||||
|
||||
this.client.capture({ ...capturedEvent, distinctId: this.distinctId })
|
||||
// Use the provider's log method instead of direct client capture
|
||||
this.provider.log(event.event, propertiesWithVersion)
|
||||
}
|
||||
|
||||
public captureExtensionActivated(installId: string) {
|
||||
this.setDistinctId(installId)
|
||||
|
||||
if (this.telemetryEnabled) {
|
||||
this.client.identify({ distinctId: this.distinctId })
|
||||
this.client.capture({ distinctId: this.distinctId, event: TelemetryService.EVENTS.USER.EXTENSION_ACTIVATED })
|
||||
}
|
||||
public captureExtensionActivated() {
|
||||
// Use provider's log method for the activation event
|
||||
this.provider.log(TelemetryService.EVENTS.USER.EXTENSION_ACTIVATED)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,24 +169,10 @@ class TelemetryService {
|
||||
* @param userInfo The user's information
|
||||
*/
|
||||
public identifyAccount(userInfo: ClineAccountUserInfo) {
|
||||
if (!this.telemetryEnabled) {
|
||||
return
|
||||
}
|
||||
const propertiesWithVersion = this.addProperties({})
|
||||
|
||||
if (!this.client) {
|
||||
console.warn("Telemetry client is not initialized. Skipping identifyAccount.")
|
||||
return
|
||||
}
|
||||
|
||||
this.client.identify({
|
||||
distinctId: userInfo.id,
|
||||
properties: {
|
||||
uuid: userInfo.id,
|
||||
email: userInfo.email,
|
||||
name: userInfo.displayName,
|
||||
...this.addProperties({}),
|
||||
},
|
||||
})
|
||||
// Use the provider's log method instead of direct client capture
|
||||
this.provider.identifyAccount(userInfo, propertiesWithVersion)
|
||||
}
|
||||
|
||||
// Task events
|
||||
@@ -306,7 +238,7 @@ class TelemetryService {
|
||||
return
|
||||
}
|
||||
|
||||
const properties: Record<string, any> = {
|
||||
const properties: Record<string, unknown> = {
|
||||
taskId,
|
||||
provider,
|
||||
model,
|
||||
@@ -361,7 +293,10 @@ class TelemetryService {
|
||||
* @param feedbackType The type of feedback ("thumbs_up" or "thumbs_down")
|
||||
*/
|
||||
public captureTaskFeedback(taskId: string, feedbackType: TaskFeedbackType) {
|
||||
console.info("TelemetryService: Capturing task feedback", { taskId, feedbackType })
|
||||
console.info("TelemetryService: Capturing task feedback", {
|
||||
taskId,
|
||||
feedbackType,
|
||||
})
|
||||
this.capture({
|
||||
event: TelemetryService.EVENTS.TASK.FEEDBACK,
|
||||
properties: {
|
||||
@@ -542,7 +477,7 @@ class TelemetryService {
|
||||
action?: string
|
||||
url?: string
|
||||
isRemote?: boolean
|
||||
[key: string]: any
|
||||
[key: string]: unknown
|
||||
},
|
||||
) {
|
||||
if (!this.isCategoryEnabled("browser")) {
|
||||
@@ -678,14 +613,6 @@ class TelemetryService {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if telemetry is enabled
|
||||
* @returns Boolean indicating whether telemetry is enabled
|
||||
*/
|
||||
public isTelemetryEnabled(): boolean {
|
||||
return this.telemetryEnabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a specific telemetry category is enabled
|
||||
* @param category The telemetry category to check
|
||||
@@ -695,10 +622,4 @@ class TelemetryService {
|
||||
// Default to true if category has not been explicitly configured
|
||||
return this.telemetryCategoryEnabled.get(category) ?? true
|
||||
}
|
||||
|
||||
public async shutdown(): Promise<void> {
|
||||
await this.client.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
export const telemetryService = TelemetryService.getInstance()
|
||||
@@ -1,6 +1,7 @@
|
||||
export const FEATURE_FLAGS = {
|
||||
CUSTOM_INSTRUCTIONS: "custom-instructions",
|
||||
// Further flags here
|
||||
DEV_ENV_POSTHOG: "dev-env-posthog",
|
||||
} as const
|
||||
|
||||
export type FeatureFlag = (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS]
|
||||
@@ -1,38 +1,48 @@
|
||||
import { useEffect, type ReactNode } from "react"
|
||||
import { PostHogProvider } from "posthog-js/react"
|
||||
import posthog from "posthog-js"
|
||||
import { posthogConfig } from "@shared/services/config/posthog-config"
|
||||
import posthog from "posthog-js"
|
||||
import { PostHogProvider } from "posthog-js/react"
|
||||
import { type ReactNode, useEffect, useState } from "react"
|
||||
import { useExtensionState } from "./context/ExtensionStateContext"
|
||||
|
||||
export function CustomPostHogProvider({ children }: { children: ReactNode }) {
|
||||
const { telemetrySetting, distinctId, version } = useExtensionState()
|
||||
const isTelemetryEnabled = telemetrySetting !== "disabled"
|
||||
const { telemetrySetting, distinctId, version, userInfo } = useExtensionState()
|
||||
|
||||
// NOTE: This is a hack to stop recording webview click events temporarily.
|
||||
// Remove this to re-enable.
|
||||
const temporaryDisabled = true
|
||||
// const isTelemetryEnabled = telemetrySetting !== "disabled";
|
||||
const isTelemetryEnabled = false
|
||||
const [isActive, setIsActive] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (temporaryDisabled) {
|
||||
if (isActive || !isTelemetryEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
posthog.init(posthogConfig.apiKey, {
|
||||
api_host: posthogConfig.host,
|
||||
ui_host: posthogConfig.uiHost,
|
||||
disable_session_recording: true,
|
||||
capture_pageview: false,
|
||||
capture_dead_clicks: true,
|
||||
// Feature flags should work regardless of telemetry opt-out
|
||||
advanced_disable_decide: false,
|
||||
// Autocapture should respect telemetry settings
|
||||
autocapture: false,
|
||||
})
|
||||
setIsActive(true)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (temporaryDisabled || distinctId.length === 0 || version.length === 0) {
|
||||
if (!isTelemetryEnabled || !isActive || !distinctId || !version) {
|
||||
return
|
||||
}
|
||||
|
||||
posthog.set_config({
|
||||
before_send: (payload: any) => {
|
||||
before_send: (payload) => {
|
||||
// Only filter out events if telemetry is disabled, but allow feature flag requests
|
||||
if (!isTelemetryEnabled && payload?.event !== "$feature_flag_called") {
|
||||
return null
|
||||
}
|
||||
|
||||
if (payload?.properties) {
|
||||
payload.properties.extension_version = version
|
||||
payload.properties.distinct_id = distinctId
|
||||
@@ -43,14 +53,20 @@ export function CustomPostHogProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const optedIn = posthog.has_opted_in_capturing()
|
||||
const optedOut = posthog.has_opted_out_capturing()
|
||||
|
||||
const args = {
|
||||
email: userInfo?.email,
|
||||
name: userInfo?.displayName,
|
||||
}
|
||||
if (isTelemetryEnabled && !optedIn) {
|
||||
posthog.opt_in_capturing()
|
||||
posthog.identify(distinctId)
|
||||
posthog.identify(distinctId, args)
|
||||
} else if (!isTelemetryEnabled && !optedOut) {
|
||||
// For feature flags to work, we need to identify the user even when telemetry is disabled
|
||||
posthog.identify(distinctId, args)
|
||||
// Then opt out of capturing other events
|
||||
posthog.opt_out_capturing()
|
||||
}
|
||||
}, [isTelemetryEnabled, distinctId, version])
|
||||
}, [isActive, isTelemetryEnabled, distinctId, version])
|
||||
|
||||
return <PostHogProvider client={posthog}>{children}</PostHogProvider>
|
||||
}
|
||||
@@ -1,23 +1,14 @@
|
||||
import { useExtensionState } from "@/context/ExtensionStateContext"
|
||||
import { useFeatureFlagPayload } from "posthog-js/react"
|
||||
import { useFeatureFlagEnabled } from "posthog-js/react"
|
||||
|
||||
export const useFeatureFlag = (flagName: string): boolean => {
|
||||
const { telemetrySetting } = useExtensionState()
|
||||
|
||||
try {
|
||||
const payload = useFeatureFlagPayload(flagName) as { enabled: boolean }
|
||||
if (payload && typeof payload === "object") {
|
||||
// Check if the enabled property exists and is a boolean
|
||||
if ("enabled" in payload && typeof payload.enabled === "boolean") {
|
||||
return payload.enabled
|
||||
}
|
||||
}
|
||||
|
||||
if (telemetrySetting === "enabled") {
|
||||
console.warn(`Feature flag ${flagName} not found or missing enabled property.`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error retrieving feature flag "${flagName}":`, error)
|
||||
/**
|
||||
* Hook to check feature flag status in the webview
|
||||
* Feature flags work independently of telemetry settings to ensure
|
||||
* proper extension functionality regardless of user privacy preferences
|
||||
*/
|
||||
export const useHasFeatureFlag = (flagName: string): boolean => {
|
||||
const flagEnabled = useFeatureFlagEnabled(flagName)
|
||||
if (flagEnabled && typeof flagEnabled === "boolean") {
|
||||
return flagEnabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in new issue
Block a user