diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 9e5641332..f48e848a9 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; -import { getGlobalContextFilePath } from "./paths"; import { EmbeddingsProvider } from "../"; +import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { indexingPaused: boolean; @@ -37,7 +37,15 @@ export class GlobalContext { ); } else { const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); - const parsed = JSON.parse(data); + + let parsed; + try { + parsed = JSON.parse(data); + } catch (e: any) { + console.warn(`Error updating global context: ${e}`); + return; + } + parsed[key] = value; fs.writeFileSync( getGlobalContextFilePath(), @@ -54,7 +62,12 @@ export class GlobalContext { } const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); - const parsed = JSON.parse(data); - return parsed[key]; + try { + const parsed = JSON.parse(data); + return parsed[key]; + } catch (e: any) { + console.warn(`Error parsing global context: ${e}`); + return undefined; + } } } diff --git a/core/util/history.ts b/core/util/history.ts index 5f4a85e5d..08bc26994 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -3,6 +3,18 @@ import { PersistedSessionInfo, SessionInfo } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { getSessionFilePath, getSessionsListPath } from "./paths.js"; +function safeParseArray( + value: string, + errorMessage: string = "Error parsing array", +): T[] | undefined { + try { + return JSON.parse(value) as T[]; + } catch (e: any) { + console.warn(`${errorMessage}: ${e}`); + return undefined; + } +} + class HistoryManager { list(options: ListHistoryOptions): SessionInfo[] { const filepath = getSessionsListPath(); @@ -10,7 +22,9 @@ class HistoryManager { return []; } const content = fs.readFileSync(filepath, "utf8"); - let sessions = JSON.parse(content).filter((session: any) => { + + let sessions = safeParseArray(content) ?? []; + sessions = sessions.filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; }); @@ -35,14 +49,11 @@ class HistoryManager { // Read and update the sessions list const sessionsListFile = getSessionsListPath(); const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); - let sessionsList: SessionInfo[]; - try { - sessionsList = JSON.parse(sessionsListRaw); - } catch (error) { - throw new Error( - `It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFile}). Please fix this before creating a new session.`, - ); - } + let sessionsList = + safeParseArray( + sessionsListRaw, + "Error parsing sessions.json", + ) ?? []; sessionsList = sessionsList.filter( (session) => session.sessionId !== sessionId, diff --git a/core/util/posthog.ts b/core/util/posthog.ts index c9d329f2b..58828dacd 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -13,22 +13,34 @@ export class Telemetry { event: string, properties: { [key: string]: any }, sendToTeam: boolean = false, + isExtensionActivationError: boolean = false, ) { - if (process.env.NODE_ENV === "test") { - return; - } try { - Telemetry.client?.capture({ + const augmentedProperties = { + ...properties, + os: Telemetry.os, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, + }; + const payload = { distinctId: Telemetry.uniqueId, event, - properties: { - ...properties, - os: Telemetry.os, - extensionVersion: Telemetry.ideInfo?.extensionVersion, - ideName: Telemetry.ideInfo?.name, - ideType: Telemetry.ideInfo?.ideType, - }, - }); + properties: augmentedProperties, + }; + + // In cases where an extremely early fatal error occurs, we may not have initialized yet + if (isExtensionActivationError && !Telemetry.client) { + const client = await Telemetry.getTelemetryClient(); + client?.capture(payload); + return; + } + + if (process.env.NODE_ENV === "test") { + return; + } + + Telemetry.client?.capture(payload); if (sendToTeam) { void TeamAnalytics.capture(event, properties); @@ -42,6 +54,17 @@ export class Telemetry { Telemetry.client?.shutdown(); } + static async getTelemetryClient() { + try { + const { PostHog } = await import("posthog-node"); + return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { + host: "https://app.posthog.com", + }); + } catch (e) { + console.error(`Failed to setup telemetry: ${e}`); + } + } + static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) { Telemetry.uniqueId = uniqueId; Telemetry.os = os.platform(); @@ -49,20 +72,8 @@ export class Telemetry { if (!allow || process.env.NODE_ENV === "test") { Telemetry.client = undefined; - } else { - try { - if (!Telemetry.client) { - const { PostHog } = await import("posthog-node"); - Telemetry.client = new PostHog( - "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", - { - host: "https://app.posthog.com", - }, - ); - } - } catch (e) { - console.error(`Failed to setup telemetry: ${e}`); - } + } else if (!Telemetry.client) { + Telemetry.client = await Telemetry.getTelemetryClient(); } } } diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index cce7bcfbe..864b07cc4 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -1,11 +1,9 @@ -import { getContinueRcPath, getTsConfigPath, migrate } from "core/util/paths"; +import { getContinueRcPath, getTsConfigPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; -import path from "node:path"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; -import { getExtensionUri } from "../util/vscode"; import { VsCodeContinueApi } from "./api"; import { setupInlineTips } from "./inlineTips"; diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index e3967bdb2..9fa7cfb49 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -3,18 +3,31 @@ */ import { setupCa } from "core/util/ca"; +import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { + await setupCa(); const { activateExtension } = await import("./activation/activate"); - try { - return activateExtension(context); - } catch (e) { + return await activateExtension(context); +} + +export function activate(context: vscode.ExtensionContext) { + return dynamicImportAndActivate(context).catch((e) => { console.log("Error activating extension: ", e); + Telemetry.capture( + "vscode_extension_activation_error", + { + stack: extractMinimalStackTraceInfo(e.stack), + message: e.message, + }, + false, + true, + ); vscode.window - .showInformationMessage( + .showWarningMessage( "Error activating the Continue extension.", "View Logs", "Retry", @@ -27,12 +40,7 @@ async function dynamicImportAndActivate(context: vscode.ExtensionContext) { vscode.commands.executeCommand("workbench.action.reloadWindow"); } }); - } -} - -export function activate(context: vscode.ExtensionContext) { - setupCa(); - return dynamicImportAndActivate(context); + }); } export function deactivate() { diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 4b20f8af7..c8f5ee79a 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -94,31 +94,42 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { this.secretStorage = new SecretStorage(context); } - private decodeJwt(jwt: string): any { - const decodedToken = JSON.parse( - Buffer.from(jwt.split(".")[1], "base64").toString(), - ); - return decodedToken; + private decodeJwt(jwt: string): Record | null { + try { + const decodedToken = JSON.parse( + Buffer.from(jwt.split(".")[1], "base64").toString(), + ); + return decodedToken; + } catch (e: any) { + console.warn(`Error decoding JWT: ${e}`); + return null; + } } private getExpirationTimeMs(jwt: string): number { const decodedToken = this.decodeJwt(jwt); + if (!decodedToken) { + return WorkOsAuthProvider.EXPIRATION_TIME_MS; + } return decodedToken.exp && decodedToken.iat ? (decodedToken.exp - decodedToken.iat) * 1000 : WorkOsAuthProvider.EXPIRATION_TIME_MS; } - private jwtIsExpired(jwt: string): boolean { + private jwtIsExpiredOrInvalid(jwt: string): boolean { const decodedToken = this.decodeJwt(jwt); + if (!decodedToken) { + return true; + } return decodedToken.exp * 1000 < Date.now(); } private async debugAccessTokenValidity(jwt: string, refreshToken: string) { - const expired = this.jwtIsExpired(jwt); - if (expired) { - console.debug(`Invalid JWT: ${expired}`); + const expiredOrInvalid = this.jwtIsExpiredOrInvalid(jwt); + if (expiredOrInvalid) { + console.debug("Invalid JWT"); } else { - console.debug(`Valid JWT: ${expired}`); + console.debug("Valid JWT"); } } @@ -135,8 +146,13 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { return []; } - const value = JSON.parse(data) as ContinueAuthenticationSession[]; - return value; + try { + const value = JSON.parse(data) as ContinueAuthenticationSession[]; + return value; + } catch (e: any) { + console.warn(`Error parsing sessions.json: ${e}`); + return []; + } } get onDidChangeSessions() {