-
Notifications
You must be signed in to change notification settings - Fork 806
/
webviewProtocol.ts
239 lines (220 loc) · 8.07 KB
/
webviewProtocol.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { Message } from "core/util/messenger";
import fs from "node:fs";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import {
ToCoreFromWebviewProtocol,
ToWebviewFromCoreProtocol,
} from "../../../core/protocol/coreWebview";
import {
ToIdeFromWebviewProtocol,
ToWebviewFromIdeProtocol,
} from "../../../core/protocol/ideWebview";
import { IMessenger } from "../../../core/util/messenger";
import { getExtensionUri } from "./util/vscode";
export async function showTutorial() {
const tutorialPath = path.join(
getExtensionUri().fsPath,
"continue_tutorial.py",
);
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = fs.readFileSync(tutorialPath, "utf8");
tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl");
fs.writeFileSync(tutorialPath, tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath),
);
await vscode.window.showTextDocument(doc, { preview: false });
}
export type ToCoreOrIdeFromWebviewProtocol = ToCoreFromWebviewProtocol &
ToIdeFromWebviewProtocol;
type FullToWebviewFromIdeOrCoreProtocol = ToWebviewFromIdeProtocol &
ToWebviewFromCoreProtocol;
export class VsCodeWebviewProtocol
implements
IMessenger<
ToCoreOrIdeFromWebviewProtocol,
FullToWebviewFromIdeOrCoreProtocol
>
{
listeners = new Map<
keyof ToCoreOrIdeFromWebviewProtocol,
((message: Message) => any)[]
>();
send(messageType: string, data: any, messageId?: string): string {
const id = messageId ?? uuidv4();
this.webview?.postMessage({
messageType,
data,
messageId: id,
});
return id;
}
on<T extends keyof ToCoreOrIdeFromWebviewProtocol>(
messageType: T,
handler: (
message: Message<ToCoreOrIdeFromWebviewProtocol[T][0]>,
) =>
| Promise<ToCoreOrIdeFromWebviewProtocol[T][1]>
| ToCoreOrIdeFromWebviewProtocol[T][1],
): void {
if (!this.listeners.has(messageType)) {
this.listeners.set(messageType, []);
}
this.listeners.get(messageType)?.push(handler);
}
_webview?: vscode.Webview;
_webviewListener?: vscode.Disposable;
get webview(): vscode.Webview | undefined {
return this._webview;
}
set webview(webView: vscode.Webview) {
this._webview = webView;
this._webviewListener?.dispose();
this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => {
if (!msg.messageType || !msg.messageId) {
throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`);
}
const respond = (message: any) =>
this.send(msg.messageType, message, msg.messageId);
const handlers = this.listeners.get(msg.messageType) || [];
for (const handler of handlers) {
try {
const response = await handler(msg);
if (
response &&
typeof response[Symbol.asyncIterator] === "function"
) {
let next = await response.next();
while (!next.done) {
respond(next.value);
next = await response.next();
}
respond({ done: true, content: next.value?.content });
} else {
respond(response || {});
}
} catch (e: any) {
respond({ done: true, error: e });
console.error(
`Error handling webview message: ${JSON.stringify(
{ msg },
null,
2,
)}\n\n${e}`,
);
let message = e.message;
if (e.cause) {
if (e.cause.name === "ConnectTimeoutError") {
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`;
} else if (e.cause.code === "ECONNREFUSED") {
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`;
} else {
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.`;
}
}
if (message.includes("https://proxy-server")) {
message = message.split("\n").filter((l: string) => l !== "")[1];
try {
message = JSON.parse(message).message;
} catch {}
if (message.includes("exceeded")) {
message +=
" To keep using Continue, you can set up a local model or use your own API key.";
}
vscode.window
.showInformationMessage(message, "Add API Key", "Use Local Model")
.then((selection) => {
if (selection === "Add API Key") {
this.request("addApiKey", undefined);
} else if (selection === "Use Local Model") {
this.request("setupLocalModel", undefined);
}
});
} else if (message.includes("Please sign in with GitHub")) {
vscode.window
.showInformationMessage(
message,
"Sign In",
"Use API key / local model",
)
.then((selection) => {
if (selection === "Sign In") {
vscode.authentication
.getSession("github", [], {
createIfNone: true,
})
.then(() => {
this.reloadConfig();
});
} else if (selection === "Use API key / local model") {
this.request("openOnboarding", undefined);
}
});
} else {
vscode.window
.showErrorMessage(
message.split("\n\n")[0],
"Show Logs",
"Troubleshooting",
)
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand(
"workbench.action.toggleDevTools",
);
} else if (selection === "Troubleshooting") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/troubleshooting",
),
);
}
});
}
}
}
});
}
constructor(private readonly reloadConfig: () => void) {}
invoke<T extends keyof ToCoreOrIdeFromWebviewProtocol>(
messageType: T,
data: ToCoreOrIdeFromWebviewProtocol[T][0],
messageId?: string,
): ToCoreOrIdeFromWebviewProtocol[T][1] {
throw new Error("Method not implemented.");
}
onError(handler: (error: Error) => void): void {
throw new Error("Method not implemented.");
}
public request<T extends keyof FullToWebviewFromIdeOrCoreProtocol>(
messageType: T,
data: FullToWebviewFromIdeOrCoreProtocol[T][0],
): Promise<FullToWebviewFromIdeOrCoreProtocol[T][1]> {
const messageId = uuidv4();
return new Promise(async (resolve) => {
let i = 0;
while (!this.webview) {
if (i >= 10) {
resolve(undefined);
return;
} else {
await new Promise((res) => setTimeout(res, i >= 5 ? 1000 : 500));
i++;
}
}
this.send(messageType, data, messageId);
const disposable = this.webview.onDidReceiveMessage(
(msg: Message<FullToWebviewFromIdeOrCoreProtocol[T][1]>) => {
if (msg.messageId === messageId) {
resolve(msg.data);
disposable?.dispose();
}
},
);
});
}
}