| 1 | import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; |
| 2 | import { Message } from "core/protocol/messenger"; |
| 3 | import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; |
| 4 | import { Telemetry } from "core/util/posthog"; |
| 5 | import { v4 as uuidv4 } from "uuid"; |
| 6 | import * as vscode from "vscode"; |
| 7 | |
| 8 | import { IMessenger } from "../../../core/protocol/messenger"; |
| 9 | |
| 10 | import { handleLLMError } from "./util/errorHandling"; |
| 11 | |
| 12 | export class VsCodeWebviewProtocol |
| 13 | implements IMessenger<FromWebviewProtocol, ToWebviewProtocol> |
| 14 | { |
| 15 | listeners = new Map< |
| 16 | keyof FromWebviewProtocol, |
| 17 | ((message: Message) => any)[] |
| 18 | >(); |
| 19 | |
| 20 | send(messageType: string, data: any, messageId?: string): string { |
| 21 | const id = messageId ?? uuidv4(); |
| 22 | this.webview?.postMessage({ |
| 23 | messageType, |
| 24 | data, |
| 25 | messageId: id, |
| 26 | }); |
| 27 | return id; |
| 28 | } |
| 29 | |
| 30 | on<T extends keyof FromWebviewProtocol>( |
| 31 | messageType: T, |
| 32 | handler: ( |
| 33 | message: Message<FromWebviewProtocol[T][0]>, |
| 34 | ) => Promise<FromWebviewProtocol[T][1]> | FromWebviewProtocol[T][1], |
| 35 | ): void { |
| 36 | if (!this.listeners.has(messageType)) { |
| 37 | this.listeners.set(messageType, []); |
| 38 | } |
| 39 | this.listeners.get(messageType)?.push(handler); |
| 40 | } |
| 41 | |
| 42 | _webview?: vscode.Webview; |
| 43 | _webviewListener?: vscode.Disposable; |
| 44 | |
| 45 | get webview(): vscode.Webview | undefined { |
| 46 | return this._webview; |
| 47 | } |
| 48 | |
| 49 | set webview(webView: vscode.Webview) { |
| 50 | this._webview = webView; |
| 51 | this._webviewListener?.dispose(); |
| 52 | |
| 53 | const handleMessage = async (msg: Message): Promise<void> => { |
| 54 | if (!("messageType" in msg) || !("messageId" in msg)) { |
| 55 | throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`); |
| 56 | } |
| 57 | |
| 58 | const respond = (message: any) => |
| 59 | this.send(msg.messageType, message, msg.messageId); |
| 60 | |
| 61 | const handlers = |
| 62 | this.listeners.get(msg.messageType as keyof FromWebviewProtocol) || []; |
| 63 | for (const handler of handlers) { |
| 64 | try { |
| 65 | const response = await handler(msg); |
| 66 | // For generator types e.g. llm/streamChat |
| 67 | if ( |
| 68 | response && |
| 69 | typeof response[Symbol.asyncIterator] === "function" |
| 70 | ) { |
| 71 | let next = await response.next(); |
| 72 | while (!next.done) { |
| 73 | respond({ |
| 74 | done: false, |
| 75 | content: next.value, |
| 76 | status: "success", |
| 77 | }); |
| 78 | next = await response.next(); |
| 79 | } |
| 80 | respond({ |
| 81 | done: true, |
| 82 | content: next.value, |
| 83 | status: "success", |
| 84 | }); |
| 85 | } else { |
| 86 | respond({ done: true, content: response, status: "success" }); |
| 87 | } |
| 88 | } catch (e: any) { |
| 89 | if (await handleLLMError(e)) { |
| 90 | // Respond without an error, so the UI doesn't show the error component |
| 91 | respond({ done: true, status: "error" }); |
| 92 | } |
| 93 | let message = e.message; |
| 94 | respond({ done: true, error: message, status: "error" }); |
| 95 | |
| 96 | const stringified = JSON.stringify({ msg }, null, 2); |
| 97 | console.error( |
| 98 | `Error handling webview message: ${stringified}\n\n${e}`, |
| 99 | ); |
| 100 | |
| 101 | if ( |
| 102 | stringified.includes("llm/streamChat") || |
| 103 | stringified.includes("chatDescriber/describe") |
| 104 | ) { |
| 105 | return; |
| 106 | } |
| 107 | |
| 108 | if (e.cause) { |
| 109 | if (e.cause.name === "ConnectTimeoutError") { |
| 110 | message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in your config by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://docs.continue.dev/reference/config`; |
| 111 | } else if (e.cause.code === "ECONNREFUSED") { |
| 112 | message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://docs.continue.dev/reference/Model%20Providers/openai#openai-compatible-servers--apis`; |
| 113 | } else { |
| 114 | message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`; |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | if (message.includes("https://proxy-server")) { |
| 119 | message = message.split("\n").filter((l: string) => l !== "")[1]; |
| 120 | try { |
| 121 | message = JSON.parse(message).message; |
| 122 | } catch {} |
| 123 | if (message.includes("exceeded")) { |
| 124 | message += |
| 125 | " To keep using Continue, you can set up a local model or use your own API key."; |
| 126 | } |
| 127 | |
| 128 | vscode.window |
| 129 | .showInformationMessage(message, "Add API Key", "Use Local Model") |
| 130 | .then((selection) => { |
| 131 | if (selection === "Add API Key") { |
| 132 | this.request("setupApiKey", undefined); |
| 133 | } else if (selection === "Use Local Model") { |
| 134 | this.request("setupLocalConfig", undefined); |
| 135 | } |
| 136 | }); |
| 137 | } else { |
| 138 | Telemetry.capture( |
| 139 | "webview_protocol_error", |
| 140 | { |
| 141 | messageType: msg.messageType, |
| 142 | errorMsg: message.split("\n\n")[0], |
| 143 | stack: extractMinimalStackTraceInfo(e.stack), |
| 144 | }, |
| 145 | false, |
| 146 | ); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | }; |
| 151 | |
| 152 | this._webviewListener = this._webview.onDidReceiveMessage(handleMessage); |
| 153 | } |
| 154 | |
| 155 | constructor() {} |
| 156 | |
| 157 | invoke<T extends keyof FromWebviewProtocol>( |
| 158 | messageType: T, |
| 159 | data: FromWebviewProtocol[T][0], |
| 160 | messageId?: string, |
| 161 | ): FromWebviewProtocol[T][1] { |
| 162 | throw new Error("Method not implemented."); |
| 163 | } |
| 164 | |
| 165 | onError(handler: (message: Message, error: Error) => void): void { |
| 166 | throw new Error("Method not implemented."); |
| 167 | } |
| 168 | |
| 169 | public request<T extends keyof ToWebviewProtocol>( |
| 170 | messageType: T, |
| 171 | data: ToWebviewProtocol[T][0], |
| 172 | retry: boolean = true, |
| 173 | ): Promise<ToWebviewProtocol[T][1]> { |
| 174 | const messageId = uuidv4(); |
| 175 | return new Promise(async (resolve) => { |
| 176 | if (retry) { |
| 177 | let i = 0; |
| 178 | while (!this.webview) { |
| 179 | if (i >= 10) { |
| 180 | resolve(undefined); |
| 181 | return; |
| 182 | } else { |
| 183 | await new Promise((res) => setTimeout(res, i >= 5 ? 1000 : 500)); |
| 184 | i++; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | this.send(messageType, data, messageId); |
| 190 | |
| 191 | if (this.webview) { |
| 192 | const disposable = this.webview.onDidReceiveMessage( |
| 193 | (msg: Message<ToWebviewProtocol[T][1]>) => { |
| 194 | if (msg.messageId === messageId) { |
| 195 | resolve(msg.data); |
| 196 | disposable?.dispose(); |
| 197 | } |
| 198 | }, |
| 199 | ); |
| 200 | } else if (!retry) { |
| 201 | resolve(undefined); |
| 202 | } |
| 203 | }); |
| 204 | } |
| 205 | } |