Elffuss BraidHub

kikocis/continue public

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