extension.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import * as vscode from "vscode"
  2. import * as dotenvx from "@dotenvx/dotenvx"
  3. import * as path from "path"
  4. // Load environment variables from .env file
  5. try {
  6. // Specify path to .env file in the project root directory
  7. const envPath = path.join(__dirname, "..", ".env")
  8. dotenvx.config({ path: envPath })
  9. } catch (e) {
  10. // Silently handle environment loading errors
  11. console.warn("Failed to load environment variables:", e)
  12. }
  13. import type { CloudUserInfo, AuthState } from "@roo-code/types"
  14. import { CloudService, BridgeOrchestrator } from "@roo-code/cloud"
  15. import { TelemetryService, PostHogTelemetryClient } from "@roo-code/telemetry"
  16. import "./utils/path" // Necessary to have access to String.prototype.toPosix.
  17. import { createOutputChannelLogger, createDualLogger } from "./utils/outputChannelLogger"
  18. import { Package } from "./shared/package"
  19. import { formatLanguage } from "./shared/language"
  20. import { ContextProxy } from "./core/config/ContextProxy"
  21. import { ClineProvider } from "./core/webview/ClineProvider"
  22. import { DIFF_VIEW_URI_SCHEME } from "./integrations/editor/DiffViewProvider"
  23. import { TerminalRegistry } from "./integrations/terminal/TerminalRegistry"
  24. import { McpServerManager } from "./services/mcp/McpServerManager"
  25. import { CodeIndexManager } from "./services/code-index/manager"
  26. import { MdmService } from "./services/mdm/MdmService"
  27. import { migrateSettings } from "./utils/migrateSettings"
  28. import { autoImportSettings } from "./utils/autoImportSettings"
  29. import { API } from "./extension/api"
  30. import {
  31. handleUri,
  32. registerCommands,
  33. registerCodeActions,
  34. registerTerminalActions,
  35. CodeActionProvider,
  36. } from "./activate"
  37. import { initializeI18n } from "./i18n"
  38. import { flushModels, getModels, initializeModelCacheRefresh } from "./api/providers/fetchers/modelCache"
  39. /**
  40. * Built using https://github.com/microsoft/vscode-webview-ui-toolkit
  41. *
  42. * Inspired by:
  43. * - https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/default/weather-webview
  44. * - https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/frameworks/hello-world-react-cra
  45. */
  46. let outputChannel: vscode.OutputChannel
  47. let extensionContext: vscode.ExtensionContext
  48. let cloudService: CloudService | undefined
  49. let authStateChangedHandler: ((data: { state: AuthState; previousState: AuthState }) => Promise<void>) | undefined
  50. let settingsUpdatedHandler: (() => void) | undefined
  51. let userInfoHandler: ((data: { userInfo: CloudUserInfo }) => Promise<void>) | undefined
  52. // This method is called when your extension is activated.
  53. // Your extension is activated the very first time the command is executed.
  54. export async function activate(context: vscode.ExtensionContext) {
  55. extensionContext = context
  56. outputChannel = vscode.window.createOutputChannel(Package.outputChannel)
  57. context.subscriptions.push(outputChannel)
  58. outputChannel.appendLine(`${Package.name} extension activated - ${JSON.stringify(Package)}`)
  59. // Migrate old settings to new
  60. await migrateSettings(context, outputChannel)
  61. // Initialize telemetry service.
  62. const telemetryService = TelemetryService.createInstance()
  63. try {
  64. telemetryService.register(new PostHogTelemetryClient())
  65. } catch (error) {
  66. console.warn("Failed to register PostHogTelemetryClient:", error)
  67. }
  68. // Create logger for cloud services.
  69. const cloudLogger = createDualLogger(createOutputChannelLogger(outputChannel))
  70. // Initialize MDM service
  71. const mdmService = await MdmService.createInstance(cloudLogger)
  72. // Initialize i18n for internationalization support.
  73. initializeI18n(context.globalState.get("language") ?? formatLanguage(vscode.env.language))
  74. // Initialize terminal shell execution handlers.
  75. TerminalRegistry.initialize()
  76. // Get default commands from configuration.
  77. const defaultCommands = vscode.workspace.getConfiguration(Package.name).get<string[]>("allowedCommands") || []
  78. // Initialize global state if not already set.
  79. if (!context.globalState.get("allowedCommands")) {
  80. context.globalState.update("allowedCommands", defaultCommands)
  81. }
  82. const contextProxy = await ContextProxy.getInstance(context)
  83. // Initialize code index managers for all workspace folders.
  84. const codeIndexManagers: CodeIndexManager[] = []
  85. if (vscode.workspace.workspaceFolders) {
  86. for (const folder of vscode.workspace.workspaceFolders) {
  87. const manager = CodeIndexManager.getInstance(context, folder.uri.fsPath)
  88. if (manager) {
  89. codeIndexManagers.push(manager)
  90. // Initialize in background; do not block extension activation
  91. void manager.initialize(contextProxy).catch((error) => {
  92. const message = error instanceof Error ? error.message : String(error)
  93. outputChannel.appendLine(
  94. `[CodeIndexManager] Error during background CodeIndexManager configuration/indexing for ${folder.uri.fsPath}: ${message}`,
  95. )
  96. })
  97. context.subscriptions.push(manager)
  98. }
  99. }
  100. }
  101. // Initialize the provider *before* the Roo Code Cloud service.
  102. const provider = new ClineProvider(context, outputChannel, "sidebar", contextProxy, mdmService)
  103. // Initialize Roo Code Cloud service.
  104. const postStateListener = () => ClineProvider.getVisibleInstance()?.postStateToWebview()
  105. authStateChangedHandler = async (data: { state: AuthState; previousState: AuthState }) => {
  106. postStateListener()
  107. if (data.state === "logged-out") {
  108. try {
  109. await provider.remoteControlEnabled(false)
  110. } catch (error) {
  111. cloudLogger(
  112. `[authStateChangedHandler] remoteControlEnabled(false) failed: ${error instanceof Error ? error.message : String(error)}`,
  113. )
  114. }
  115. }
  116. // Handle Roo models cache based on auth state
  117. const handleRooModelsCache = async () => {
  118. try {
  119. // Flush and refresh cache on auth state changes
  120. await flushModels("roo", true)
  121. if (data.state === "active-session") {
  122. cloudLogger(`[authStateChangedHandler] Refreshed Roo models cache for active session`)
  123. } else {
  124. cloudLogger(`[authStateChangedHandler] Flushed Roo models cache on logout`)
  125. }
  126. } catch (error) {
  127. cloudLogger(
  128. `[authStateChangedHandler] Failed to handle Roo models cache: ${error instanceof Error ? error.message : String(error)}`,
  129. )
  130. }
  131. }
  132. if (data.state === "active-session" || data.state === "logged-out") {
  133. await handleRooModelsCache()
  134. // Apply stored provider model to API configuration if present
  135. if (data.state === "active-session") {
  136. try {
  137. const storedModel = context.globalState.get<string>("roo-provider-model")
  138. if (storedModel) {
  139. cloudLogger(`[authStateChangedHandler] Applying stored provider model: ${storedModel}`)
  140. // Get the current API configuration name
  141. const currentConfigName =
  142. provider.contextProxy.getGlobalState("currentApiConfigName") || "default"
  143. // Update it with the stored model using upsertProviderProfile
  144. await provider.upsertProviderProfile(currentConfigName, {
  145. apiProvider: "roo",
  146. apiModelId: storedModel,
  147. })
  148. // Clear the stored model after applying
  149. await context.globalState.update("roo-provider-model", undefined)
  150. cloudLogger(`[authStateChangedHandler] Applied and cleared stored provider model`)
  151. }
  152. } catch (error) {
  153. cloudLogger(
  154. `[authStateChangedHandler] Failed to apply stored provider model: ${error instanceof Error ? error.message : String(error)}`,
  155. )
  156. }
  157. }
  158. }
  159. }
  160. settingsUpdatedHandler = async () => {
  161. const userInfo = CloudService.instance.getUserInfo()
  162. if (userInfo && CloudService.instance.cloudAPI) {
  163. try {
  164. provider.remoteControlEnabled(CloudService.instance.isTaskSyncEnabled())
  165. } catch (error) {
  166. cloudLogger(
  167. `[settingsUpdatedHandler] remoteControlEnabled failed: ${error instanceof Error ? error.message : String(error)}`,
  168. )
  169. }
  170. }
  171. postStateListener()
  172. }
  173. userInfoHandler = async ({ userInfo }: { userInfo: CloudUserInfo }) => {
  174. postStateListener()
  175. if (!CloudService.instance.cloudAPI) {
  176. cloudLogger("[userInfoHandler] CloudAPI is not initialized")
  177. return
  178. }
  179. try {
  180. provider.remoteControlEnabled(CloudService.instance.isTaskSyncEnabled())
  181. } catch (error) {
  182. cloudLogger(
  183. `[userInfoHandler] remoteControlEnabled failed: ${error instanceof Error ? error.message : String(error)}`,
  184. )
  185. }
  186. }
  187. cloudService = await CloudService.createInstance(context, cloudLogger, {
  188. "auth-state-changed": authStateChangedHandler,
  189. "settings-updated": settingsUpdatedHandler,
  190. "user-info": userInfoHandler,
  191. })
  192. try {
  193. if (cloudService.telemetryClient) {
  194. TelemetryService.instance.register(cloudService.telemetryClient)
  195. }
  196. } catch (error) {
  197. outputChannel.appendLine(
  198. `[CloudService] Failed to register TelemetryClient: ${error instanceof Error ? error.message : String(error)}`,
  199. )
  200. }
  201. // Add to subscriptions for proper cleanup on deactivate.
  202. context.subscriptions.push(cloudService)
  203. // Trigger initial cloud profile sync now that CloudService is ready.
  204. try {
  205. await provider.initializeCloudProfileSyncWhenReady()
  206. } catch (error) {
  207. outputChannel.appendLine(
  208. `[CloudService] Failed to initialize cloud profile sync: ${error instanceof Error ? error.message : String(error)}`,
  209. )
  210. }
  211. // Finish initializing the provider.
  212. TelemetryService.instance.setProvider(provider)
  213. context.subscriptions.push(
  214. vscode.window.registerWebviewViewProvider(ClineProvider.sideBarId, provider, {
  215. webviewOptions: { retainContextWhenHidden: true },
  216. }),
  217. )
  218. // Auto-import configuration if specified in settings.
  219. try {
  220. await autoImportSettings(outputChannel, {
  221. providerSettingsManager: provider.providerSettingsManager,
  222. contextProxy: provider.contextProxy,
  223. customModesManager: provider.customModesManager,
  224. })
  225. } catch (error) {
  226. outputChannel.appendLine(
  227. `[AutoImport] Error during auto-import: ${error instanceof Error ? error.message : String(error)}`,
  228. )
  229. }
  230. registerCommands({ context, outputChannel, provider })
  231. /**
  232. * We use the text document content provider API to show the left side for diff
  233. * view by creating a virtual document for the original content. This makes it
  234. * readonly so users know to edit the right side if they want to keep their changes.
  235. *
  236. * This API allows you to create readonly documents in VSCode from arbitrary
  237. * sources, and works by claiming an uri-scheme for which your provider then
  238. * returns text contents. The scheme must be provided when registering a
  239. * provider and cannot change afterwards.
  240. *
  241. * Note how the provider doesn't create uris for virtual documents - its role
  242. * is to provide contents given such an uri. In return, content providers are
  243. * wired into the open document logic so that providers are always considered.
  244. *
  245. * https://code.visualstudio.com/api/extension-guides/virtual-documents
  246. */
  247. const diffContentProvider = new (class implements vscode.TextDocumentContentProvider {
  248. provideTextDocumentContent(uri: vscode.Uri): string {
  249. return Buffer.from(uri.query, "base64").toString("utf-8")
  250. }
  251. })()
  252. context.subscriptions.push(
  253. vscode.workspace.registerTextDocumentContentProvider(DIFF_VIEW_URI_SCHEME, diffContentProvider),
  254. )
  255. context.subscriptions.push(vscode.window.registerUriHandler({ handleUri }))
  256. // Register code actions provider.
  257. context.subscriptions.push(
  258. vscode.languages.registerCodeActionsProvider({ pattern: "**/*" }, new CodeActionProvider(), {
  259. providedCodeActionKinds: CodeActionProvider.providedCodeActionKinds,
  260. }),
  261. )
  262. registerCodeActions(context)
  263. registerTerminalActions(context)
  264. // Allows other extensions to activate once Roo is ready.
  265. vscode.commands.executeCommand(`${Package.name}.activationCompleted`)
  266. // Implements the `RooCodeAPI` interface.
  267. const socketPath = process.env.ROO_CODE_IPC_SOCKET_PATH
  268. const enableLogging = typeof socketPath === "string"
  269. // Watch the core files and automatically reload the extension host.
  270. if (process.env.NODE_ENV === "development") {
  271. const watchPaths = [
  272. { path: context.extensionPath, pattern: "**/*.ts" },
  273. { path: path.join(context.extensionPath, "../packages/types"), pattern: "**/*.ts" },
  274. { path: path.join(context.extensionPath, "../packages/telemetry"), pattern: "**/*.ts" },
  275. { path: path.join(context.extensionPath, "node_modules/@roo-code/cloud"), pattern: "**/*" },
  276. ]
  277. console.log(
  278. `♻️♻️♻️ Core auto-reloading: Watching for changes in ${watchPaths.map(({ path }) => path).join(", ")}`,
  279. )
  280. // Create a debounced reload function to prevent excessive reloads
  281. let reloadTimeout: NodeJS.Timeout | undefined
  282. const DEBOUNCE_DELAY = 1_000
  283. const debouncedReload = (uri: vscode.Uri) => {
  284. if (reloadTimeout) {
  285. clearTimeout(reloadTimeout)
  286. }
  287. console.log(`♻️ ${uri.fsPath} changed; scheduling reload...`)
  288. reloadTimeout = setTimeout(() => {
  289. console.log(`♻️ Reloading host after debounce delay...`)
  290. vscode.commands.executeCommand("workbench.action.reloadWindow")
  291. }, DEBOUNCE_DELAY)
  292. }
  293. watchPaths.forEach(({ path: watchPath, pattern }) => {
  294. const relPattern = new vscode.RelativePattern(vscode.Uri.file(watchPath), pattern)
  295. const watcher = vscode.workspace.createFileSystemWatcher(relPattern, false, false, false)
  296. // Listen to all change types to ensure symlinked file updates trigger reloads.
  297. watcher.onDidChange(debouncedReload)
  298. watcher.onDidCreate(debouncedReload)
  299. watcher.onDidDelete(debouncedReload)
  300. context.subscriptions.push(watcher)
  301. })
  302. // Clean up the timeout on deactivation
  303. context.subscriptions.push({
  304. dispose: () => {
  305. if (reloadTimeout) {
  306. clearTimeout(reloadTimeout)
  307. }
  308. },
  309. })
  310. }
  311. // Initialize background model cache refresh
  312. initializeModelCacheRefresh()
  313. return new API(outputChannel, provider, socketPath, enableLogging)
  314. }
  315. // This method is called when your extension is deactivated.
  316. export async function deactivate() {
  317. outputChannel.appendLine(`${Package.name} extension deactivated`)
  318. if (cloudService && CloudService.hasInstance()) {
  319. try {
  320. if (authStateChangedHandler) {
  321. CloudService.instance.off("auth-state-changed", authStateChangedHandler)
  322. }
  323. if (settingsUpdatedHandler) {
  324. CloudService.instance.off("settings-updated", settingsUpdatedHandler)
  325. }
  326. if (userInfoHandler) {
  327. CloudService.instance.off("user-info", userInfoHandler as any)
  328. }
  329. outputChannel.appendLine("CloudService event handlers cleaned up")
  330. } catch (error) {
  331. outputChannel.appendLine(
  332. `Failed to clean up CloudService event handlers: ${error instanceof Error ? error.message : String(error)}`,
  333. )
  334. }
  335. }
  336. const bridge = BridgeOrchestrator.getInstance()
  337. if (bridge) {
  338. await bridge.disconnect()
  339. }
  340. await McpServerManager.cleanup(extensionContext)
  341. TelemetryService.instance.shutdown()
  342. TerminalRegistry.cleanup()
  343. }