ClaudeDevProvider.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import * as vscode from "vscode"
  2. import { ClaudeDev } from "../ClaudeDev"
  3. import { ApiProvider } from "../shared/api"
  4. import { ExtensionMessage } from "../shared/ExtensionMessage"
  5. import { WebviewMessage } from "../shared/WebviewMessage"
  6. import { downloadTask, getNonce, getUri, selectImages } from "../utils"
  7. /*
  8. https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
  9. https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/customSidebarViewProvider.ts
  10. */
  11. type SecretKey = "apiKey" | "openRouterApiKey" | "awsAccessKey" | "awsSecretKey"
  12. type GlobalStateKey = "apiProvider" | "awsRegion" | "maxRequestsPerTask" | "lastShownAnnouncementId"
  13. export class ClaudeDevProvider implements vscode.WebviewViewProvider {
  14. public static readonly sideBarId = "claude-dev.SidebarProvider" // used in package.json as the view's id. This value cannot be changed due to how vscode caches views based on their id, and updating the id would break existing instances of the extension.
  15. public static readonly tabPanelId = "claude-dev.TabPanelProvider"
  16. private disposables: vscode.Disposable[] = []
  17. private view?: vscode.WebviewView | vscode.WebviewPanel
  18. private claudeDev?: ClaudeDev
  19. private latestAnnouncementId = "aug-10-2024" // update to some unique identifier when we add a new announcement
  20. constructor(
  21. private readonly context: vscode.ExtensionContext,
  22. private readonly outputChannel: vscode.OutputChannel
  23. ) {
  24. this.outputChannel.appendLine("ClaudeDevProvider instantiated")
  25. }
  26. /*
  27. VSCode extensions use the disposable pattern to clean up resources when the sidebar/editor tab is closed by the user or system. This applies to event listening, commands, interacting with the UI, etc.
  28. - https://vscode-docs.readthedocs.io/en/stable/extensions/patterns-and-principles/
  29. - https://github.com/microsoft/vscode-extension-samples/blob/main/webview-sample/src/extension.ts
  30. */
  31. async dispose() {
  32. this.outputChannel.appendLine("Disposing ClaudeDevProvider...")
  33. await this.clearTask()
  34. this.outputChannel.appendLine("Cleared task")
  35. if (this.view && "dispose" in this.view) {
  36. this.view.dispose()
  37. this.outputChannel.appendLine("Disposed webview")
  38. }
  39. while (this.disposables.length) {
  40. const x = this.disposables.pop()
  41. if (x) {
  42. x.dispose()
  43. }
  44. }
  45. this.outputChannel.appendLine("Disposed all disposables")
  46. }
  47. resolveWebviewView(
  48. webviewView: vscode.WebviewView | vscode.WebviewPanel
  49. //context: vscode.WebviewViewResolveContext<unknown>, used to recreate a deallocated webview, but we don't need this since we use retainContextWhenHidden
  50. //token: vscode.CancellationToken
  51. ): void | Thenable<void> {
  52. this.outputChannel.appendLine("Resolving webview view")
  53. this.view = webviewView
  54. webviewView.webview.options = {
  55. // Allow scripts in the webview
  56. enableScripts: true,
  57. localResourceRoots: [this.context.extensionUri],
  58. }
  59. webviewView.webview.html = this.getHtmlContent(webviewView.webview)
  60. // Sets up an event listener to listen for messages passed from the webview view context
  61. // and executes code based on the message that is recieved
  62. this.setWebviewMessageListener(webviewView.webview)
  63. // Logs show up in bottom panel > Debug Console
  64. //console.log("registering listener")
  65. // Listen for when the panel becomes visible
  66. // https://github.com/microsoft/vscode-discussions/discussions/840
  67. if ("onDidChangeViewState" in webviewView) {
  68. // WebviewView and WebviewPanel have all the same properties except for this visibility listener
  69. // panel
  70. webviewView.onDidChangeViewState(
  71. () => {
  72. if (this.view?.visible) {
  73. this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
  74. }
  75. },
  76. null,
  77. this.disposables
  78. )
  79. } else if ("onDidChangeVisibility" in webviewView) {
  80. // sidebar
  81. webviewView.onDidChangeVisibility(
  82. () => {
  83. if (this.view?.visible) {
  84. this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
  85. }
  86. },
  87. null,
  88. this.disposables
  89. )
  90. }
  91. // Listen for when the view is disposed
  92. // This happens when the user closes the view or when the view is closed programmatically
  93. webviewView.onDidDispose(
  94. async () => {
  95. await this.dispose()
  96. },
  97. null,
  98. this.disposables
  99. )
  100. // Listen for when color changes
  101. vscode.workspace.onDidChangeConfiguration(
  102. (e) => {
  103. if (e && e.affectsConfiguration("workbench.colorTheme")) {
  104. // Sends latest theme name to webview
  105. this.postStateToWebview()
  106. }
  107. },
  108. null,
  109. this.disposables
  110. )
  111. // if the extension is starting a new session, clear previous task state
  112. this.clearTask()
  113. // Clear previous version's (0.0.6) claudeMessage cache from workspace state. We now store in global state with a unique identifier for each provider instance. We need to store globally rather than per workspace to eventually implement task history
  114. this.updateWorkspaceState("claudeMessages", undefined)
  115. this.outputChannel.appendLine("Webview view resolved")
  116. }
  117. async initClaudeDevWithTask(task?: string, images?: string[]) {
  118. await this.clearTask() // ensures that an exising task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
  119. const { apiProvider, apiKey, openRouterApiKey, awsAccessKey, awsSecretKey, awsRegion, maxRequestsPerTask } =
  120. await this.getState()
  121. this.claudeDev = new ClaudeDev(
  122. this,
  123. { apiProvider, apiKey, openRouterApiKey, awsAccessKey, awsSecretKey, awsRegion },
  124. maxRequestsPerTask,
  125. task,
  126. images
  127. )
  128. }
  129. // Send any JSON serializable data to the react app
  130. async postMessageToWebview(message: ExtensionMessage) {
  131. await this.view?.webview.postMessage(message)
  132. }
  133. /**
  134. * Defines and returns the HTML that should be rendered within the webview panel.
  135. *
  136. * @remarks This is also the place where references to the React webview build files
  137. * are created and inserted into the webview HTML.
  138. *
  139. * @param webview A reference to the extension webview
  140. * @param extensionUri The URI of the directory containing the extension
  141. * @returns A template string literal containing the HTML that should be
  142. * rendered within the webview panel
  143. */
  144. private getHtmlContent(webview: vscode.Webview): string {
  145. // Get the local path to main script run in the webview,
  146. // then convert it to a uri we can use in the webview.
  147. // The CSS file from the React build output
  148. const stylesUri = getUri(webview, this.context.extensionUri, [
  149. "webview-ui",
  150. "build",
  151. "static",
  152. "css",
  153. "main.css",
  154. ])
  155. // The JS file from the React build output
  156. const scriptUri = getUri(webview, this.context.extensionUri, ["webview-ui", "build", "static", "js", "main.js"])
  157. // The codicon font from the React build output
  158. // https://github.com/microsoft/vscode-extension-samples/blob/main/webview-codicons-sample/src/extension.ts
  159. // we installed this package in the extension so that we can access it how its intended from the extension (the font file is likely bundled in vscode), and we just import the css fileinto our react app we don't have access to it
  160. // don't forget to add font-src ${webview.cspSource};
  161. const codiconsUri = getUri(webview, this.context.extensionUri, [
  162. "node_modules",
  163. "@vscode",
  164. "codicons",
  165. "dist",
  166. "codicon.css",
  167. ])
  168. // const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "main.js"))
  169. // const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "reset.css"))
  170. // const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "vscode.css"))
  171. // // Same for stylesheet
  172. // const stylesheetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "main.css"))
  173. // Use a nonce to only allow a specific script to be run.
  174. /*
  175. content security policy of your webview to only allow scripts that have a specific nonce
  176. create a content security policy meta tag so that only loading scripts with a nonce is allowed
  177. As your extension grows you will likely want to add custom styles, fonts, and/or images to your webview. If you do, you will need to update the content security policy meta tag to explicity allow for these resources. E.g.
  178. <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; font-src ${webview.cspSource}; img-src ${webview.cspSource} https:; script-src 'nonce-${nonce}';">
  179. - 'unsafe-inline' is required for styles due to vscode-webview-toolkit's dynamic style injection
  180. - since we pass base64 images to the webview, we need to specify img-src ${webview.cspSource} data:;
  181. in meta tag we add nonce attribute: A cryptographic nonce (only used once) to allow scripts. The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial.
  182. */
  183. const nonce = getNonce()
  184. // Tip: Install the es6-string-html VS Code extension to enable code highlighting below
  185. return /*html*/ `
  186. <!DOCTYPE html>
  187. <html lang="en">
  188. <head>
  189. <meta charset="utf-8">
  190. <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
  191. <meta name="theme-color" content="#000000">
  192. <meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src ${webview.cspSource} 'unsafe-inline'; img-src ${webview.cspSource} data:; script-src 'nonce-${nonce}';">
  193. <link rel="stylesheet" type="text/css" href="${stylesUri}">
  194. <link href="${codiconsUri}" rel="stylesheet" />
  195. <title>Claude Dev</title>
  196. </head>
  197. <body>
  198. <noscript>You need to enable JavaScript to run this app.</noscript>
  199. <div id="root"></div>
  200. <script nonce="${nonce}" src="${scriptUri}"></script>
  201. </body>
  202. </html>
  203. `
  204. }
  205. /**
  206. * Sets up an event listener to listen for messages passed from the webview context and
  207. * executes code based on the message that is recieved.
  208. *
  209. * @param webview A reference to the extension webview
  210. */
  211. private setWebviewMessageListener(webview: vscode.Webview) {
  212. webview.onDidReceiveMessage(
  213. async (message: WebviewMessage) => {
  214. switch (message.type) {
  215. case "webviewDidLaunch":
  216. await this.postStateToWebview()
  217. break
  218. case "newTask":
  219. // Code that should run in response to the hello message command
  220. //vscode.window.showInformationMessage(message.text!)
  221. // Send a message to our webview.
  222. // You can send any JSON serializable data.
  223. // Could also do this in extension .ts
  224. //this.postMessageToWebview({ type: "text", text: `Extension: ${Date.now()}` })
  225. // initializing new instance of ClaudeDev will make sure that any agentically running promises in old instance don't affect our new task. this essentially creates a fresh slate for the new task
  226. await this.initClaudeDevWithTask(message.text, message.images)
  227. break
  228. case "apiConfiguration":
  229. if (message.apiConfiguration) {
  230. const { apiProvider, apiKey, openRouterApiKey, awsAccessKey, awsSecretKey, awsRegion } =
  231. message.apiConfiguration
  232. await this.updateGlobalState("apiProvider", apiProvider)
  233. await this.storeSecret("apiKey", apiKey)
  234. await this.storeSecret("openRouterApiKey", openRouterApiKey)
  235. await this.storeSecret("awsAccessKey", awsAccessKey)
  236. await this.storeSecret("awsSecretKey", awsSecretKey)
  237. await this.updateGlobalState("awsRegion", awsRegion)
  238. this.claudeDev?.updateApi(message.apiConfiguration)
  239. }
  240. await this.postStateToWebview()
  241. break
  242. case "maxRequestsPerTask":
  243. let result: number | undefined = undefined
  244. if (message.text && message.text.trim()) {
  245. const num = Number(message.text)
  246. if (!isNaN(num)) {
  247. result = num
  248. }
  249. }
  250. await this.updateGlobalState("maxRequestsPerTask", result)
  251. this.claudeDev?.updateMaxRequestsPerTask(result)
  252. await this.postStateToWebview()
  253. break
  254. case "askResponse":
  255. this.claudeDev?.handleWebviewAskResponse(message.askResponse!, message.text, message.images)
  256. break
  257. case "clearTask":
  258. // newTask will start a new task with a given task text, while clear task resets the current session and allows for a new task to be started
  259. await this.clearTask()
  260. await this.postStateToWebview()
  261. break
  262. case "didShowAnnouncement":
  263. await this.updateGlobalState("lastShownAnnouncementId", this.latestAnnouncementId)
  264. await this.postStateToWebview()
  265. break
  266. case "downloadTask":
  267. downloadTask(this.claudeDev?.apiConversationHistory ?? [])
  268. break
  269. case "selectImages":
  270. const images = await selectImages()
  271. await this.postMessageToWebview({ type: "selectedImages", images })
  272. break
  273. // Add more switch case statements here as more webview message commands
  274. // are created within the webview context (i.e. inside media/main.js)
  275. }
  276. },
  277. null,
  278. this.disposables
  279. )
  280. }
  281. async postStateToWebview() {
  282. const {
  283. apiProvider,
  284. apiKey,
  285. openRouterApiKey,
  286. awsAccessKey,
  287. awsSecretKey,
  288. awsRegion,
  289. maxRequestsPerTask,
  290. lastShownAnnouncementId,
  291. } = await this.getState()
  292. this.postMessageToWebview({
  293. type: "state",
  294. state: {
  295. version: this.context.extension?.packageJSON?.version ?? "",
  296. apiConfiguration: { apiProvider, apiKey, openRouterApiKey, awsAccessKey, awsSecretKey, awsRegion },
  297. maxRequestsPerTask,
  298. themeName: vscode.workspace.getConfiguration("workbench").get<string>("colorTheme"),
  299. claudeMessages: this.claudeDev?.claudeMessages || [],
  300. shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
  301. },
  302. })
  303. }
  304. async clearTask() {
  305. this.claudeDev?.abortTask()
  306. this.claudeDev = undefined // removes reference to it, so once promises end it will be garbage collected
  307. }
  308. // Caching mechanism to keep track of webview messages + API conversation history per provider instance
  309. /*
  310. Now that we use retainContextWhenHidden, we don't have to store a cache of claude messages in the user's state, but we could to reduce memory footprint in long conversations.
  311. - We have to be careful of what state is shared between ClaudeDevProvider instances since there could be multiple instances of the extension running at once. For example when we cached claude messages using the same key, two instances of the extension could end up using the same key and overwriting each other's messages.
  312. - Some state does need to be shared between the instances, i.e. the API key--however there doesn't seem to be a good way to notfy the other instances that the API key has changed.
  313. We need to use a unique identifier for each ClaudeDevProvider instance's message cache since we could be running several instances of the extension outside of just the sidebar i.e. in editor panels.
  314. For now since we don't need to store task history, we'll just use an identifier unique to this provider instance (since there can be several provider instances open at once).
  315. However in the future when we implement task history, we'll need to use a unique identifier for each task. As well as manage a data structure that keeps track of task history with their associated identifiers and the task message itself, to present in a 'Task History' view.
  316. Task history is a significant undertaking as it would require refactoring how we wait for ask responses--it would need to be a hidden claudeMessage, so that user's can resume tasks that ended with an ask.
  317. */
  318. // private providerInstanceIdentifier = Date.now()
  319. // getClaudeMessagesStateKey() {
  320. // return `claudeMessages-${this.providerInstanceIdentifier}`
  321. // }
  322. // getApiConversationHistoryStateKey() {
  323. // return `apiConversationHistory-${this.providerInstanceIdentifier}`
  324. // }
  325. // claude messages to present in the webview
  326. // getClaudeMessages(): ClaudeMessage[] {
  327. // // const messages = (await this.getGlobalState(this.getClaudeMessagesStateKey())) as ClaudeMessage[]
  328. // // return messages || []
  329. // return this.claudeMessages
  330. // }
  331. // setClaudeMessages(messages: ClaudeMessage[] | undefined) {
  332. // // await this.updateGlobalState(this.getClaudeMessagesStateKey(), messages)
  333. // this.claudeMessages = messages || []
  334. // }
  335. // addClaudeMessage(message: ClaudeMessage): ClaudeMessage[] {
  336. // // const messages = await this.getClaudeMessages()
  337. // // messages.push(message)
  338. // // await this.setClaudeMessages(messages)
  339. // // return messages
  340. // this.claudeMessages.push(message)
  341. // return this.claudeMessages
  342. // }
  343. // conversation history to send in API requests
  344. /*
  345. It seems that some API messages do not comply with vscode state requirements. Either the Anthropic library is manipulating these values somehow in the backend in a way thats creating cyclic references, or the API returns a function or a Symbol as part of the message content.
  346. VSCode docs about state: "The value must be JSON-stringifyable ... value — A value. MUST not contain cyclic references."
  347. For now we'll store the conversation history in memory, and if we need to store in state directly we'd need to do a manual conversion to ensure proper json stringification.
  348. */
  349. // getApiConversationHistory(): Anthropic.MessageParam[] {
  350. // // const history = (await this.getGlobalState(
  351. // // this.getApiConversationHistoryStateKey()
  352. // // )) as Anthropic.MessageParam[]
  353. // // return history || []
  354. // return this.apiConversationHistory
  355. // }
  356. // setApiConversationHistory(history: Anthropic.MessageParam[] | undefined) {
  357. // // await this.updateGlobalState(this.getApiConversationHistoryStateKey(), history)
  358. // this.apiConversationHistory = history || []
  359. // }
  360. // addMessageToApiConversationHistory(message: Anthropic.MessageParam): Anthropic.MessageParam[] {
  361. // // const history = await this.getApiConversationHistory()
  362. // // history.push(message)
  363. // // await this.setApiConversationHistory(history)
  364. // // return history
  365. // this.apiConversationHistory.push(message)
  366. // return this.apiConversationHistory
  367. // }
  368. /*
  369. Storage
  370. https://dev.to/kompotkot/how-to-use-secretstorage-in-your-vscode-extensions-2hco
  371. https://www.eliostruyf.com/devhack-code-extension-storage-options/
  372. */
  373. async getState() {
  374. const [
  375. apiProvider,
  376. apiKey,
  377. openRouterApiKey,
  378. awsAccessKey,
  379. awsSecretKey,
  380. awsRegion,
  381. maxRequestsPerTask,
  382. lastShownAnnouncementId,
  383. ] = await Promise.all([
  384. this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
  385. this.getSecret("apiKey") as Promise<string | undefined>,
  386. this.getSecret("openRouterApiKey") as Promise<string | undefined>,
  387. this.getSecret("awsAccessKey") as Promise<string | undefined>,
  388. this.getSecret("awsSecretKey") as Promise<string | undefined>,
  389. this.getGlobalState("awsRegion") as Promise<string | undefined>,
  390. this.getGlobalState("maxRequestsPerTask") as Promise<number | undefined>,
  391. this.getGlobalState("lastShownAnnouncementId") as Promise<string | undefined>,
  392. ])
  393. return {
  394. apiProvider: apiProvider || "anthropic", // for legacy users that were using Anthropic by default
  395. apiKey,
  396. openRouterApiKey,
  397. awsAccessKey,
  398. awsSecretKey,
  399. awsRegion,
  400. maxRequestsPerTask,
  401. lastShownAnnouncementId,
  402. }
  403. }
  404. // global
  405. private async updateGlobalState(key: GlobalStateKey, value: any) {
  406. await this.context.globalState.update(key, value)
  407. }
  408. private async getGlobalState(key: GlobalStateKey) {
  409. return await this.context.globalState.get(key)
  410. }
  411. // workspace
  412. private async updateWorkspaceState(key: string, value: any) {
  413. await this.context.workspaceState.update(key, value)
  414. }
  415. private async getWorkspaceState(key: string) {
  416. return await this.context.workspaceState.get(key)
  417. }
  418. // private async clearState() {
  419. // this.context.workspaceState.keys().forEach((key) => {
  420. // this.context.workspaceState.update(key, undefined)
  421. // })
  422. // this.context.globalState.keys().forEach((key) => {
  423. // this.context.globalState.update(key, undefined)
  424. // })
  425. // this.context.secrets.delete("apiKey")
  426. // }
  427. // secrets
  428. private async storeSecret(key: SecretKey, value?: string) {
  429. if (value) {
  430. await this.context.secrets.store(key, value)
  431. } else {
  432. await this.context.secrets.delete(key)
  433. }
  434. }
  435. private async getSecret(key: SecretKey) {
  436. return await this.context.secrets.get(key)
  437. }
  438. }