Nighttrek/telemetry task tracking (#2098)

* updated service with specific events

* added telemetry to understand task creation and tool usage and task completion

* updated the telemetry system to track system messages and user messages

* added better message counting telemetry

* removed a create task which was suppose to be a restart

* updated so we can detect task completion properly

* switched to production key

* added changeset

* Modify telemetry signatures

* Fixes

* remove redundant task created

* Update src/services/telemetry/TelemetryService.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Clean up apiconfiguration

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Dennis Bartlett <bartlett.dc.1@gmail.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2025-03-05 13:46:00 -08:00
1 parent faa5e4dd61
commit 8900df7285
4 files changed
+400 -28

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Added support for defined events and tracking of task creation completion message generation and tool usage
+33 -2
View File
@@ -69,6 +69,7 @@ type UserContent = Array<Anthropic.ContentBlockParam>
export class Cline {
readonly taskId: string
readonly apiProvider?: string
api: ApiHandler
private terminalManager: TerminalManager
private urlContentFetcher: UrlContentFetcher
@@ -129,6 +130,7 @@ export class Cline {
console.error("Failed to initialize ClineIgnoreController:", error)
})
this.providerRef = new WeakRef(provider)
this.apiProvider = apiConfiguration.apiProvider
this.api = buildApiHandler(apiConfiguration)
this.terminalManager = new TerminalManager()
this.urlContentFetcher = new UrlContentFetcher(provider.context)
@@ -148,6 +150,14 @@ export class Cline {
} else {
throw new Error("Either historyItem or task/images must be provided")
}
if (historyItem) {
// Open task from history
telemetryService.captureTaskRestarted(this.taskId, this.apiProvider)
} else {
// New task started
telemetryService.captureTaskCreated(this.taskId, this.apiProvider)
}
}
updateBrowserSettings(browserSettings: BrowserSettings) {
@@ -1791,6 +1801,7 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, false)
this.consecutiveAutoApprovedRequestsCount++
telemetryService.captureToolUsage(this.taskId, block.name, true, true)
// we need an artificial delay to let the diagnostics catch up to the changes
await delay(3_500)
@@ -1800,7 +1811,6 @@ export class Cline {
`Cline wants to ${fileExists ? "edit" : "create"} ${path.basename(relPath)}`,
)
this.removeLastPartialMessageIfExistsWithType("say", "tool")
// const didApprove = await askApproval("tool", completeMessage)
// Need a more customized tool response for file edits to highlight the fact that the file was not updated (particularly important for deepseek)
let didApprove = true
@@ -1818,17 +1828,18 @@ export class Cline {
}
this.didRejectTool = true
didApprove = false
telemetryService.captureToolUsage(this.taskId, block.name, false, false)
} else {
// User hit the approve button, and may have provided feedback
if (text || images?.length) {
pushAdditionalToolFeedback(text, images)
await this.say("user_feedback", text, images)
}
telemetryService.captureToolUsage(this.taskId, block.name, false, true)
}
if (!didApprove) {
await this.diffViewProvider.revertChanges()
break
}
}
@@ -1936,6 +1947,7 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, 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.consecutiveAutoApprovedRequestsCount++
telemetryService.captureToolUsage(this.taskId, block.name, true, true)
} else {
showNotificationForApprovalIfAutoApprovalEnabled(
`Cline wants to read ${path.basename(absolutePath)}`,
@@ -1943,8 +1955,10 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("say", "tool")
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
telemetryService.captureToolUsage(this.taskId, block.name, false, false)
break
}
telemetryService.captureToolUsage(this.taskId, block.name, false, true)
}
// now execute the tool like normal
const content = await extractTextFromFile(absolutePath)
@@ -2007,6 +2021,7 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, false)
this.consecutiveAutoApprovedRequestsCount++
telemetryService.captureToolUsage(this.taskId, block.name, true, true)
} else {
showNotificationForApprovalIfAutoApprovalEnabled(
`Cline wants to view directory ${path.basename(absolutePath)}/`,
@@ -2014,8 +2029,10 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("say", "tool")
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
telemetryService.captureToolUsage(this.taskId, block.name, false, false)
break
}
telemetryService.captureToolUsage(this.taskId, block.name, false, true)
}
pushToolResult(result)
@@ -2071,6 +2088,7 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, false)
this.consecutiveAutoApprovedRequestsCount++
telemetryService.captureToolUsage(this.taskId, block.name, true, true)
} else {
showNotificationForApprovalIfAutoApprovalEnabled(
`Cline wants to view source code definitions in ${path.basename(absolutePath)}/`,
@@ -2078,8 +2096,10 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("say", "tool")
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
telemetryService.captureToolUsage(this.taskId, block.name, false, false)
break
}
telemetryService.captureToolUsage(this.taskId, block.name, false, true)
}
pushToolResult(result)
@@ -2147,6 +2167,7 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, false)
this.consecutiveAutoApprovedRequestsCount++
telemetryService.captureToolUsage(this.taskId, block.name, true, true)
} else {
showNotificationForApprovalIfAutoApprovalEnabled(
`Cline wants to search files in ${path.basename(absolutePath)}/`,
@@ -2154,8 +2175,10 @@ export class Cline {
this.removeLastPartialMessageIfExistsWithType("say", "tool")
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
telemetryService.captureToolUsage(this.taskId, block.name, false, false)
break
}
telemetryService.captureToolUsage(this.taskId, block.name, false, true)
}
pushToolResult(results)
@@ -2831,6 +2854,7 @@ export class Cline {
await this.say("completion_result", result, undefined, false)
await this.saveCheckpoint(true)
await addNewChangesFlagToLastCompletionResultMessage()
telemetryService.captureTaskCompleted(this.taskId)
} else {
// we already sent a command message, meaning the complete completion message has also been sent
await this.saveCheckpoint(true)
@@ -2853,6 +2877,7 @@ export class Cline {
await this.say("completion_result", result, undefined, false)
await this.saveCheckpoint(true)
await addNewChangesFlagToLastCompletionResultMessage()
telemetryService.captureTaskCompleted(this.taskId)
}
// we already sent completion_result says, an empty string asks relinquishes control over button and field
@@ -3035,6 +3060,8 @@ export class Cline {
content: userContent,
})
telemetryService.captureConversationTurnEvent(this.taskId, this.apiProvider, this.api.getModel().id, "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.clineMessages, (m) => m.say === "api_req_started")
this.clineMessages[lastApiReqIndex].text = JSON.stringify({
@@ -3110,6 +3137,8 @@ export class Cline {
updateApiReqMsg(cancelReason, streamingFailedMessage)
await this.saveClineMessages()
telemetryService.captureConversationTurnEvent(this.taskId, this.apiProvider, this.api.getModel().id, "assistant")
// signals to provider that it can retrieve the saved messages from disk, as abortTask can not be awaited on in nature
this.didFinishAbortingStream = true
}
@@ -3233,6 +3262,8 @@ export class Cline {
// 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.apiProvider, this.api.getModel().id, "assistant")
await this.addToApiConversationHistory({
role: "assistant",
content: [{ type: "text", text: assistantMessage }],
+3 -20
View File
@@ -290,16 +290,6 @@ export class ClineProvider implements vscode.WebviewViewProvider {
task,
images,
)
// New task started
if (telemetryService.isTelemetryEnabled()) {
telemetryService.capture({
event: "New task started",
properties: {
apiProvider: apiConfiguration.apiProvider,
},
})
}
}
async initClineWithHistoryItem(historyItem: HistoryItem) {
@@ -317,16 +307,6 @@ export class ClineProvider implements vscode.WebviewViewProvider {
undefined,
historyItem,
)
// Open task from history
if (telemetryService.isTelemetryEnabled()) {
telemetryService.capture({
event: "Open task from history",
properties: {
apiProvider: apiConfiguration.apiProvider,
},
})
}
}
// Send any JSON serializable data to the react app
@@ -1000,6 +980,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
async togglePlanActModeWithChatSettings(chatSettings: ChatSettings, chatContent?: ChatContent) {
const didSwitchToActMode = chatSettings.mode === "act"
// Capture mode switch telemetry | Capture regardless of if we know the taskId
telemetryService.captureModeSwitch(this.cline?.taskId ?? "0", chatSettings.mode)
// Get previous model info that we will revert to after saving current mode api info
const {
apiConfiguration,
+359 -6
View File
@@ -1,12 +1,75 @@
import { PostHog } from "posthog-node"
import * as vscode from "vscode"
/**
* PostHogClient handles telemetry event tracking for the Cline extension
* Uses PostHog analytics to track user interactions and system events
* Respects user privacy settings and VSCode's global telemetry configuration
*/
class PostHogClient {
// Event constants for tracking user interactions and system events
private static readonly EVENTS = {
// Task-related events for tracking conversation and execution flow
TASK: {
// Tracks when a new task/conversation is started
CREATED: "task.created",
// Tracks when a task is reopened
RESTARTED: "task.restarted",
// Tracks when a task is finished, with acceptance or rejection status
COMPLETED: "task.completed",
// Tracks when a message is sent in a conversation
CONVERSATION_TURN: "task.conversation_turn",
// Tracks token consumption for cost and usage analysis
TOKEN_USAGE: "task.tokens",
// Tracks switches between plan and act modes
MODE_SWITCH: "task.mode",
// Tracks usage of the git-based checkpoint system (create/restore/delete)
CHECKPOINT_USED: "task.checkpoint_used",
// Tracks when tools (like file operations, commands) are used
TOOL_USED: "task.tool_used",
// Tracks when a historical task is loaded from storage
HISTORICAL_LOADED: "task.historical_loaded",
// Tracks when the retry button is clicked for failed operations
RETRY_CLICKED: "task.retry_clicked",
},
// UI interaction events for tracking user engagement
UI: {
// Tracks when user switches between API providers
PROVIDER_SWITCH: "ui.provider_switch",
// Tracks when images are attached to a conversation
IMAGE_ATTACHED: "ui.image_attached",
// Tracks general button click interactions
BUTTON_CLICK: "ui.button_click",
// Tracks when the marketplace view is opened
MARKETPLACE_OPENED: "ui.marketplace_opened",
// Tracks when settings panel is opened
SETTINGS_OPENED: "ui.settings_opened",
// Tracks when task history view is opened
HISTORY_OPENED: "ui.history_opened",
// Tracks when a task is removed from history
TASK_POPPED: "ui.task_popped",
// Tracks when a different model is selected
MODEL_SELECTED: "ui.model_selected",
// Tracks when planning mode is toggled on
PLAN_MODE_TOGGLED: "ui.plan_mode_toggled",
// Tracks when action mode is toggled on
ACT_MODE_TOGGLED: "ui.act_mode_toggled",
},
}
/** Singleton instance of the PostHogClient */
private static instance: PostHogClient
/** PostHog client instance for sending analytics events */
private client: PostHog
/** Unique identifier for the current VSCode instance */
private distinctId: string = vscode.env.machineId
/** Whether telemetry is currently enabled based on user and VSCode settings */
private telemetryEnabled: boolean = false
/**
* Private constructor to enforce singleton pattern
* Initializes PostHog client with configuration
*/
private constructor() {
this.client = new PostHog("phc_qfOAGxZw2TL5O8p9KYd9ak3bPBFzfjC8fy5L6jNWY7K", {
host: "https://us.i.posthog.com",
@@ -14,6 +77,11 @@ class PostHogClient {
})
}
/**
* Updates the telemetry state based on user preferences and VSCode settings
* Only enables telemetry if both VSCode global telemetry is enabled and user has opted in
* @param didUserOptIn Whether the user has explicitly opted into telemetry
*/
public updateTelemetryState(didUserOptIn: boolean): void {
this.telemetryEnabled = false
@@ -26,17 +94,18 @@ class PostHogClient {
this.telemetryEnabled = didUserOptIn
}
// Update PostHog client state based on telemetry preference and use machineId to tie it to the webview
// Update PostHog client state based on telemetry preference
if (this.telemetryEnabled) {
this.client.optIn()
this.client.identify({ distinctId: this.distinctId })
// console.log("Telemetry enabled")
} else {
this.client.optOut()
// console.log("Telemetry disabled")
}
}
/**
* Gets or creates the singleton instance of PostHogClient
* @returns The PostHogClient instance
*/
public static getInstance(): PostHogClient {
if (!PostHogClient.instance) {
PostHogClient.instance = new PostHogClient()
@@ -44,14 +113,299 @@ class PostHogClient {
return PostHogClient.instance
}
/**
* 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 {
// Only send events if telemetry is enabled
if (this.telemetryEnabled) {
this.client.capture({ distinctId: this.distinctId, event: event.event, properties: event.properties })
// console.log("Captured event", { distinctId: this.distinctId, event: event.event, properties: event.properties })
}
}
// Task events
/**
* Records when a new task/conversation is started
* @param taskId Unique identifier for the new task
*/
public captureTaskCreated(taskId: string, apiProvider?: string) {
this.capture({
event: PostHogClient.EVENTS.TASK.CREATED,
properties: { taskId, apiProvider },
})
}
/**
* Records when a task/conversation is restarted
* @param taskId Unique identifier for the new task
*/
public captureTaskRestarted(taskId: string, apiProvider?: string) {
this.capture({
event: PostHogClient.EVENTS.TASK.RESTARTED,
properties: { taskId, 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
*/
public captureTaskCompleted(taskId: string) {
this.capture({
event: PostHogClient.EVENTS.TASK.COMPLETED,
properties: { taskId },
})
}
/**
* Captures that a message was sent, and includes the API provider and model used
* @param taskId 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.
*/
public captureConversationTurnEvent(
taskId: string,
provider: string = "unknown",
model: string = "unknown",
source: "user" | "assistant",
) {
// Ensure required parameters are provided
if (!taskId || !provider || !model || !source) {
console.warn("TelemetryService: Missing required parameters for message capture")
return
}
const properties: Record<string, any> = {
taskId,
provider,
model,
source,
timestamp: new Date().toISOString(), // Add timestamp for message sequencing
}
this.capture({
event: PostHogClient.EVENTS.TASK.CONVERSATION_TURN,
properties,
})
}
/**
* TODO
* Records token usage metrics for cost tracking and usage analysis
* @param taskId 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) {
this.capture({
event: PostHogClient.EVENTS.TASK.TOKEN_USAGE,
properties: {
taskId,
tokensIn,
tokensOut,
model,
},
})
}
/**
* Records when a task switches between plan and act modes
* @param taskId Unique identifier for the task
* @param mode The mode being switched to (plan or act)
*/
public captureModeSwitch(taskId: string, mode: "plan" | "act") {
this.capture({
event: PostHogClient.EVENTS.TASK.MODE_SWITCH,
properties: {
taskId,
mode,
},
})
}
// Tool events
/**
* Records when a tool is used during task execution
* @param taskId 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, autoApproved: boolean, success: boolean) {
this.capture({
event: PostHogClient.EVENTS.TASK.TOOL_USED,
properties: {
taskId,
tool,
autoApproved,
success,
},
})
}
/**
* Records interactions with the git-based checkpoint system
* @param taskId Unique identifier for the task
* @param action The type of checkpoint action (created/restored/deleted)
*/
public captureCheckpointUsage(taskId: string, action: "created" | "restored" | "deleted") {
this.capture({
event: PostHogClient.EVENTS.TASK.CHECKPOINT_USED,
properties: {
taskId,
action,
},
})
}
// UI events
/**
* Records when the user switches between different API providers
* @param from Previous provider name
* @param to New provider name
* @param location Where the switch occurred (settings panel or bottom bar)
* @param taskId Optional task identifier if switch occurred during a task
*/
public captureProviderSwitch(from: string, to: string, location: "settings" | "bottom", taskId?: string) {
this.capture({
event: PostHogClient.EVENTS.UI.PROVIDER_SWITCH,
properties: {
from,
to,
location,
taskId,
},
})
}
/**
* Records when images are attached to a conversation
* @param taskId Unique identifier for the task
* @param imageCount Number of images attached
*/
public captureImageAttached(taskId: string, imageCount: number) {
this.capture({
event: PostHogClient.EVENTS.UI.IMAGE_ATTACHED,
properties: {
taskId,
imageCount,
},
})
}
/**
* Records general button click interactions in the UI
* @param button Identifier for the button that was clicked
* @param taskId Optional task identifier if click occurred during a task
*/
public captureButtonClick(button: string, taskId?: string) {
this.capture({
event: PostHogClient.EVENTS.UI.BUTTON_CLICK,
properties: {
button,
taskId,
},
})
}
/**
* Records when the marketplace view is opened
* @param taskId Optional task identifier if marketplace was opened during a task
*/
public captureMarketplaceOpened(taskId?: string) {
this.capture({
event: PostHogClient.EVENTS.UI.MARKETPLACE_OPENED,
properties: {
taskId,
},
})
}
/**
* Records when the settings panel is opened
* @param taskId Optional task identifier if settings were opened during a task
*/
public captureSettingsOpened(taskId?: string) {
this.capture({
event: PostHogClient.EVENTS.UI.SETTINGS_OPENED,
properties: {
taskId,
},
})
}
/**
* Records when the task history view is opened
* @param taskId Optional task identifier if history was opened during a task
*/
public captureHistoryOpened(taskId?: string) {
this.capture({
event: PostHogClient.EVENTS.UI.HISTORY_OPENED,
properties: {
taskId,
},
})
}
/**
* Records when a task is removed from the task history
* @param taskId Unique identifier for the task being removed
*/
public captureTaskPopped(taskId: string) {
this.capture({
event: PostHogClient.EVENTS.UI.TASK_POPPED,
properties: {
taskId,
},
})
}
/**
* 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
*/
public captureModelSelected(model: string, provider: string, taskId?: string) {
this.capture({
event: PostHogClient.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: PostHogClient.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: PostHogClient.EVENTS.TASK.RETRY_CLICKED,
properties: {
taskId,
},
})
}
public isTelemetryEnabled(): boolean {
return this.telemetryEnabled
}
@@ -61,5 +415,4 @@ class PostHogClient {
}
}
// Export a single instance
export const telemetryService = PostHogClient.getInstance()