continue-custom/extensions/vscode/src/webviewProtocol.ts
Nate Sesti afa582345a
Nate/control plane client (#1691)
* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* 🚑 fix constant warnings when onboarding with Ollama

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* team analytics

* apply control plane settings

* workos auth

* ide protocol get session info

* UI for auth

* profile switching

* small fixes

* updates

* refresh tokens

* updates

* fix tsc errs

* model select in toolbar to make room for profile selector

* prod client id

* link to prod URL

* internal beta option

* profiles change listener

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
2024-07-08 21:51:53 -07:00

222 lines
7.5 KiB
TypeScript

import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
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 { 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 class VsCodeWebviewProtocol
implements IMessenger<FromWebviewProtocol, ToWebviewProtocol>
{
listeners = new Map<
keyof FromWebviewProtocol,
((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 FromWebviewProtocol>(
messageType: T,
handler: (
message: Message<FromWebviewProtocol[T][0]>,
) => Promise<FromWebviewProtocol[T][1]> | FromWebviewProtocol[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 FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
messageId?: string,
): FromWebviewProtocol[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 ToWebviewProtocol>(
messageType: T,
data: ToWebviewProtocol[T][0],
): Promise<ToWebviewProtocol[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<ToWebviewProtocol[T][1]>) => {
if (msg.messageId === messageId) {
resolve(msg.data);
disposable?.dispose();
}
},
);
});
}
}