SidebarProvider.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { Uri, Webview } from "vscode"
  2. //import * as weather from "weather-js"
  3. import * as vscode from "vscode"
  4. import { ClaudeMessage, ExtensionMessage } from "../shared/ExtensionMessage"
  5. import { WebviewMessage } from "../shared/WebviewMessage"
  6. import { ClaudeDev } from "../ClaudeDev"
  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 ExtensionSecretKey = "apiKey"
  12. type ExtensionGlobalStateKey = "didOpenOnce" | "maxRequestsPerTask"
  13. type ExtensionWorkspaceStateKey = "claudeMessages"
  14. export class SidebarProvider implements vscode.WebviewViewProvider {
  15. public static readonly viewType = "claude-dev.SidebarProvider"
  16. private view?: vscode.WebviewView
  17. private claudeDev?: ClaudeDev
  18. constructor(private readonly context: vscode.ExtensionContext) {}
  19. resolveWebviewView(
  20. webviewView: vscode.WebviewView,
  21. context: vscode.WebviewViewResolveContext<unknown>,
  22. token: vscode.CancellationToken
  23. ): void | Thenable<void> {
  24. this.view = webviewView
  25. webviewView.webview.options = {
  26. // Allow scripts in the webview
  27. enableScripts: true,
  28. localResourceRoots: [this.context.extensionUri],
  29. }
  30. webviewView.webview.html = this.getHtmlContent(webviewView.webview)
  31. // Sets up an event listener to listen for messages passed from the webview view context
  32. // and executes code based on the message that is recieved
  33. this.setWebviewMessageListener(webviewView.webview)
  34. // Listen for when the panel becomes visible
  35. // https://github.com/microsoft/vscode-discussions/discussions/840
  36. webviewView.onDidChangeVisibility((e: any) => {
  37. if (e.visible) {
  38. // Your view is visible
  39. this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
  40. } else {
  41. // Your view is hidden
  42. }
  43. })
  44. // if the extension is starting a new session, clear previous task state
  45. this.clearTask()
  46. }
  47. async tryToInitClaudeDevWithTask(task: string) {
  48. const [apiKey, maxRequestsPerTask] = await Promise.all([
  49. this.getSecret("apiKey") as Promise<string | undefined>,
  50. this.getGlobalState("maxRequestsPerTask") as Promise<number | undefined>,
  51. ])
  52. if (this.view && apiKey) {
  53. this.claudeDev = new ClaudeDev(this, task, apiKey, maxRequestsPerTask)
  54. }
  55. }
  56. // Send any JSON serializable data to the react app
  57. async postMessageToWebview(message: ExtensionMessage) {
  58. await this.view?.webview.postMessage(message)
  59. }
  60. /**
  61. * Defines and returns the HTML that should be rendered within the webview panel.
  62. *
  63. * @remarks This is also the place where references to the React webview build files
  64. * are created and inserted into the webview HTML.
  65. *
  66. * @param webview A reference to the extension webview
  67. * @param extensionUri The URI of the directory containing the extension
  68. * @returns A template string literal containing the HTML that should be
  69. * rendered within the webview panel
  70. */
  71. private getHtmlContent(webview: vscode.Webview): string {
  72. // Get the local path to main script run in the webview,
  73. // then convert it to a uri we can use in the webview.
  74. // The CSS file from the React build output
  75. const stylesUri = getUri(webview, this.context.extensionUri, [
  76. "webview-ui",
  77. "build",
  78. "static",
  79. "css",
  80. "main.css",
  81. ])
  82. // The JS file from the React build output
  83. const scriptUri = getUri(webview, this.context.extensionUri, ["webview-ui", "build", "static", "js", "main.js"])
  84. // The codicon font from the React build output
  85. // https://github.com/microsoft/vscode-extension-samples/blob/main/webview-codicons-sample/src/extension.ts
  86. // 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
  87. // don't forget to add font-src ${webview.cspSource};
  88. const codiconsUri = getUri(webview, this.context.extensionUri, [
  89. "node_modules",
  90. "@vscode",
  91. "codicons",
  92. "dist",
  93. "codicon.css",
  94. ])
  95. // const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "main.js"))
  96. // const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "reset.css"))
  97. // const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "vscode.css"))
  98. // // Same for stylesheet
  99. // const stylesheetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "main.css"))
  100. // Use a nonce to only allow a specific script to be run.
  101. /*
  102. content security policy of your webview to only allow scripts that have a specific nonce
  103. create a content security policy meta tag so that only loading scripts with a nonce is allowed
  104. 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.
  105. <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}';">
  106. 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.
  107. */
  108. const nonce = getNonce()
  109. // Tip: Install the es6-string-html VS Code extension to enable code highlighting below
  110. return /*html*/ `
  111. <!DOCTYPE html>
  112. <html lang="en">
  113. <head>
  114. <meta charset="utf-8">
  115. <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
  116. <meta name="theme-color" content="#000000">
  117. <meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
  118. <link rel="stylesheet" type="text/css" href="${stylesUri}">
  119. <link href="${codiconsUri}" rel="stylesheet" />
  120. <title>Claude Dev</title>
  121. </head>
  122. <body>
  123. <noscript>You need to enable JavaScript to run this app.</noscript>
  124. <div id="root"></div>
  125. <script nonce="${nonce}" src="${scriptUri}"></script>
  126. </body>
  127. </html>
  128. `
  129. }
  130. /**
  131. * Sets up an event listener to listen for messages passed from the webview context and
  132. * executes code based on the message that is recieved.
  133. *
  134. * @param webview A reference to the extension webview
  135. * @param context A reference to the extension context
  136. */
  137. private setWebviewMessageListener(webview: vscode.Webview) {
  138. webview.onDidReceiveMessage(async (message: WebviewMessage) => {
  139. switch (message.type) {
  140. case "webviewDidLaunch":
  141. await this.updateGlobalState("didOpenOnce", true)
  142. await this.postStateToWebview()
  143. break
  144. case "newTask":
  145. // Code that should run in response to the hello message command
  146. //vscode.window.showInformationMessage(message.text!)
  147. // Send a message to our webview.
  148. // You can send any JSON serializable data.
  149. // Could also do this in extension .ts
  150. //this.postMessageToWebview({ type: "text", text: `Extension: ${Date.now()}` })
  151. // 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
  152. await this.tryToInitClaudeDevWithTask(message.text!)
  153. break
  154. case "apiKey":
  155. await this.storeSecret("apiKey", message.text!)
  156. this.claudeDev?.updateApiKey(message.text!)
  157. await this.postStateToWebview()
  158. break
  159. case "maxRequestsPerTask":
  160. let result: number | undefined = undefined
  161. if (message.text && message.text.trim()) {
  162. const num = Number(message.text)
  163. if (!isNaN(num)) {
  164. result = num
  165. }
  166. }
  167. await this.updateGlobalState("maxRequestsPerTask", result)
  168. this.claudeDev?.updateMaxRequestsPerTask(result)
  169. await this.postStateToWebview()
  170. break
  171. case "askResponse":
  172. this.claudeDev?.handleWebviewAskResponse(message.askResponse!, message.text)
  173. break
  174. case "clearTask":
  175. await this.clearTask()
  176. await this.postStateToWebview()
  177. break
  178. // Add more switch case statements here as more webview message commands
  179. // are created within the webview context (i.e. inside media/main.js)
  180. }
  181. })
  182. }
  183. async postStateToWebview() {
  184. const [didOpenOnce, apiKey, maxRequestsPerTask, claudeMessages] = await Promise.all([
  185. this.getGlobalState("didOpenOnce") as Promise<boolean | undefined>,
  186. this.getSecret("apiKey") as Promise<string | undefined>,
  187. this.getGlobalState("maxRequestsPerTask") as Promise<number | undefined>,
  188. this.getClaudeMessages(),
  189. ])
  190. this.postMessageToWebview({
  191. type: "state",
  192. state: { didOpenOnce: !!didOpenOnce, apiKey, maxRequestsPerTask, claudeMessages },
  193. })
  194. }
  195. async clearTask() {
  196. this.claudeDev = undefined
  197. await this.setClaudeMessages([])
  198. }
  199. // client messages
  200. async getClaudeMessages(): Promise<ClaudeMessage[]> {
  201. const messages = (await this.getWorkspaceState("claudeMessages")) as ClaudeMessage[]
  202. return messages || []
  203. }
  204. async setClaudeMessages(messages: ClaudeMessage[] | undefined) {
  205. await this.updateWorkspaceState("claudeMessages", messages)
  206. }
  207. async addClaudeMessage(message: ClaudeMessage): Promise<ClaudeMessage[]> {
  208. const messages = await this.getClaudeMessages()
  209. messages.push(message)
  210. await this.setClaudeMessages(messages)
  211. return messages
  212. }
  213. // api conversation history
  214. // async getApiConversationHistory(): Promise<ClaudeMessage[]> {
  215. // const messages = (await this.getWorkspaceState("apiConversationHistory")) as ClaudeMessage[]
  216. // return messages || []
  217. // }
  218. // async setApiConversationHistory(messages: ClaudeMessage[] | undefined) {
  219. // await this.updateWorkspaceState("apiConversationHistory", messages)
  220. // }
  221. // async addMessageToApiConversationHistory(message: ClaudeMessage): Promise<ClaudeMessage[]> {
  222. // const messages = await this.getClaudeMessages()
  223. // messages.push(message)
  224. // await this.setClaudeMessages(messages)
  225. // return messages
  226. // }
  227. /*
  228. Storage
  229. https://dev.to/kompotkot/how-to-use-secretstorage-in-your-vscode-extensions-2hco
  230. https://www.eliostruyf.com/devhack-code-extension-storage-options/
  231. */
  232. // global
  233. private async updateGlobalState(key: ExtensionGlobalStateKey, value: any) {
  234. await this.context.globalState.update(key, value)
  235. }
  236. private async getGlobalState(key: ExtensionGlobalStateKey) {
  237. return await this.context.globalState.get(key)
  238. }
  239. // workspace
  240. private async updateWorkspaceState(key: ExtensionWorkspaceStateKey, value: any) {
  241. await this.context.workspaceState.update(key, value)
  242. }
  243. private async getWorkspaceState(key: ExtensionWorkspaceStateKey) {
  244. return await this.context.workspaceState.get(key)
  245. }
  246. // secrets
  247. private async storeSecret(key: ExtensionSecretKey, value: any) {
  248. await this.context.secrets.store(key, value)
  249. }
  250. private async getSecret(key: ExtensionSecretKey) {
  251. return await this.context.secrets.get(key)
  252. }
  253. }
  254. /**
  255. * A helper function that returns a unique alphanumeric identifier called a nonce.
  256. *
  257. * @remarks This function is primarily used to help enforce content security
  258. * policies for resources/scripts being executed in a webview context.
  259. *
  260. * @returns A nonce
  261. */
  262. export function getNonce() {
  263. let text = ""
  264. const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  265. for (let i = 0; i < 32; i++) {
  266. text += possible.charAt(Math.floor(Math.random() * possible.length))
  267. }
  268. return text
  269. }
  270. /**
  271. * A helper function which will get the webview URI of a given file or resource.
  272. *
  273. * @remarks This URI can be used within a webview's HTML as a link to the
  274. * given file/resource.
  275. *
  276. * @param webview A reference to the extension webview
  277. * @param extensionUri The URI of the directory containing the extension
  278. * @param pathList An array of strings representing the path to a file/resource
  279. * @returns A URI pointing to the file/resource
  280. */
  281. export function getUri(webview: Webview, extensionUri: Uri, pathList: string[]) {
  282. return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList))
  283. }