diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 17217fc3..82491aa1 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -65,6 +65,7 @@ import { HistoryItem } from "@shared/HistoryItem" import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages" import { CLINE_MCP_TOOL_IDENTIFIER } from "@shared/mcp" import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message" +import type { Mode } from "@shared/storage/types" import { ClineDefaultTool } from "@shared/tools" import { ClineAskResponse } from "@shared/WebviewMessage" import { isClaude4PlusModelFamily, isGPT5ModelFamily, isLocalModel, isNextGenModelFamily } from "@utils/model-utils" @@ -539,7 +540,7 @@ export class Task { this.removeLastPartialMessageIfExistsWithType.bind(this), this.executeCommandTool.bind(this), () => this.checkpointManager?.doesLatestTaskCompletionHaveNewChanges() ?? Promise.resolve(false), - this.FocusChainManager?.updateFCListFromToolResponse.bind(this.FocusChainManager) || (async () => {}), + this.FocusChainManager?.updateFCListFromToolResponse.bind(this.FocusChainManager) || (async () => { }), this.switchToActModeCallback.bind(this), this.cancelTask, // Atomic hook state helpers for ToolExecutor @@ -795,8 +796,7 @@ export class Task { async sayAndCreateMissingParamError(toolName: ClineDefaultTool, paramName: string, relPath?: string) { await this.say( "error", - `Cline tried to use ${toolName}${ - relPath ? ` for '${relPath.toPosix()}'` : "" + `Cline tried to use ${toolName}${relPath ? ` for '${relPath.toPosix()}'` : "" } without value for required parameter '${paramName}'. Retrying...`, ) return formatResponse.toolError(formatResponse.missingToolParameterError(paramName)) @@ -1825,8 +1825,7 @@ export class Task { return [ true, formatResponse.toolResult( - `Command is still running in the user's terminal.${ - result.length > 0 ? `\nHere's the output so far:\n${result}` : "" + `Command is still running in the user's terminal.${result.length > 0 ? `\nHere's the output so far:\n${result}` : "" }\n\nThe user provided the following feedback:\n\n${userFeedback.text}\n`, userFeedback.images, fileContentString, @@ -1839,8 +1838,7 @@ export class Task { } else { return [ false, - `Command is still running in the user's terminal.${ - result.length > 0 ? `\nHere's the output so far:\n${result}` : "" + `Command is still running in the user's terminal.${result.length > 0 ? `\nHere's the output so far:\n${result}` : "" }\n\nYou will be updated on the terminal status and new output in the future.`, ] } @@ -2439,7 +2437,7 @@ export class Task { model.id, this.stateManager.getGlobalSettingsKey("mode"), ) - } catch {} + } catch { } } const modelInfo = { @@ -2670,7 +2668,9 @@ export class Task { content: userContent, }) - const currentMode = this.stateManager.getGlobalSettingsKey("mode") + const modeSetting = this.stateManager.getGlobalSettingsKey("mode") + const currentMode: Mode = modeSetting === "act" ? "act" : "plan" + telemetryService.captureConversationTurnEvent(this.ulid, providerId, model.id, "user", currentMode) // Capture task initialization timing telemetry for the first API request @@ -2723,10 +2723,9 @@ export class Task { type: "text", text: assistantMessage + - `\n\n[${ - cancelReason === "streaming_failed" - ? "Response interrupted by API Error" - : "Response interrupted by user" + `\n\n[${cancelReason === "streaming_failed" + ? "Response interrupted by API Error" + : "Response interrupted by user" }]`, }, ], @@ -2747,7 +2746,6 @@ export class Task { }) await this.messageStateHandler.saveClineMessagesAndUpdateHistory() - const currentMode = this.stateManager.getGlobalSettingsKey("mode") telemetryService.captureConversationTurnEvent( this.ulid, providerId, @@ -3460,7 +3458,7 @@ export class Task { await pWaitFor(() => busyTerminals.every((t) => !this.terminalManager.isProcessHot(t.id)), { interval: 100, timeout: 15_000, - }).catch(() => {}) + }).catch(() => { }) } this.taskState.didEditFile = false // reset, this lets us know when to wait for saved files to update terminals diff --git a/src/services/telemetry/TelemetryProviderFactory.ts b/src/services/telemetry/TelemetryProviderFactory.ts index cb883a72..014b3809 100644 --- a/src/services/telemetry/TelemetryProviderFactory.ts +++ b/src/services/telemetry/TelemetryProviderFactory.ts @@ -1,7 +1,7 @@ import { getValidOpenTelemetryConfig } from "@/shared/services/config/otel-config" import { isPostHogConfigValid, posthogConfig } from "@/shared/services/config/posthog-config" import { Logger } from "../logging/Logger" -import type { ITelemetryProvider } from "./providers/ITelemetryProvider" +import type { ITelemetryProvider, TelemetryProperties, TelemetrySettings } from "./providers/ITelemetryProvider" import { OpenTelemetryClientProvider } from "./providers/opentelemetry/OpenTelemetryClientProvider" import { OpenTelemetryTelemetryProvider } from "./providers/opentelemetry/OpenTelemetryTelemetryProvider" import { PostHogClientProvider } from "./providers/posthog/PostHogClientProvider" @@ -15,9 +15,10 @@ export type TelemetryProviderType = "posthog" | "no-op" | "opentelemetry" /** * Configuration for telemetry providers */ -export interface TelemetryProviderConfig { - type: TelemetryProviderType -} +export type TelemetryProviderConfig = + | { type: "posthog"; apiKey?: string; host?: string } + | { type: "opentelemetry"; enabled?: boolean } + | { type: "no-op" } /** * Factory class for creating telemetry providers @@ -27,17 +28,25 @@ export class TelemetryProviderFactory { /** * Creates multiple telemetry providers based on configuration * Supports dual tracking during transition period - * @returns Array of ITelemetryProvider instances */ public static async createProviders(): Promise { const configs = TelemetryProviderFactory.getDefaultConfigs() - const providers: ITelemetryProvider[] = await Promise.all(configs.map((c) => TelemetryProviderFactory.createProvider(c))) + const providers: ITelemetryProvider[] = [] - // Fallback to no-op if no providers available + for (const config of configs) { + try { + const provider = await TelemetryProviderFactory.createProvider(config) + providers.push(provider) + } catch (error) { + Logger.error(`Failed to create telemetry provider: ${config.type}`, error) + } + } + + // Always have at least a no-op provider if (providers.length === 0) { providers.push(new NoOpTelemetryProvider()) - Logger.info("TelemetryProviderFactory: Using NoOp provider (no valid configs)") } + Logger.info("TelemetryProviderFactory: Created providers - " + providers.map((p) => p.constructor.name).join(", ")) return providers } @@ -46,8 +55,6 @@ export class TelemetryProviderFactory { * Creates a single telemetry provider based on the provided configuration * @param config Configuration for the telemetry provider * @returns ITelemetryProvider instance - * @deprecated Use createProviders() for multi-provider support - * @deprecated Use createProviders() for multi-provider support */ private static async createProvider(config: TelemetryProviderConfig): Promise { switch (config.type) { @@ -68,11 +75,9 @@ export class TelemetryProviderFactory { return new NoOpTelemetryProvider() } case "no-op": + return new NoOpTelemetryProvider() default: - // Always fallback to NoOp provider. Only log error for unsupported types - if (config.type !== "no-op") { - console.error(`Unsupported telemetry provider type: ${config.type}`) - } + Logger.error(`Unsupported telemetry provider type: ${(config as { type?: string }).type ?? "unknown"}`) return new NoOpTelemetryProvider() } } @@ -80,17 +85,19 @@ export class TelemetryProviderFactory { /** * Gets the default telemetry provider configuration * @returns Default configuration using available providers - * @returns Default configuration using available providers */ public static getDefaultConfigs(): TelemetryProviderConfig[] { const configs: TelemetryProviderConfig[] = [] + if (isPostHogConfigValid(posthogConfig)) { configs.push({ type: "posthog", ...posthogConfig }) } + const otelConfig = getValidOpenTelemetryConfig() if (otelConfig) { configs.push({ type: "opentelemetry", ...otelConfig }) } + return configs.length > 0 ? configs : [{ type: "no-op" }] } } @@ -100,38 +107,59 @@ export class TelemetryProviderFactory { * or for testing purposes */ export class NoOpTelemetryProvider implements ITelemetryProvider { - public isOptIn = true + private isOptIn = true - public log(event: string, properties?: Record): void { - Logger.log(`[NoOpTelemetryProvider] ${event}: ${JSON.stringify(properties)}`) + log(_event: string, _properties?: TelemetryProperties): void { + Logger.log(`[NoOpTelemetryProvider] ${_event}: ${JSON.stringify(_properties)}`) } - - public logRequired(event: string, properties?: Record): void { - Logger.log(`[NoOpTelemetryProvider] REQUIRED ${event}: ${JSON.stringify(properties)}`) + logRequired(_event: string, _properties?: TelemetryProperties): void { + Logger.log(`[NoOpTelemetryProvider] REQUIRED ${_event}: ${JSON.stringify(_properties)}`) } - - public identifyUser(userInfo: any, properties?: Record): void { - Logger.info(`[NoOpTelemetryProvider] identifyUser - ${JSON.stringify(userInfo)} - ${JSON.stringify(properties)}`) + identifyUser(_userInfo: any, _properties?: TelemetryProperties): void { + Logger.info(`[NoOpTelemetryProvider] identifyUser - ${JSON.stringify(_userInfo)} - ${JSON.stringify(_properties)}`) } - - public setOptIn(optIn: boolean): void { - Logger.info(`[NoOpTelemetryProvider] setOptIn(${optIn})`) - this.isOptIn = optIn + setOptIn(_optIn: boolean): void { + Logger.info(`[NoOpTelemetryProvider] setOptIn(${_optIn})`) + this.isOptIn = _optIn } - - public isEnabled(): boolean { + isEnabled(): boolean { return false } - - public getSettings() { + getSettings(): TelemetrySettings { return { extensionEnabled: false, hostEnabled: false, - level: "off" as const, + level: "off", } } - - public async dispose(): Promise { - Logger.info("[NoOpTelemetryProvider] Disposing") + recordCounter( + _name: string, + _value: number, + _attributes?: TelemetryProperties, + _description?: string, + _required = false, + ): void { + // no-op + } + recordHistogram( + _name: string, + _value: number, + _attributes?: TelemetryProperties, + _description?: string, + _required = false, + ): void { + // no-op + } + recordGauge( + _name: string, + _value: number | null, + _attributes?: TelemetryProperties, + _description?: string, + _required = false, + ): void { + // no-op + } + async dispose(): Promise { + Logger.info(`[NoOpTelemetryProvider] Disposing (optIn=${this.isOptIn})`) } } diff --git a/src/services/telemetry/TelemetryService.test.ts b/src/services/telemetry/TelemetryService.test.ts index 003586f0..952330d2 100644 --- a/src/services/telemetry/TelemetryService.test.ts +++ b/src/services/telemetry/TelemetryService.test.ts @@ -27,8 +27,8 @@ describe("Telemetry system is abstracted and can easily switch between providers }) const MOCK_USER_INFO = { id: "test-user-123", - email: "test@example.com", displayName: "Test User", + email: "test@example.com", createdAt: new Date().toISOString(), organizations: [], } diff --git a/src/services/telemetry/TelemetryService.ts b/src/services/telemetry/TelemetryService.ts index cfab4d47..e0fc58c7 100644 --- a/src/services/telemetry/TelemetryService.ts +++ b/src/services/telemetry/TelemetryService.ts @@ -81,6 +81,42 @@ export class TelemetryService { ["subagents", true], // CLI Subagents telemetry enabled ]) + private userId?: string + private taskTurnCounts = new Map() + private taskToolCallCounts = new Map() + private taskErrorCounts = new Map() + public static readonly METRICS = { + TASK: { + TURNS_TOTAL: "cline.turns.total", + TURNS_PER_TASK: "cline.turns.per_task", + TOKENS_INPUT_TOTAL: "cline.tokens.input.total", + TOKENS_INPUT_PER_RESPONSE: "cline.tokens.input.per_response", + TOKENS_OUTPUT_TOTAL: "cline.tokens.output.total", + TOKENS_OUTPUT_PER_RESPONSE: "cline.tokens.output.per_response", + COST_TOTAL: "cline.cost.total", + COST_PER_EVENT: "cline.cost.per_event", + }, + CACHE: { + WRITE_TOTAL: "cline.cache.write.tokens.total", + WRITE_PER_EVENT: "cline.cache.write.tokens.per_event", + READ_TOTAL: "cline.cache.read.tokens.total", + READ_PER_EVENT: "cline.cache.read.tokens.per_event", + HITS_TOTAL: "cline.cache.hits.total", + }, + TOOLS: { + CALLS_TOTAL: "cline.tool.calls.total", + CALLS_PER_TASK: "cline.tool.calls.per_task", + }, + ERRORS: { + TOTAL: "cline.errors.total", + PER_TASK: "cline.errors.per_task", + }, + API: { + TTFT_SECONDS: "cline.api.ttft.seconds", + DURATION_SECONDS: "cline.api.duration.seconds", + THROUGHPUT_TOKENS_PER_SECOND: "cline.api.throughput.tokens_per_second", + }, + } // Event constants for tracking user interactions and system events private static readonly EVENTS = { // Task-related events for tracking conversation and execution flow @@ -329,6 +365,81 @@ export class TelemetryService { }) } + private getStandardAttributes(extra?: TelemetryProperties): TelemetryProperties { + return { + ...this.telemetryMetadata, + ...(this.userId ? { userId: this.userId } : {}), + ...(extra ?? {}), + } + } + + private recordCounter( + name: string, + value: number, + attributes?: TelemetryProperties, + description?: string, + required = false, + ): void { + const attrs = this.getStandardAttributes(attributes) + this.providers.forEach((provider) => { + try { + provider.recordCounter(name, value, attrs, description, required) + } catch (error) { + console.error(`[TelemetryService] recordCounter failed: ${name}`, error) + } + }) + } + + private recordHistogram( + name: string, + value: number, + attributes?: TelemetryProperties, + description?: string, + required = false, + ): void { + const attrs = this.getStandardAttributes(attributes) + this.providers.forEach((provider) => { + try { + provider.recordHistogram(name, value, attrs, description, required) + } catch (error) { + console.error(`[TelemetryService] recordHistogram failed: ${name}`, error) + } + }) + } + + /** + * Gauge values require explicit cleanup: callers must pass null with the same attribute set + * when the series identified by name+attributes ends to prevent stale metric entries. + */ + private recordGauge( + name: string, + value: number | null, + attributes?: TelemetryProperties, + description?: string, + required = false, + ): void { + const attrs = this.getStandardAttributes(attributes) + this.providers.forEach((provider) => { + try { + provider.recordGauge(name, value, attrs, description, required) + } catch (error) { + console.error(`[TelemetryService] recordGauge failed: ${name}`, error) + } + }) + } + + private incrementTaskCounter(store: Map, ulid: string): number { + const nextValue = (store.get(ulid) ?? 0) + 1 + store.set(ulid, nextValue) + return nextValue + } + + private resetTaskAggregates(ulid: string): void { + this.taskTurnCounts.delete(ulid) + this.taskToolCallCounts.delete(ulid) + this.taskErrorCounts.delete(ulid) + } + public captureExtensionActivated() { this.captureToProviders(TelemetryService.EVENTS.USER.EXTENSION_ACTIVATED, {}, false) } @@ -396,6 +507,7 @@ export class TelemetryService { ...this.telemetryMetadata, } + this.userId = userInfo.id // Update all providers with error isolation this.providers.forEach((provider) => { try { @@ -539,6 +651,7 @@ export class TelemetryService { * @param openAiCompatibleDomain Optional domain for OpenAI Compatible providers (e.g., "api.example.com") */ public captureTaskCreated(ulid: string, apiProvider?: string, openAiCompatibleDomain?: string) { + this.resetTaskAggregates(ulid) this.capture({ event: TelemetryService.EVENTS.TASK.CREATED, properties: { ulid, apiProvider, openAiCompatibleDomain }, @@ -552,6 +665,7 @@ export class TelemetryService { * @param openAiCompatibleDomain Optional domain for OpenAI Compatible providers (e.g., "api.example.com") */ public captureTaskRestarted(ulid: string, apiProvider?: string, openAiCompatibleDomain?: string) { + this.resetTaskAggregates(ulid) this.capture({ event: TelemetryService.EVENTS.TASK.RESTARTED, properties: { ulid, apiProvider, openAiCompatibleDomain }, @@ -567,6 +681,7 @@ export class TelemetryService { event: TelemetryService.EVENTS.TASK.COMPLETED, properties: { ulid }, }) + this.resetTaskAggregates(ulid) } /** @@ -612,6 +727,51 @@ export class TelemetryService { isNativeToolCall, }, }) + + const turnCount = this.incrementTaskCounter(this.taskTurnCounts, ulid) + + const turnAttributes = { ulid, provider, model, source, mode } + this.recordCounter(TelemetryService.METRICS.TASK.TURNS_TOTAL, 1, turnAttributes) + this.recordHistogram(TelemetryService.METRICS.TASK.TURNS_PER_TASK, turnCount, turnAttributes) + + if (Number.isFinite(tokenUsage.cacheWriteTokens)) { + const cacheWriteTokens = tokenUsage.cacheWriteTokens ?? 0 + this.recordCounter(TelemetryService.METRICS.CACHE.WRITE_TOTAL, cacheWriteTokens, { + ulid, + provider, + model, + mode, + }) + this.recordHistogram(TelemetryService.METRICS.CACHE.WRITE_PER_EVENT, cacheWriteTokens, { + ulid, + provider, + model, + mode, + }) + } + + if (Number.isFinite(tokenUsage.cacheReadTokens)) { + const cacheReadTokens = tokenUsage.cacheReadTokens ?? 0 + this.recordCounter(TelemetryService.METRICS.CACHE.READ_TOTAL, cacheReadTokens, { + ulid, + provider, + model, + mode, + }) + this.recordHistogram(TelemetryService.METRICS.CACHE.READ_PER_EVENT, cacheReadTokens, { + ulid, + provider, + model, + mode, + }) + } + + if (Number.isFinite(tokenUsage.totalCost)) { + const totalCost = tokenUsage.totalCost ?? 0 + const costAttributes = { ulid, provider, model, mode, currency: "USD" } + this.recordCounter(TelemetryService.METRICS.TASK.COST_TOTAL, totalCost, costAttributes) + this.recordHistogram(TelemetryService.METRICS.TASK.COST_PER_EVENT, totalCost, costAttributes) + } } /** @@ -631,6 +791,18 @@ export class TelemetryService { model, }, }) + + if (Number.isFinite(tokensIn)) { + const value = tokensIn ?? 0 + this.recordCounter(TelemetryService.METRICS.TASK.TOKENS_INPUT_TOTAL, value, { ulid, model }) + this.recordHistogram(TelemetryService.METRICS.TASK.TOKENS_INPUT_PER_RESPONSE, value, { ulid, model }) + } + + if (Number.isFinite(tokensOut)) { + const value = tokensOut ?? 0 + this.recordCounter(TelemetryService.METRICS.TASK.TOKENS_OUTPUT_TOTAL, value, { ulid, model }) + this.recordHistogram(TelemetryService.METRICS.TASK.TOKENS_OUTPUT_PER_RESPONSE, value, { ulid, model }) + } } /** @@ -692,6 +864,7 @@ export class TelemetryService { feedbackType, }, }) + this.resetTaskAggregates(ulid) } // Tool events @@ -739,6 +912,17 @@ export class TelemetryService { isNativeToolCall, }, }) + + const toolAttributes = { + ulid, + tool, + model: modelId, + success, + autoApproved, + } + const toolCallCount = this.incrementTaskCounter(this.taskToolCallCounts, ulid) + this.recordCounter(TelemetryService.METRICS.TOOLS.CALLS_TOTAL, 1, toolAttributes) + this.recordHistogram(TelemetryService.METRICS.TOOLS.CALLS_PER_TASK, toolCallCount, toolAttributes) } /** @@ -990,6 +1174,34 @@ export class TelemetryService { ...data, }, }) + + if (typeof data.ttftSec === "number") { + this.recordHistogram(TelemetryService.METRICS.API.TTFT_SECONDS, data.ttftSec, { + ulid, + model: modelId, + provider: "gemini", + }) + } + + if (typeof data.totalDurationSec === "number") { + this.recordHistogram(TelemetryService.METRICS.API.DURATION_SECONDS, data.totalDurationSec, { + ulid, + model: modelId, + provider: "gemini", + }) + } + + if (typeof data.throughputTokensPerSec === "number") { + this.recordHistogram(TelemetryService.METRICS.API.THROUGHPUT_TOKENS_PER_SECOND, data.throughputTokensPerSec, { + ulid, + model: modelId, + provider: "gemini", + }) + } + + if (data.cacheHit) { + this.recordCounter(TelemetryService.METRICS.CACHE.HITS_TOTAL, 1, { ulid, model: modelId, provider: "gemini" }) + } } /** @@ -1043,6 +1255,21 @@ export class TelemetryService { timestamp: new Date().toISOString(), }, }) + + this.recordCounter(TelemetryService.METRICS.ERRORS.TOTAL, 1, { + ulid: args.ulid, + model: args.model, + provider: args.provider, + error_status: args.errorStatus, + }) + const errorAttributes = { + ulid: args.ulid, + model: args.model, + provider: args.provider, + error_status: args.errorStatus, + } + const errorCount = this.incrementTaskCounter(this.taskErrorCounts, args.ulid) + this.recordHistogram(TelemetryService.METRICS.ERRORS.PER_TASK, errorCount, errorAttributes) } /** @@ -1374,6 +1601,15 @@ export class TelemetryService { feature_flag_enabled: featureFlagEnabled, }, }) + + const isMultiRoot = rootCount > 1 + this.recordGauge("cline.workspace.active_roots", rootCount, { + is_multi_root: isMultiRoot, + }) + // Retire the previous series to avoid leaking gauge entries when the flag flips. + this.recordGauge("cline.workspace.active_roots", null, { + is_multi_root: !isMultiRoot, + }) } /** diff --git a/src/services/telemetry/__tests__/TelemetryService.metrics.test.ts b/src/services/telemetry/__tests__/TelemetryService.metrics.test.ts new file mode 100644 index 00000000..a03fa0a7 --- /dev/null +++ b/src/services/telemetry/__tests__/TelemetryService.metrics.test.ts @@ -0,0 +1,192 @@ +import * as assert from "assert" +import type { ITelemetryProvider, TelemetryProperties, TelemetrySettings } from "../providers/ITelemetryProvider" +import { TelemetryService } from "../TelemetryService" + +class FakeProvider implements ITelemetryProvider { + public counters: Array<{ name: string; value: number; attributes: TelemetryProperties; description?: string }> = [] + public histograms: Array<{ name: string; value: number; attributes: TelemetryProperties; description?: string }> = [] + public gauges = new Map>() + + log(): void {} + logRequired(): void {} + identifyUser(): void {} + setOptIn(): void {} + isEnabled(): boolean { + return true + } + getSettings(): TelemetrySettings { + return { extensionEnabled: true, hostEnabled: true, level: "all" } + } + recordCounter(name: string, value: number, attributes?: TelemetryProperties, description?: string, _required = false): void { + this.counters.push({ name, value, attributes: attributes ?? {}, description }) + } + recordHistogram( + name: string, + value: number, + attributes?: TelemetryProperties, + description?: string, + _required = false, + ): void { + this.histograms.push({ name, value, attributes: attributes ?? {}, description }) + } + recordGauge( + name: string, + value: number | null, + attributes?: TelemetryProperties, + description?: string, + _required = false, + ): void { + const attrKey = JSON.stringify(attributes ?? {}) + const series = this.gauges.get(name) + if (value === null) { + series?.delete(attrKey) + if (series && series.size === 0) { + this.gauges.delete(name) + } + return + } + + let nextSeries = series + if (!nextSeries) { + nextSeries = new Map() + this.gauges.set(name, nextSeries) + } + + nextSeries.set(attrKey, { value, attributes: attributes ?? {}, description }) + } + async dispose(): Promise {} +} + +function createTelemetryService(provider: FakeProvider): TelemetryService { + return new TelemetryService([provider], { + extension_version: "test", + platform: "test-platform", + platform_version: "1.0.0", + os_type: "darwin", + os_version: "24", + is_dev: "true", + }) +} + +describe("TelemetryService metrics", () => { + it("captureTokenUsage emits token counters and histograms", () => { + const provider = new FakeProvider() + const service = createTelemetryService(provider) + + service.captureTokenUsage("task-1", 120, 80, "model-a") + + assert.deepStrictEqual( + provider.counters.map((entry) => entry.name), + [TelemetryService.METRICS.TASK.TOKENS_INPUT_TOTAL, TelemetryService.METRICS.TASK.TOKENS_OUTPUT_TOTAL], + ) + assert.deepStrictEqual( + provider.histograms.map((entry) => entry.name), + [TelemetryService.METRICS.TASK.TOKENS_INPUT_PER_RESPONSE, TelemetryService.METRICS.TASK.TOKENS_OUTPUT_PER_RESPONSE], + ) + provider.counters.forEach((entry) => { + assert.strictEqual(entry.attributes.ulid, "task-1") + assert.strictEqual(entry.attributes.model, "model-a") + assert.strictEqual(entry.attributes.extension_version, "test") + }) + }) + + it("captureConversationTurnEvent emits counters with cache and cost", () => { + const provider = new FakeProvider() + const service = createTelemetryService(provider) + service.identifyAccount({ id: "user-1" } as any) + + service.captureConversationTurnEvent("task-2", "openai", "gpt-4", "assistant", "plan", { + tokensIn: 150, + tokensOut: 200, + cacheWriteTokens: 40, + cacheReadTokens: 20, + totalCost: 1.23, + }) + + assert.deepStrictEqual( + provider.counters.map((entry) => entry.name), + [ + TelemetryService.METRICS.TASK.TURNS_TOTAL, + TelemetryService.METRICS.CACHE.WRITE_TOTAL, + TelemetryService.METRICS.CACHE.READ_TOTAL, + TelemetryService.METRICS.TASK.COST_TOTAL, + ], + ) + const costEntry = provider.counters.find((entry) => entry.name === "cline.cost.total") + assert.ok(costEntry) + assert.strictEqual(costEntry?.attributes.ulid, "task-2") + assert.strictEqual(costEntry?.attributes.provider, "openai") + assert.strictEqual(costEntry?.attributes.model, "gpt-4") + assert.strictEqual(costEntry?.attributes.mode, "plan") + assert.strictEqual(costEntry?.attributes.currency, "USD") + assert.deepStrictEqual( + provider.histograms.map((entry) => entry.name), + [ + TelemetryService.METRICS.TASK.TURNS_PER_TASK, + TelemetryService.METRICS.CACHE.WRITE_PER_EVENT, + TelemetryService.METRICS.CACHE.READ_PER_EVENT, + TelemetryService.METRICS.TASK.COST_PER_EVENT, + ], + ) + const turnEntry = provider.histograms.find((entry) => entry.name === TelemetryService.METRICS.TASK.TURNS_PER_TASK) + assert.ok(turnEntry) + assert.strictEqual(turnEntry?.value, 1) + assert.strictEqual(turnEntry?.attributes.ulid, "task-2") + assert.strictEqual(turnEntry?.attributes.provider, "openai") + assert.strictEqual(turnEntry?.attributes.model, "gpt-4") + assert.strictEqual(turnEntry?.attributes.source, "assistant") + assert.strictEqual(turnEntry?.attributes.mode, "plan") + }) + + it("captureWorkspaceInitialized emits gauge and retires previous series", () => { + const provider = new FakeProvider() + const service = createTelemetryService(provider) + + service.captureWorkspaceInitialized(3, ["Git"], 500) + const initialSeries = provider.gauges.get("cline.workspace.active_roots") + assert.ok(initialSeries) + assert.strictEqual(initialSeries.size, 1) + const [initialEntry] = Array.from(initialSeries.values()) + assert.strictEqual(initialEntry.value, 3) + assert.strictEqual(initialEntry.attributes.is_multi_root, true) + assert.strictEqual(initialEntry.attributes.extension_version, "test") + + service.captureWorkspaceInitialized(1, ["Git"], 200) + const updatedSeries = provider.gauges.get("cline.workspace.active_roots") + assert.ok(updatedSeries) + assert.strictEqual(updatedSeries.size, 1) + const [updatedEntry] = Array.from(updatedSeries.values()) + assert.strictEqual(updatedEntry.value, 1) + assert.strictEqual(updatedEntry.attributes.is_multi_root, false) + }) + + it("captureProviderApiError increments error counter", () => { + const provider = new FakeProvider() + const service = createTelemetryService(provider) + + service.captureProviderApiError({ + ulid: "task-3", + model: "claude", + errorMessage: "boom", + provider: "anthropic", + errorStatus: 500, + }) + + assert.strictEqual(provider.counters.length, 1) + const entry = provider.counters[0] + assert.strictEqual(entry.name, TelemetryService.METRICS.ERRORS.TOTAL) + assert.strictEqual(entry.value, 1) + assert.strictEqual(entry.attributes.ulid, "task-3") + assert.strictEqual(entry.attributes.provider, "anthropic") + assert.strictEqual(entry.attributes.model, "claude") + assert.strictEqual(entry.attributes.error_status, 500) + assert.strictEqual(provider.histograms.length, 1) + const errorHistogram = provider.histograms[0] + assert.strictEqual(errorHistogram.name, TelemetryService.METRICS.ERRORS.PER_TASK) + assert.strictEqual(errorHistogram.value, 1) + assert.strictEqual(errorHistogram.attributes.ulid, "task-3") + assert.strictEqual(errorHistogram.attributes.provider, "anthropic") + assert.strictEqual(errorHistogram.attributes.model, "claude") + assert.strictEqual(errorHistogram.attributes.error_status, 500) + }) +}) diff --git a/src/services/telemetry/providers/ITelemetryProvider.ts b/src/services/telemetry/providers/ITelemetryProvider.ts index 2d682056..6194f67f 100644 --- a/src/services/telemetry/providers/ITelemetryProvider.ts +++ b/src/services/telemetry/providers/ITelemetryProvider.ts @@ -87,22 +87,37 @@ export interface ITelemetryProvider { getSettings(): TelemetrySettings /** - * (Optional) Increment a counter metric. + * Record a counter metric (cumulative value that only increases) * Providers that don't support metrics may implement this as a no-op. - * @param name Metric name + * @param name Metric name (e.g., "cline.tokens.input") * @param value Amount to increment by (default 1) - * @param attributes Optional metric attributes (JSON-serializable) + * @param attributes Optional metric attributes including userId, ulid (JSON-serializable) */ - incrementCounter?(name: string, value?: number, attributes?: TelemetryProperties): void + recordCounter(name: string, value: number, attributes?: TelemetryProperties, description?: string, required?: boolean): void /** - * (Optional) Record a value in a histogram metric. + * Record a histogram metric (distribution of values for percentile analysis) * Providers that don't support metrics may implement this as a no-op. - * @param name Metric name + * @param name Metric name (e.g., "cline.api.duration_seconds") * @param value Value to record - * @param attributes Optional metric attributes (JSON-serializable) + * @param attributes Optional metric attributes including userId, ulid (JSON-serializable) */ - recordHistogram?(name: string, value: number, attributes?: TelemetryProperties): void + recordHistogram(name: string, value: number, attributes?: TelemetryProperties, description?: string, required?: boolean): void + + /** + * Record a gauge metric (point-in-time value that can go up or down) + * Providers that don't support metrics may implement this as a no-op. + * @param name Metric name (e.g., "cline.workspace.active_roots") + * @param value Current value, or null to retire the series identified by name + attributes + * @param attributes Optional metric attributes including userId, ulid (JSON-serializable). When retiring a series pass the same attribute set that was used when recording it. + */ + recordGauge( + name: string, + value: number | null, + attributes?: TelemetryProperties, + description?: string, + required?: boolean, + ): void /** * Clean up resources when the provider is disposed diff --git a/src/services/telemetry/providers/opentelemetry/OpenTelemetryTelemetryProvider.ts b/src/services/telemetry/providers/opentelemetry/OpenTelemetryTelemetryProvider.ts index 6788fd03..51ffa3b1 100644 --- a/src/services/telemetry/providers/opentelemetry/OpenTelemetryTelemetryProvider.ts +++ b/src/services/telemetry/providers/opentelemetry/OpenTelemetryTelemetryProvider.ts @@ -20,6 +20,8 @@ export class OpenTelemetryTelemetryProvider implements ITelemetryProvider { // Lazy instrument caches for metrics private counters = new Map>() private histograms = new Map>() + private gauges = new Map>() + private gaugeValues = new Map>() constructor() { // Initialize telemetry settings @@ -120,7 +122,6 @@ export class OpenTelemetryTelemetryProvider implements ITelemetryProvider { // Store user attributes for future events this.userAttributes = { user_id: userInfo.id, - user_email: userInfo.email || "", user_name: userInfo.displayName || "", ...this.flattenProperties(properties), } @@ -156,17 +157,24 @@ export class OpenTelemetryTelemetryProvider implements ITelemetryProvider { } /** - * Increment a counter metric (lazy creation). - * Only creates the counter on first use if meter is available. + * Record a counter metric (cumulative value that only increases) + * Lazy creation - only creates the counter on first use if meter is available. */ - public incrementCounter(name: string, value: number = 1, attributes?: TelemetryProperties): void { - if (!this.meter) { + public recordCounter( + name: string, + value: number, + attributes?: TelemetryProperties, + description?: string, + required = false, + ): void { + if (!this.meter || (!required && !this.isEnabled())) { return } let counter = this.counters.get(name) if (!counter) { - counter = this.meter.createCounter(name) + const options = description ? { description } : undefined + counter = this.meter.createCounter(name, options) this.counters.set(name, counter) console.log(`[OTEL] Created counter: ${name}`) } @@ -175,17 +183,24 @@ export class OpenTelemetryTelemetryProvider implements ITelemetryProvider { } /** - * Record a histogram metric (lazy creation). - * Only creates the histogram on first use if meter is available. + * Record a histogram metric (distribution of values for percentile analysis) + * Lazy creation - only creates the histogram on first use if meter is available. */ - public recordHistogram(name: string, value: number, attributes?: TelemetryProperties): void { - if (!this.meter) { + public recordHistogram( + name: string, + value: number, + attributes?: TelemetryProperties, + description?: string, + required = false, + ): void { + if (!this.meter || (!required && !this.isEnabled())) { return } let histogram = this.histograms.get(name) if (!histogram) { - histogram = this.meter.createHistogram(name) + const options = description ? { description } : undefined + histogram = this.meter.createHistogram(name, options) this.histograms.set(name, histogram) console.log(`[OTEL] Created histogram: ${name}`) } @@ -193,6 +208,78 @@ export class OpenTelemetryTelemetryProvider implements ITelemetryProvider { histogram.record(value, this.flattenProperties(attributes)) } + /** + * Record a gauge metric (point-in-time value that can go up or down) + * Lazy creation - creates an observable gauge that reads from stored values + */ + public recordGauge( + name: string, + value: number | null, + attributes?: TelemetryProperties, + description?: string, + required = false, + ): void { + if (!this.meter || (!required && !this.isEnabled())) { + return + } + + const attrKey = attributes ? JSON.stringify(attributes) : "" + + const existingSeries = this.gaugeValues.get(name) + + if (value === null) { + if (existingSeries) { + existingSeries.delete(attrKey) + if (existingSeries.size === 0) { + this.gaugeValues.delete(name) + this.gauges.delete(name) + } + } + return + } + + let series = existingSeries + if (!series) { + series = new Map() + this.gaugeValues.set(name, series) + } + + if (!this.gauges.has(name)) { + const options = description ? { description } : undefined + const gauge = this.meter.createObservableGauge(name, options) + + gauge.addCallback((observableResult) => { + const snapshot = this.snapshotGaugeSeries(name) + if (snapshot.length === 0) { + return + } + for (const data of snapshot) { + observableResult.observe(data.value, this.flattenProperties(data.attributes)) + } + }) + + this.gauges.set(name, gauge) + console.log(`[OTEL] Created gauge: ${name}`) + } + + series.set(attrKey, { value, attributes }) + } + + private snapshotGaugeSeries(name: string): Array<{ value: number; attributes?: TelemetryProperties }> { + const series = this.gaugeValues.get(name) + if (!series) { + return [] + } + const snapshot: Array<{ value: number; attributes?: TelemetryProperties }> = [] + for (const data of series.values()) { + snapshot.push({ + value: data.value, + attributes: data.attributes ? { ...data.attributes } : undefined, + }) + } + return snapshot + } + public async dispose(): Promise { // OpenTelemetry client provider handles shutdown // Individual providers don't need to do anything diff --git a/src/services/telemetry/providers/posthog/PostHogTelemetryProvider.ts b/src/services/telemetry/providers/posthog/PostHogTelemetryProvider.ts index 75168526..8b61f92b 100644 --- a/src/services/telemetry/providers/posthog/PostHogTelemetryProvider.ts +++ b/src/services/telemetry/providers/posthog/PostHogTelemetryProvider.ts @@ -98,7 +98,6 @@ export class PostHogTelemetryProvider implements ITelemetryProvider { distinctId: userInfo.id, properties: { uuid: userInfo.id, - email: userInfo.email, name: userInfo.displayName, ...properties, alias: distinctId, @@ -129,14 +128,63 @@ export class PostHogTelemetryProvider implements ITelemetryProvider { } /** - * Metrics are not supported in PostHog provider. These are intentional no-ops. + * Record a counter metric by converting to equivalent PostHog event + * This maintains backward compatibility with existing dashboards */ - public incrementCounter(name: string, value: number = 1, attributes?: TelemetryProperties): void { - // no-op + public recordCounter( + name: string, + value: number, + attributes?: TelemetryProperties, + _description?: string, + required = false, + ): void { + if (!this.isEnabled() && !required) return + + // Convert metric to event format for PostHog + // Most counters don't need individual events - they're aggregated in OpenTelemetry + // Only log significant counter events that have dashboard equivalents + if (name === "cline.tokens.input.total" || name === "cline.tokens.output.total") { + // These will be batched and emitted as a single "task.tokens" event + // Implementation will be added when we update captureTokenUsage + } } - public recordHistogram(name: string, value: number, attributes?: TelemetryProperties): void { - // no-op + /** + * Record a histogram metric by converting to equivalent PostHog event + * Histograms track distributions, but PostHog events capture individual values + */ + public recordHistogram( + _name: string, + _value: number, + _attributes?: TelemetryProperties, + _description?: string, + _required = false, + ): void { + // Histograms are for distribution analysis in OpenTelemetry + // PostHog gets the raw values through existing event capture methods + // No action needed here - events already capture these values + } + + /** + * Record a gauge metric by converting to equivalent PostHog event + * Gauges track current state, which we can log as state change events + */ + public recordGauge( + name: string, + value: number | null, + attributes?: TelemetryProperties, + _description?: string, + required = false, + ): void { + if ((!this.isEnabled() && !required) || value === null) return + + // Convert gauge updates to state change events + if (name === "cline.workspace.active_roots") { + this.log("workspace.roots_changed", { + count: value, + ...attributes, + }) + } } public async dispose(): Promise {