From 675cd1779be0dabdfb0ccc0324f7eeeb82943701 Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Tue, 12 Aug 2025 21:19:28 -0700 Subject: [PATCH] using ulid instead of taskid (#5524) * using ulid instead of taskid * protos * Update src/services/browser/BrowserSession.ts Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> --------- Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> --- proto/cline/models.proto | 2 +- proto/cline/state.proto | 2 +- src/api/index.ts | 8 +- src/api/providers/cline.ts | 4 +- src/api/providers/gemini.ts | 10 +- src/api/providers/litellm.ts | 4 +- src/api/providers/vertex.ts | 2 +- src/core/controller/index.ts | 8 +- .../controller/models/refreshGroqModels.ts | 1 - .../models/updateApiConfigurationProto.ts | 2 +- src/core/controller/state/updateSettings.ts | 2 +- src/core/controller/task/taskFeedback.ts | 4 +- src/core/task/ToolExecutor.ts | 48 +++--- src/core/task/index.ts | 37 ++--- src/extension.ts | 10 +- src/services/browser/BrowserSession.ts | 42 +++--- .../posthog/telemetry/TelemetryService.ts | 137 +++++++----------- src/shared/api.ts | 2 +- .../models/api-configuration-conversion.ts | 4 +- .../state/settings-conversion.ts | 4 +- 20 files changed, 149 insertions(+), 184 deletions(-) diff --git a/proto/cline/models.proto b/proto/cline/models.proto index 09d23b40..cf1edeed 100644 --- a/proto/cline/models.proto +++ b/proto/cline/models.proto @@ -175,7 +175,7 @@ message ModelsApiConfiguration { // Global configuration fields (not mode-specific) optional string api_key = 1; optional string cline_api_key = 2; - optional string task_id = 3; + optional string ulid = 3; optional string lite_llm_base_url = 4; optional string lite_llm_api_key = 5; optional bool lite_llm_use_prompt_cache = 6; diff --git a/proto/cline/state.proto b/proto/cline/state.proto index b2b56a77..73bbcdbe 100644 --- a/proto/cline/state.proto +++ b/proto/cline/state.proto @@ -130,7 +130,7 @@ message ApiConfiguration { // Global configuration fields (not mode-specific) optional string api_key = 1; // anthropic optional string cline_api_key = 2; - optional string task_id = 3; + optional string ulid = 3; optional string lite_llm_base_url = 4; optional string lite_llm_api_key = 5; optional bool lite_llm_use_prompt_cache = 6; diff --git a/src/api/index.ts b/src/api/index.ts index 1058fdd0..7b1426df 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -98,7 +98,7 @@ function createHandlerForProvider( mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens, geminiApiKey: options.geminiApiKey, geminiBaseUrl: options.geminiBaseUrl, - taskId: options.taskId, + ulid: options.ulid, }) case "openai": return new OpenAiHandler({ @@ -132,7 +132,7 @@ function createHandlerForProvider( thinkingBudgetTokens: mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens, apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId, - taskId: options.taskId, + ulid: options.ulid, }) case "openai-native": return new OpenAiNativeHandler({ @@ -193,7 +193,7 @@ function createHandlerForProvider( case "cline": return new ClineHandler({ clineAccountId: options.clineAccountId, - taskId: options.taskId, + ulid: options.ulid, reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort, thinkingBudgetTokens: mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens, @@ -210,7 +210,7 @@ function createHandlerForProvider( thinkingBudgetTokens: mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens, liteLlmUsePromptCache: options.liteLlmUsePromptCache, - taskId: options.taskId, + ulid: options.ulid, }) case "moonshot": return new MoonshotHandler({ diff --git a/src/api/providers/cline.ts b/src/api/providers/cline.ts index 43f831cb..ba9384c6 100644 --- a/src/api/providers/cline.ts +++ b/src/api/providers/cline.ts @@ -15,7 +15,7 @@ import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount" import { clineEnvConfig } from "@/config" interface ClineHandlerOptions { - taskId?: string + ulid?: string reasoningEffort?: string thinkingBudgetTokens?: number openRouterProviderSorting?: string @@ -51,7 +51,7 @@ export class ClineHandler implements ApiHandler { defaultHeaders: { "HTTP-Referer": "https://cline.bot", "X-Title": "Cline", - "X-Task-ID": this.options.taskId || "", + "X-Task-ID": this.options.ulid || "", "X-Cline-Version": extensionVersion, }, }) diff --git a/src/api/providers/gemini.ts b/src/api/providers/gemini.ts index 9d323bc3..dbeba17b 100644 --- a/src/api/providers/gemini.ts +++ b/src/api/providers/gemini.ts @@ -20,7 +20,7 @@ interface GeminiHandlerOptions { geminiBaseUrl?: string thinkingBudgetTokens?: number apiModelId?: string - taskId?: string + ulid?: string } /** @@ -28,7 +28,7 @@ interface GeminiHandlerOptions { * * Key features: * - One cache per task: Creates a single cache per task and reuses it for subsequent turns - * - Stable cache keys: Uses taskId as a stable identifier for caches + * - Stable cache keys: Uses ulid as a stable identifier for caches * - Efficient cache updates: Only updates caches when there's new content to add * - Split cost accounting: Separates immediate costs from ongoing cache storage costs * @@ -255,8 +255,8 @@ export class GeminiHandler implements ApiHandler { const throughputTokensPerSecSdk = totalDurationSdkMs > 0 && outputTokens > 0 ? outputTokens / (totalDurationSdkMs / 1000) : undefined - if (this.options.taskId) { - telemetryService.captureGeminiApiPerformance(this.options.taskId, modelId, { + if (this.options.ulid) { + telemetryService.captureGeminiApiPerformance(this.options.ulid, modelId, { ttftSec: ttftSdkMs !== undefined ? ttftSdkMs / 1000 : undefined, totalDurationSec: totalDurationSdkMs / 1000, promptTokens, @@ -269,7 +269,7 @@ export class GeminiHandler implements ApiHandler { throughputTokensPerSec: throughputTokensPerSecSdk, }) } else { - console.warn("GeminiHandler: taskId not available for telemetry in createMessage.") + console.warn("GeminiHandler: ulid not available for telemetry in createMessage.") } } } diff --git a/src/api/providers/litellm.ts b/src/api/providers/litellm.ts index e01a377c..922efae5 100644 --- a/src/api/providers/litellm.ts +++ b/src/api/providers/litellm.ts @@ -13,7 +13,7 @@ interface LiteLlmHandlerOptions { liteLlmModelInfo?: LiteLLMModelInfo thinkingBudgetTokens?: number liteLlmUsePromptCache?: boolean - taskId?: string + ulid?: string } interface LiteLlmModelInfoResponse { @@ -230,7 +230,7 @@ export class LiteLlmHandler implements ApiHandler { stream: true, stream_options: { include_usage: true }, ...(thinkingConfig && { thinking: thinkingConfig }), // Add thinking configuration when applicable - ...(this.options.taskId && { litellm_session_id: `cline-${this.options.taskId}` }), // Add session ID for LiteLLM tracking + ...(this.options.ulid && { litellm_session_id: `cline-${this.options.ulid}` }), // Add session ID for LiteLLM tracking }) for await (const chunk of stream) { diff --git a/src/api/providers/vertex.ts b/src/api/providers/vertex.ts index c900edec..5b3adfcb 100644 --- a/src/api/providers/vertex.ts +++ b/src/api/providers/vertex.ts @@ -13,7 +13,7 @@ interface VertexHandlerOptions { thinkingBudgetTokens?: number geminiApiKey?: string geminiBaseUrl?: string - taskId?: string + ulid?: string } export class VertexHandler implements ApiHandler { diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index a8d09d22..e7d7cd57 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -238,12 +238,12 @@ export class Controller { this.cacheService.setGlobalState("mode", modeToSwitchTo) // Capture mode switch telemetry | Capture regardless of if we know the taskId - telemetryService.captureModeSwitch(this.task?.taskId ?? "0", modeToSwitchTo) + telemetryService.captureModeSwitch(this.task?.ulid ?? "0", modeToSwitchTo) // Update API handler with new mode (buildApiHandler now selects provider based on mode) if (this.task) { const apiConfiguration = this.cacheService.getApiConfiguration() - this.task.api = buildApiHandler({ ...apiConfiguration, taskId: this.task.taskId }, modeToSwitchTo) + this.task.api = buildApiHandler({ ...apiConfiguration, ulid: this.task.ulid }, modeToSwitchTo) } await this.postStateToWebview() @@ -336,7 +336,7 @@ export class Controller { this.cacheService.setGlobalState("welcomeViewCompleted", true) if (this.task) { - this.task.api = buildApiHandler({ ...updatedConfig, taskId: this.task.taskId }, currentMode) + this.task.api = buildApiHandler({ ...updatedConfig, ulid: this.task.ulid }, currentMode) } await this.postStateToWebview() @@ -480,7 +480,7 @@ export class Controller { await this.postStateToWebview() if (this.task) { - this.task.api = buildApiHandler({ ...updatedConfig, taskId: this.task.taskId }, currentMode) + this.task.api = buildApiHandler({ ...updatedConfig, ulid: this.task.ulid }, currentMode) } // Dont send settingsButtonClicked because its bad ux if user is on welcome } diff --git a/src/core/controller/models/refreshGroqModels.ts b/src/core/controller/models/refreshGroqModels.ts index ad1649d6..a2a8b919 100644 --- a/src/core/controller/models/refreshGroqModels.ts +++ b/src/core/controller/models/refreshGroqModels.ts @@ -110,7 +110,6 @@ export async function refreshGroqModels(controller: Controller, request: EmptyRe } telemetryService.captureProviderApiError({ - taskId: controller.task?.taskId || "", ulid: controller.task?.ulid || "", errorMessage, errorStatus: error.status, diff --git a/src/core/controller/models/updateApiConfigurationProto.ts b/src/core/controller/models/updateApiConfigurationProto.ts index 4047caa9..b570723d 100644 --- a/src/core/controller/models/updateApiConfigurationProto.ts +++ b/src/core/controller/models/updateApiConfigurationProto.ts @@ -29,7 +29,7 @@ export async function updateApiConfigurationProto( // Update the task's API handler if there's an active task if (controller.task) { const currentMode = await controller.getCurrentMode() - controller.task.api = buildApiHandler({ ...appApiConfiguration, taskId: controller.task.taskId }, currentMode) + controller.task.api = buildApiHandler({ ...appApiConfiguration, ulid: controller.task.ulid }, currentMode) } // Post updated state to webview diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts index 3e93d34d..3c837387 100644 --- a/src/core/controller/state/updateSettings.ts +++ b/src/core/controller/state/updateSettings.ts @@ -27,7 +27,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett if (controller.task) { const currentMode = await controller.getCurrentMode() - controller.task.api = buildApiHandler({ ...apiConfiguration, taskId: controller.task.taskId }, currentMode) + controller.task.api = buildApiHandler({ ...apiConfiguration, ulid: controller.task.ulid }, currentMode) } } diff --git a/src/core/controller/task/taskFeedback.ts b/src/core/controller/task/taskFeedback.ts index 7caafe9d..52a329c8 100644 --- a/src/core/controller/task/taskFeedback.ts +++ b/src/core/controller/task/taskFeedback.ts @@ -15,8 +15,8 @@ export async function taskFeedback(controller: Controller, request: StringReques } try { - if (controller.task?.taskId) { - telemetryService.captureTaskFeedback(controller.task.taskId, request.value as any) + if (controller.task?.ulid) { + telemetryService.captureTaskFeedback(controller.task.ulid, request.value as any) } else { console.warn("taskFeedback: No active task to receive feedback") } diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 60ba60c2..8182d2f1 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -566,7 +566,7 @@ export class ToolExecutor { : "other_diff_error" // Add telemetry for diff edit failure - telemetryService.captureDiffEditFailure(this.taskId, this.api.getModel().id, errorType) + telemetryService.captureDiffEditFailure(this.ulid, this.api.getModel().id, errorType) this.pushToolResult( formatResponse.toolError( @@ -692,7 +692,7 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) // we need an artificial delay to let the diagnostics catch up to the changes await setTimeoutPromise(3_500) @@ -727,7 +727,7 @@ export class ToolExecutor { } this.taskState.didRejectTool = true didApprove = false - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, false) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) } else { // User hit the approve button, and may have provided feedback if (text || (images && images.length > 0) || (askFiles && askFiles.length > 0)) { @@ -740,7 +740,7 @@ export class ToolExecutor { await this.say("user_feedback", text, images, askFiles) await this.saveCheckpoint() } - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) } if (!didApprove) { @@ -856,7 +856,7 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) // need to be sending partialValue bool, since undefined has its own purpose in that the message is treated neither as a partial or completion of a partial, but as a single complete message this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to read ${path.basename(absolutePath)}`, @@ -867,10 +867,10 @@ export class ToolExecutor { const didApprove = await this.askApproval("tool", block, completeMessage) if (!didApprove) { await this.saveCheckpoint() - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, false) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) break } - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) } // now execute the tool like normal const supportsImages = this.api.getModel().info.supportsImages ?? false @@ -945,7 +945,7 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to view directory ${path.basename(absolutePath)}/`, @@ -955,11 +955,11 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await this.askApproval("tool", block, completeMessage) if (!didApprove) { - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, false) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) await this.saveCheckpoint() break } - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) } this.pushToolResult(result, block) await this.saveCheckpoint() @@ -1017,7 +1017,7 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to view source code definitions in ${path.basename(absolutePath)}/`, @@ -1027,11 +1027,11 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await this.askApproval("tool", block, completeMessage) if (!didApprove) { - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, false) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) await this.saveCheckpoint() break } - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) } this.pushToolResult(result, block) await this.saveCheckpoint() @@ -1101,7 +1101,7 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to search files in ${path.basename(absolutePath)}/`, @@ -1111,11 +1111,11 @@ export class ToolExecutor { this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await this.askApproval("tool", block, completeMessage) if (!didApprove) { - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, false) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) await this.saveCheckpoint() break } - telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, false, true) + telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) } this.pushToolResult(results, block) await this.saveCheckpoint() @@ -1716,6 +1716,7 @@ export class ToolExecutor { // Check if options contains the text response if (optionsRaw && text && parsePartialArrayString(optionsRaw).includes(text)) { + telemetryService.captureOptionSelected(this.ulid, options.length, "act") // Valid option selected, don't show user message in UI // Update last followup message with selected option const lastFollowupMessage = findLast( @@ -1731,7 +1732,7 @@ export class ToolExecutor { } } else { // Option not selected, send user feedback - telemetryService.captureOptionsIgnored(this.taskId, options.length, "act") + telemetryService.captureOptionsIgnored(this.ulid, options.length, "act") await this.say("user_feedback", text ?? "", images, followupFiles) } @@ -2077,7 +2078,7 @@ export class ToolExecutor { await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage( - this.taskId, + this.ulid, "web_fetch" as ToolUseName, this.api.getModel().id, true, @@ -2093,7 +2094,7 @@ export class ToolExecutor { const didApprove = await this.askApproval("tool", block, completeMessage) if (!didApprove) { telemetryService.captureToolUsage( - this.taskId, + this.ulid, "web_fetch" as ToolUseName, this.api.getModel().id, false, @@ -2103,7 +2104,7 @@ export class ToolExecutor { break } telemetryService.captureToolUsage( - this.taskId, + this.ulid, "web_fetch" as ToolUseName, this.api.getModel().id, false, @@ -2190,6 +2191,7 @@ export class ToolExecutor { // Check if options contains the text response if (optionsRaw && text && parsePartialArrayString(optionsRaw).includes(text)) { + telemetryService.captureOptionSelected(this.ulid, options.length, "plan") // Valid option selected, don't show user message in UI // Update last followup message with selected option const lastPlanMessage = findLast( @@ -2206,7 +2208,7 @@ export class ToolExecutor { } else { // Option not selected, send user feedback if (text || (images && images.length > 0) || (planResponseFiles && planResponseFiles.length > 0)) { - telemetryService.captureOptionsIgnored(this.taskId, options.length, "plan") + telemetryService.captureOptionsIgnored(this.ulid, options.length, "plan") await this.say("user_feedback", text ?? "", images, planResponseFiles) await this.saveCheckpoint() } @@ -2350,7 +2352,7 @@ export class ToolExecutor { await this.say("completion_result", result, undefined, undefined, false) await this.saveCheckpoint(true) await addNewChangesFlagToLastCompletionResultMessage() - telemetryService.captureTaskCompleted(this.taskId, this.ulid) + telemetryService.captureTaskCompleted(this.ulid) } else { // we already sent a command message, meaning the complete completion message has also been sent await this.saveCheckpoint(true) @@ -2375,7 +2377,7 @@ export class ToolExecutor { await this.say("completion_result", result, undefined, undefined, false) await this.saveCheckpoint(true) await addNewChangesFlagToLastCompletionResultMessage() - telemetryService.captureTaskCompleted(this.taskId, this.ulid) + telemetryService.captureTaskCompleted(this.ulid) } // we already sent completion_result says, an empty string asks relinquishes control over button and field diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 9f08a20e..f165baba 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -238,7 +238,7 @@ export class Task { // Prepare effective API configuration const effectiveApiConfiguration: ApiConfiguration = { ...apiConfiguration, - taskId: this.taskId, + ulid: this.ulid, onRetryAttempt: async (attempt: number, maxRetries: number, delay: number, error: any) => { const clineMessages = this.messageStateHandler.getClineMessages() const lastApiReqStartedIndex = findLastIndex(clineMessages, (m) => m.say === "api_req_started") @@ -283,11 +283,11 @@ export class Task { } } - // Now that taskId is initialized, we can build the API handler + // Now that ulid is initialized, we can build the API handler this.api = buildApiHandler(effectiveApiConfiguration, this.mode) - // Set taskId on browserSession for telemetry tracking - this.browserSession.setTaskId(this.taskId) + // Set ulid on browserSession for telemetry tracking + this.browserSession.setUlid(this.ulid) // Continue with task initialization if (historyItem) { @@ -299,10 +299,10 @@ export class Task { // initialize telemetry if (historyItem) { // Open task from history - telemetryService.captureTaskRestarted(this.taskId, this.ulid, currentProvider) + telemetryService.captureTaskRestarted(this.ulid, currentProvider) } else { // New task started - telemetryService.captureTaskCreated(this.taskId, this.ulid, currentProvider) + telemetryService.captureTaskCreated(this.ulid, currentProvider) } this.toolExecutor = new ToolExecutor( @@ -2105,7 +2105,7 @@ export class Task { content: userContent, }) - telemetryService.captureConversationTurnEvent(this.taskId, this.ulid, providerId, modelId, "user") + telemetryService.captureConversationTurnEvent(this.ulid, providerId, modelId, "user") // since we sent off a placeholder api_req_started message to update the webview while waiting to actually start the API request (to load potential details for example), we need to update the text of that message const lastApiReqIndex = findLastIndex(this.messageStateHandler.getClineMessages(), (m) => m.say === "api_req_started") @@ -2170,20 +2170,13 @@ export class Task { }) await this.messageStateHandler.saveClineMessagesAndUpdateHistory() - telemetryService.captureConversationTurnEvent( - this.taskId, - this.ulid, - providerId, - this.api.getModel().id, - "assistant", - { - tokensIn: inputTokens, - tokensOut: outputTokens, - cacheWriteTokens, - cacheReadTokens, - totalCost, - }, - ) + telemetryService.captureConversationTurnEvent(this.ulid, providerId, this.api.getModel().id, "assistant", { + tokensIn: inputTokens, + tokensOut: outputTokens, + cacheWriteTokens, + cacheReadTokens, + totalCost, + }) // signals to provider that it can retrieve the saved messages from disk, as abortTask can not be awaited on in nature this.taskState.didFinishAbortingStream = true @@ -2352,7 +2345,7 @@ export class Task { // need to save assistant responses to file before proceeding to tool use since user can exit at any moment and we wouldn't be able to save the assistant's response let didEndLoop = false if (assistantMessage.length > 0) { - telemetryService.captureConversationTurnEvent(this.taskId, this.ulid, providerId, modelId, "assistant", { + telemetryService.captureConversationTurnEvent(this.ulid, providerId, modelId, "assistant", { tokensIn: inputTokens, tokensOut: outputTokens, cacheWriteTokens, diff --git a/src/extension.ts b/src/extension.ts index 5b84f370..8e41f097 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -268,7 +268,7 @@ export async function activate(context: vscode.ExtensionContext) { languageId, Array.isArray(diagnostics) ? diagnostics : undefined, ) - telemetryService.captureButtonClick("codeAction_addToChat", activeWebview?.controller.task?.taskId) + telemetryService.captureButtonClick("codeAction_addToChat", activeWebview?.controller.task?.ulid) }), ) @@ -443,7 +443,7 @@ export async function activate(context: vscode.ExtensionContext) { // Send to last active instance with diagnostics const activeWebview = WebviewProvider.getLastActiveInstance() await activeWebview?.controller.fixWithCline(selectedText, filePath, languageId, diagnostics) - telemetryService.captureButtonClick("codeAction_fixWithCline", activeWebview?.controller.task?.taskId) + telemetryService.captureButtonClick("codeAction_fixWithCline", activeWebview?.controller.task?.ulid) }), ) @@ -468,7 +468,7 @@ export async function activate(context: vscode.ExtensionContext) { const fileMention = activeWebview?.controller.getFileMentionFromPath(filePath) || filePath const prompt = `Explain the following code from ${fileMention}:\n\`\`\`${editor.document.languageId}\n${selectedText}\n\`\`\`` await activeWebview?.controller.initTask(prompt) - telemetryService.captureButtonClick("codeAction_explainCode", activeWebview?.controller.task?.taskId) + telemetryService.captureButtonClick("codeAction_explainCode", activeWebview?.controller.task?.ulid) }), ) @@ -493,7 +493,7 @@ export async function activate(context: vscode.ExtensionContext) { const fileMention = activeWebview?.controller.getFileMentionFromPath(filePath) || filePath const prompt = `Improve the following code from ${fileMention} (e.g., suggest refactorings, optimizations, or better practices):\n\`\`\`${editor.document.languageId}\n${selectedText}\n\`\`\`` await activeWebview?.controller.initTask(prompt) - telemetryService.captureButtonClick("codeAction_improveCode", activeWebview?.controller.task?.taskId) + telemetryService.captureButtonClick("codeAction_improveCode", activeWebview?.controller.task?.ulid) }), ) @@ -544,7 +544,7 @@ export async function activate(context: vscode.ExtensionContext) { } sendFocusChatInputEvent(clientId) - telemetryService.captureButtonClick("command_focusChatInput", activeWebview.controller?.task?.taskId) + telemetryService.captureButtonClick("command_focusChatInput", activeWebview.controller?.task?.ulid) }), ) diff --git a/src/services/browser/BrowserSession.ts b/src/services/browser/BrowserSession.ts index cee45e6a..a6b00b02 100644 --- a/src/services/browser/BrowserSession.ts +++ b/src/services/browser/BrowserSession.ts @@ -46,7 +46,7 @@ export class BrowserSession { // Telemetry tracking properties private sessionStartTime: number = 0 private browserActions: string[] = [] - private taskId?: string + private ulid?: string constructor(context: vscode.ExtensionContext, browserSettings: BrowserSettings, useWebp: boolean = true) { this.context = context @@ -171,11 +171,11 @@ export class BrowserSession { } /** - * Set the task ID for telemetry tracking - * @param taskId The task ID to associate with browser actions + * Set the ULID for telemetry tracking + * @param ulid The task ID to associate with browser actions */ - setTaskId(taskId: string) { - this.taskId = taskId + setUlid(ulid: string) { + this.ulid = ulid } async launchBrowser() { @@ -197,8 +197,8 @@ export class BrowserSession { // Don't create a new page here, as we'll create it in launchRemoteBrowser // Send telemetry for browser tool start - if (this.taskId) { - telemetryService.captureBrowserToolStart(this.taskId, this.browserSettings) + if (this.ulid) { + telemetryService.captureBrowserToolStart(this.ulid, this.browserSettings) } return @@ -206,9 +206,9 @@ export class BrowserSession { console.error("Failed to launch remote browser, falling back to local mode:", error) // Capture error telemetry - if (this.taskId) { + if (this.ulid) { telemetryService.captureBrowserError( - this.taskId, + this.ulid, "remote_browser_launch_error", error instanceof Error ? error.message : String(error), { @@ -228,8 +228,8 @@ export class BrowserSession { this.page = await this.browser?.newPage() // Send telemetry for browser tool start - if (this.taskId) { - telemetryService.captureBrowserToolStart(this.taskId, this.browserSettings) + if (this.ulid) { + telemetryService.captureBrowserToolStart(this.ulid, this.browserSettings) } } @@ -285,9 +285,9 @@ export class BrowserSession { console.log(`Failed to connect using cached endpoint: ${error}`) // Capture error telemetry - if (this.taskId) { + if (this.ulid) { telemetryService.captureBrowserError( - this.taskId, + this.ulid, "cached_endpoint_connection_error", error instanceof Error ? error.message : String(error), { @@ -337,9 +337,9 @@ export class BrowserSession { console.log(`Failed to connect to remote browser: ${error}`) // Capture error telemetry - if (this.taskId) { + if (this.ulid) { telemetryService.captureBrowserError( - this.taskId, + this.ulid, "remote_host_connection_error", error instanceof Error ? error.message : String(error), { @@ -394,9 +394,9 @@ export class BrowserSession { async closeBrowser(): Promise { if (this.browser || this.page) { // Send telemetry for browser tool end if we have a task ID and session was started - if (this.taskId && this.sessionStartTime > 0) { + if (this.ulid && this.sessionStartTime > 0) { const sessionDuration = Date.now() - this.sessionStartTime - telemetryService.captureBrowserToolEnd(this.taskId, { + telemetryService.captureBrowserToolEnd(this.ulid, { actionCount: this.browserActions.length, duration: sessionDuration, actions: this.browserActions, @@ -466,8 +466,8 @@ export class BrowserSession { logs.push(`[Error] ${errorMessage}`) // Capture error telemetry - if (this.taskId) { - telemetryService.captureBrowserError(this.taskId, "browser_action_error", errorMessage, { + if (this.ulid) { + telemetryService.captureBrowserError(this.ulid, "browser_action_error", errorMessage, { isRemote: this.isConnectedToRemote, action: this.browserActions[this.browserActions.length - 1], }) @@ -511,8 +511,8 @@ export class BrowserSession { if (!screenshotBase64) { // Capture error telemetry - if (this.taskId) { - telemetryService.captureBrowserError(this.taskId, "screenshot_error", "Failed to take screenshot", { + if (this.ulid) { + telemetryService.captureBrowserError(this.ulid, "screenshot_error", "Failed to take screenshot", { isRemote: this.isConnectedToRemote, action: this.browserActions[this.browserActions.length - 1], }) diff --git a/src/services/posthog/telemetry/TelemetryService.ts b/src/services/posthog/telemetry/TelemetryService.ts index 448dc497..937c941f 100644 --- a/src/services/posthog/telemetry/TelemetryService.ts +++ b/src/services/posthog/telemetry/TelemetryService.ts @@ -178,49 +178,48 @@ export class TelemetryService { // Task events /** * Records when a new task/conversation is started - * @param taskId Unique identifier for the new task + * @param ulid Unique identifier for the new task * @param apiProvider Optional API provider */ - public captureTaskCreated(taskId: string, ulid: string, apiProvider?: string) { + public captureTaskCreated(ulid: string, apiProvider?: string) { this.capture({ event: TelemetryService.EVENTS.TASK.CREATED, - properties: { taskId, ulid, apiProvider }, + properties: { ulid, apiProvider }, }) } /** * Records when a task/conversation is restarted - * @param taskId Unique identifier for the new task + * @param ulid Unique identifier for the new task * @param apiProvider Optional API provider */ - public captureTaskRestarted(taskId: string, ulid: string, apiProvider?: string) { + public captureTaskRestarted(ulid: string, apiProvider?: string) { this.capture({ event: TelemetryService.EVENTS.TASK.RESTARTED, - properties: { taskId, ulid, apiProvider }, + properties: { ulid, apiProvider }, }) } /** * Records when cline calls the task completion_result tool signifying that cline is done with the task - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task */ - public captureTaskCompleted(taskId: string, ulid: string) { + public captureTaskCompleted(ulid: string) { this.capture({ event: TelemetryService.EVENTS.TASK.COMPLETED, - properties: { taskId, ulid }, + properties: { ulid }, }) } /** * Captures that a message was sent, and includes the API provider and model used - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param provider The API provider (e.g., OpenAI, Anthropic) * @param model The specific model used (e.g., GPT-4, Claude) * @param source The source of the message ("user" | "model"). Used to track message patterns and identify when users need to correct the model's responses. * @param tokenUsage Optional token usage data */ public captureConversationTurnEvent( - taskId: string, ulid: string, provider: string = "unknown", model: string = "unknown", @@ -234,13 +233,12 @@ export class TelemetryService { } = {}, ) { // Ensure required parameters are provided - if (!taskId || !ulid || !provider || !model || !source) { + if (!ulid || !provider || !model || !source) { console.warn("TelemetryService: Missing required parameters for message capture") return } const properties: Record = { - taskId, ulid, provider, model, @@ -257,16 +255,16 @@ export class TelemetryService { /** * Records token usage metrics for cost tracking and usage analysis - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param tokensIn Number of input tokens consumed * @param tokensOut Number of output tokens generated * @param model The model used for token calculation */ - public captureTokenUsage(taskId: string, tokensIn: number, tokensOut: number, model: string) { + public captureTokenUsage(ulid: string, tokensIn: number, tokensOut: number, model: string) { this.capture({ event: TelemetryService.EVENTS.TASK.TOKEN_USAGE, properties: { - taskId, + ulid, tokensIn, tokensOut, model, @@ -276,14 +274,14 @@ export class TelemetryService { /** * Records when a task switches between plan and act modes - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param mode The mode being switched to (plan or act) */ - public captureModeSwitch(taskId: string, mode: Mode) { + public captureModeSwitch(ulid: string, mode: Mode) { this.capture({ event: TelemetryService.EVENTS.TASK.MODE_SWITCH, properties: { - taskId, + ulid, mode, }, }) @@ -291,18 +289,18 @@ export class TelemetryService { /** * Records user feedback on completed tasks - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param feedbackType The type of feedback ("thumbs_up" or "thumbs_down") */ - public captureTaskFeedback(taskId: string, feedbackType: TaskFeedbackType) { + public captureTaskFeedback(ulid: string, feedbackType: TaskFeedbackType) { console.info("TelemetryService: Capturing task feedback", { - taskId, + ulid, feedbackType, }) this.capture({ event: TelemetryService.EVENTS.TASK.FEEDBACK, properties: { - taskId, + ulid, feedbackType, }, }) @@ -311,16 +309,16 @@ export class TelemetryService { // Tool events /** * Records when a tool is used during task execution - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param tool Name of the tool being used * @param autoApproved Whether the tool was auto-approved based on settings * @param success Whether the tool execution was successful */ - public captureToolUsage(taskId: string, tool: string, modelId: string, autoApproved: boolean, success: boolean) { + public captureToolUsage(ulid: string, tool: string, modelId: string, autoApproved: boolean, success: boolean) { this.capture({ event: TelemetryService.EVENTS.TASK.TOOL_USED, properties: { - taskId, + ulid, tool, autoApproved, success, @@ -331,12 +329,12 @@ export class TelemetryService { /** * Records interactions with the git-based checkpoint system - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param action The type of checkpoint action * @param durationMs Optional duration of the operation in milliseconds */ public captureCheckpointUsage( - taskId: string, + ulid: string, action: "shadow_git_initialized" | "commit_created" | "restored" | "diff_generated", durationMs?: number, ) { @@ -347,7 +345,7 @@ export class TelemetryService { this.capture({ event: TelemetryService.EVENTS.TASK.CHECKPOINT_USED, properties: { - taskId, + ulid, action, durationMs, }, @@ -356,14 +354,14 @@ export class TelemetryService { /** * Records when a diff edit (replace_in_file) operation fails - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param errorType Type of error that occurred (e.g., "search_not_found", "invalid_format") */ - public captureDiffEditFailure(taskId: string, modelId: string, errorType?: string) { + public captureDiffEditFailure(ulid: string, modelId: string, errorType?: string) { this.capture({ event: TelemetryService.EVENTS.TASK.DIFF_EDIT_FAILED, properties: { - taskId, + ulid, errorType, modelId, }, @@ -374,51 +372,25 @@ export class TelemetryService { * Records when a different model is selected for use * @param model Name of the selected model * @param provider Provider of the selected model - * @param taskId Optional task identifier if model was selected during a task + * @param ulid Optional task identifier if model was selected during a task */ - public captureModelSelected(model: string, provider: string, taskId?: string) { + public captureModelSelected(model: string, provider: string, ulid?: string) { this.capture({ event: TelemetryService.EVENTS.UI.MODEL_SELECTED, properties: { model, provider, - taskId, - }, - }) - } - - /** - * Records when a historical task is loaded from storage - * @param taskId Unique identifier for the historical task - */ - public captureHistoricalTaskLoaded(taskId: string) { - this.capture({ - event: TelemetryService.EVENTS.TASK.HISTORICAL_LOADED, - properties: { - taskId, - }, - }) - } - - /** - * Records when the retry button is clicked for failed operations - * @param taskId Unique identifier for the task being retried - */ - public captureRetryClicked(taskId: string) { - this.capture({ - event: TelemetryService.EVENTS.TASK.RETRY_CLICKED, - properties: { - taskId, + ulid, }, }) } /** * Records when the browser tool is started - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param browserSettings The browser settings being used */ - public captureBrowserToolStart(taskId: string, browserSettings: BrowserSettings) { + public captureBrowserToolStart(ulid: string, browserSettings: BrowserSettings) { if (!this.isCategoryEnabled("browser")) { return } @@ -426,7 +398,7 @@ export class TelemetryService { this.capture({ event: TelemetryService.EVENTS.TASK.BROWSER_TOOL_START, properties: { - taskId, + ulid, viewport: browserSettings.viewport, isRemote: !!browserSettings.remoteBrowserEnabled, remoteBrowserHost: browserSettings.remoteBrowserHost, @@ -437,11 +409,11 @@ export class TelemetryService { /** * Records when the browser tool is completed - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param stats Statistics about the browser session */ public captureBrowserToolEnd( - taskId: string, + ulid: string, stats: { actionCount: number duration: number @@ -455,7 +427,7 @@ export class TelemetryService { this.capture({ event: TelemetryService.EVENTS.TASK.BROWSER_TOOL_END, properties: { - taskId, + ulid, actionCount: stats.actionCount, duration: stats.duration, actions: stats.actions, @@ -466,13 +438,13 @@ export class TelemetryService { /** * Records when browser errors occur during a task - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param errorType Type of error that occurred (e.g., "launch_error", "connection_error", "navigation_error") * @param errorMessage The error message * @param context Additional context about where the error occurred */ public captureBrowserError( - taskId: string, + ulid: string, errorType: string, errorMessage: string, context?: { @@ -489,7 +461,7 @@ export class TelemetryService { this.capture({ event: TelemetryService.EVENTS.TASK.BROWSER_ERROR, properties: { - taskId, + ulid, errorType, errorMessage, context, @@ -500,15 +472,15 @@ export class TelemetryService { /** * Records when a user selects an option from AI-generated followup questions - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param qty The quantity of options that were presented * @param mode The mode in which the option was selected ("plan" or "act") */ - public captureOptionSelected(taskId: string, qty: number, mode: Mode) { + public captureOptionSelected(ulid: string, qty: number, mode: Mode) { this.capture({ event: TelemetryService.EVENTS.TASK.OPTION_SELECTED, properties: { - taskId, + ulid, qty, mode, }, @@ -517,15 +489,15 @@ export class TelemetryService { /** * Records when a user types a custom response instead of selecting one of the AI-generated followup questions - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param qty The quantity of options that were presented * @param mode The mode in which the custom response was provided ("plan" or "act") */ - public captureOptionsIgnored(taskId: string, qty: number, mode: Mode) { + public captureOptionsIgnored(ulid: string, qty: number, mode: Mode) { this.capture({ event: TelemetryService.EVENTS.TASK.OPTIONS_IGNORED, properties: { - taskId, + ulid, qty, mode, }, @@ -534,12 +506,12 @@ export class TelemetryService { /** * Captures Gemini API performance metrics. - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param modelId Specific Gemini model ID * @param data Performance data including TTFT, durations, token counts, cache stats, and API success status */ public captureGeminiApiPerformance( - taskId: string, + ulid: string, modelId: string, data: { ttftSec?: number @@ -557,7 +529,7 @@ export class TelemetryService { this.capture({ event: TelemetryService.EVENTS.TASK.GEMINI_API_PERFORMANCE, properties: { - taskId, + ulid, modelId, ...data, }, @@ -579,19 +551,19 @@ export class TelemetryService { }) } - public captureButtonClick(button: string, taskId?: string) { + public captureButtonClick(button: string, ulid?: string) { this.capture({ event: TelemetryService.EVENTS.UI.BUTTON_CLICKED, properties: { button, - taskId, + ulid, }, }) } /** * Records telemetry when an API provider returns an error - * @param taskId Unique identifier for the task + * @param ulid Unique identifier for the task * @param model Identifier of the model used * @param requestId Unique identifier for the specific API request * @param errorMessage Detailed error message from the API provider @@ -599,7 +571,6 @@ export class TelemetryService { * @param collect Optional flag to determine if the event should be collected for batch sending */ public captureProviderApiError(args: { - taskId: string ulid: string model: string errorMessage: string diff --git a/src/shared/api.ts b/src/shared/api.ts index e90a9df9..f5074a04 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -37,7 +37,7 @@ export interface ApiHandlerOptions { // Global configuration (not mode-specific) apiKey?: string // anthropic clineAccountId?: string - taskId?: string // Used to identify the task in API requests + ulid?: string // Used to identify the task in API requests liteLlmBaseUrl?: string liteLlmApiKey?: string liteLlmUsePromptCache?: boolean diff --git a/src/shared/proto-conversions/models/api-configuration-conversion.ts b/src/shared/proto-conversions/models/api-configuration-conversion.ts index 6721a15a..ced8dc30 100644 --- a/src/shared/proto-conversions/models/api-configuration-conversion.ts +++ b/src/shared/proto-conversions/models/api-configuration-conversion.ts @@ -329,7 +329,7 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA // Global configuration fields apiKey: config.apiKey, clineAccountId: config.clineAccountId, - taskId: config.taskId, + ulid: config.ulid, liteLlmBaseUrl: config.liteLlmBaseUrl, liteLlmApiKey: config.liteLlmApiKey, liteLlmUsePromptCache: config.liteLlmUsePromptCache, @@ -461,7 +461,7 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio // Global configuration fields apiKey: protoConfig.apiKey, clineAccountId: protoConfig.clineAccountId, - taskId: protoConfig.taskId, + ulid: protoConfig.ulid, liteLlmBaseUrl: protoConfig.liteLlmBaseUrl, liteLlmApiKey: protoConfig.liteLlmApiKey, liteLlmUsePromptCache: protoConfig.liteLlmUsePromptCache, diff --git a/src/shared/proto-conversions/state/settings-conversion.ts b/src/shared/proto-conversions/state/settings-conversion.ts index 7c3e00b9..c9e56e4a 100644 --- a/src/shared/proto-conversions/state/settings-conversion.ts +++ b/src/shared/proto-conversions/state/settings-conversion.ts @@ -9,7 +9,7 @@ export function convertApiConfigurationToProtoApiConfiguration(config: ApiConfig // Global configuration fields (not mode-specific) apiKey: config.apiKey, clineAccountId: config.clineAccountId, - taskId: config.taskId, + ulid: config.ulid, liteLlmBaseUrl: config.liteLlmBaseUrl, liteLlmApiKey: config.liteLlmApiKey, liteLlmUsePromptCache: config.liteLlmUsePromptCache, @@ -136,7 +136,7 @@ export function convertProtoApiConfigurationToApiConfiguration(protoConfig: Prot // Global configuration fields (not mode-specific) apiKey: protoConfig.apiKey, clineAccountId: protoConfig.clineAccountId, - taskId: protoConfig.taskId, + ulid: protoConfig.ulid, liteLlmBaseUrl: protoConfig.liteLlmBaseUrl, liteLlmApiKey: protoConfig.liteLlmApiKey, liteLlmUsePromptCache: protoConfig.liteLlmUsePromptCache,