diff --git a/src/services/logging/distinctId.test.ts b/src/services/logging/distinctId.test.ts new file mode 100644 index 00000000..628f3ceb --- /dev/null +++ b/src/services/logging/distinctId.test.ts @@ -0,0 +1,124 @@ +import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" +import * as sinon from "sinon" +import * as vscode from "vscode" +import { HostProvider } from "@/hosts/host-provider" +import { getDistinctId, initializeDistinctId, setDistinctId } from "@/services/logging/distinctId" +import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" + +describe("distinctId", () => { + let sandbox: sinon.SinonSandbox + let mockContext: vscode.ExtensionContext + let mockGlobalState: any + + const MOCK_GLOBAL_STATE_ID = "existing-distinct-id-123" + const MOCK_UUID = "mock-uuid-12345678-1234-1234-1234-123456789012" + const MOCK_MACHINE_ID = "machine-id-456" + + const mockUuidGenerator = () => MOCK_UUID + + beforeEach(() => { + sandbox = sinon.createSandbox() + + // Mock global state + mockGlobalState = { + get: sandbox.stub(), + update: sandbox.stub(), + keys: sandbox.stub().returns([]), + setKeysForSync: sandbox.stub(), + } + + // Mock extension context + mockContext = { + globalState: mockGlobalState, + workspaceState: {} as any, + secrets: {} as any, + extensionUri: {} as any, + extensionPath: "", + asAbsolutePath: sandbox.stub(), + storagePath: "", + globalStoragePath: "", + logPath: "", + extensionMode: vscode.ExtensionMode.Development, + subscriptions: [], + environmentVariableCollection: {} as any, + storageUri: {} as any, + globalStorageUri: {} as any, + logUri: {} as any, + extension: {} as any, + } + + // Mock vscode workspace + setVscodeHostProviderMock() + + // Reset the distinctId module state + setDistinctId("") + }) + + afterEach(() => { + sandbox.restore() + // Reset HostProvider after each test to ensure clean state + HostProvider.reset() + }) + + it("should use id from extension globalstate if it exists", async () => { + mockGlobalState.get.withArgs("cline.distinctId").returns(MOCK_GLOBAL_STATE_ID) + const getMachineIdStub = sandbox.stub(HostProvider.env, "getMachineId").resolves({ value: MOCK_MACHINE_ID }) + + await initializeDistinctId(mockContext, mockUuidGenerator) + + expect(getDistinctId()).to.equal(MOCK_GLOBAL_STATE_ID) + expect(getMachineIdStub.calledOnce).to.be.true + }) + + it("should use the host machine ID", async () => { + mockGlobalState.get.withArgs("cline.distinctId").returns(undefined) + + // Mock getMachineId to return a machine ID + const getMachineIdStub = sandbox.stub(HostProvider.env, "getMachineId").resolves({ value: MOCK_MACHINE_ID }) + + await initializeDistinctId(mockContext, mockUuidGenerator) + + expect(getDistinctId()).to.equal(MOCK_MACHINE_ID) + expect(getMachineIdStub.calledOnce).to.be.true + }) + + it("distinct ID should be stable", async () => { + mockGlobalState.get.withArgs("cline.distinctId").returns(undefined) + + // Mock getMachineId to return a machine ID + sandbox.stub(HostProvider.env, "getMachineId").resolves({ value: MOCK_MACHINE_ID }) + + await initializeDistinctId(mockContext, mockUuidGenerator) + expect(getDistinctId()).to.equal(MOCK_MACHINE_ID) + + await initializeDistinctId(mockContext, mockUuidGenerator) + expect(getDistinctId()).to.equal(MOCK_MACHINE_ID) + }) + + it("should generate a UUID if there is no host ID", async () => { + mockGlobalState.get.withArgs("cline.distinctId").returns(undefined) + + // Mock getMachineId to return undefined + const getMachineIdStub = sandbox.stub(HostProvider.env, "getMachineId").resolves({ value: "" }) + + await initializeDistinctId(mockContext, mockUuidGenerator) + + const distinctId = getDistinctId() + expect(distinctId).to.equal(MOCK_UUID) + expect(getMachineIdStub.calledOnce).to.be.true + }) + + it("should handle getMachineId errors gracefully", async () => { + mockGlobalState.get.withArgs("cline.distinctId").returns(undefined) + + // Mock getMachineId to throw an error + const getMachineIdStub = sandbox.stub(HostProvider.env, "getMachineId").rejects(new Error("Network error")) + + await initializeDistinctId(mockContext, mockUuidGenerator) + + const distinctId = getDistinctId() + expect(distinctId).to.equal(MOCK_UUID) + expect(getMachineIdStub.calledOnce).to.be.true + }) +}) diff --git a/src/services/logging/distinctId.ts b/src/services/logging/distinctId.ts index 4e942b73..3d06a2c8 100644 --- a/src/services/logging/distinctId.ts +++ b/src/services/logging/distinctId.ts @@ -5,32 +5,39 @@ import { EmptyRequest } from "@/shared/proto/cline/common" import { Logger } from "./Logger" /* - * Unique identifiers for the current session - * NOTE: Unchanged throughout session + * Unique identifier for the current installation. */ -const _anonymousId = uuidv4() +let _distinctId: string = "" -let _machineId = "" -let _distinctId = "" - -export async function initializeDistinctId(context: ExtensionContext) { +export async function initializeDistinctId(context: ExtensionContext, uuid: () => string = uuidv4) { // NOTE: Backward compatibility in case where cline.distinctId was set in older versions const existingId = context.globalState.get("cline.distinctId") const machineId = await getMachineId() - setDistinctId(existingId || machineId) + let distinctId = existingId || machineId + + if (!distinctId) { + console.warn("No machine ID found, generating UUID") + distinctId = uuid() + } + + setDistinctId(distinctId) + + if (process.env.IS_DEV) { + console.log("Telemetry distinct ID:", distinctId) + } } /* * Host-provided UUID when running via HostBridge; fall back to VS Code's machineId */ -async function getMachineId() { +async function getMachineId(): Promise { try { const response = await HostProvider.env.getMachineId(EmptyRequest.create({})) - _machineId = response.value + return response.value } catch (e) { Logger.warn(`Failed to get machine ID: ${e instanceof Error ? e.message : String(e)}`) + return undefined } - return _distinctId || _anonymousId } /* @@ -38,6 +45,9 @@ async function getMachineId() { * This is updated to Cline User ID when authenticated. */ export function setDistinctId(newId: string) { + if (_distinctId) { + console.log(`Changing telemetry ID from ${_distinctId} to ${newId}.`) + } _distinctId = newId } @@ -46,4 +56,9 @@ export function setDistinctId(newId: string) { * If authenticated, this will be the Cline User ID. * Else, this will be the machine ID, or the anonymous ID as a fallback. */ -export const getDistinctId = () => _distinctId || _machineId || _anonymousId +export function getDistinctId() { + if (!_distinctId) { + console.error("Telemetry ID is not initialized. Call initializeDistinctId() first.") + } + return _distinctId +}