From 49cb06df70016af4b6081122fa2737560abaf7ce Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Fri, 19 Apr 2024 17:55:16 -0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Improved=20onboarding=20experience?= =?UTF-8?q?=20(#1155)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🚸 onboarding improvements * 🧑‍💻 keyboard shortcuts to toggle autocomplete and open config.json * ⚡️ improve detection of terminal code blocks * 🚧 onboarding improvements * 🚧 more onboarding improvements * 💄 last session button * 🚸 show more fallback options in dropdown * 💄 add sectioning to models page * 💄 clean up delete model button * 💄 make tooltip look nicer * 🚸 download Ollama button * 💄 local LLM onboarding * 🐛 select correct terminal on "runCommand" message * 💄 polish onboarding --- binary/src/core.ts | 2 +- core/autocomplete/completionProvider.ts | 14 +- core/config/default.ts | 15 +- core/config/handler.ts | 67 ++-- core/config/onboarding.ts | 5 + core/protocol.ts | 8 +- core/util/history.ts | 12 +- .../src/main/resources/continue_tutorial.py | 2 +- extensions/vscode/.continuerc.json | 4 + extensions/vscode/continue_tutorial.py | 8 +- extensions/vscode/media/welcome.md | 16 +- extensions/vscode/package.json | 25 +- .../src/autocomplete/completionProvider.ts | 26 +- extensions/vscode/src/commands.ts | 7 +- .../src/diff/verticalPerLine/manager.ts | 1 + extensions/vscode/src/ideProtocol.ts | 6 +- extensions/vscode/src/lang-server/codeLens.ts | 69 ++-- extensions/vscode/src/util/cleanSlate.ts | 16 + .../vscode/src/util/loadAutocompleteModel.ts | 3 + extensions/vscode/src/webviewProtocol.ts | 17 +- gui/src/App.tsx | 5 + gui/src/components/HeaderButtonWithText.tsx | 9 +- gui/src/components/Layout.tsx | 105 +++---- gui/src/components/dialogs/AddDocsDialog.tsx | 7 + gui/src/components/{index.ts => index.tsx} | 57 +++- gui/src/components/mainInput/MentionList.tsx | 4 +- gui/src/components/mainInput/getSuggestion.ts | 14 +- .../components/markdown/CodeBlockToolbar.tsx | 9 +- .../components/modelSelection/ModelSelect.tsx | 5 +- gui/src/hooks/useHistory.tsx | 38 ++- gui/src/hooks/useSubmenuContextProviders.tsx | 40 ++- gui/src/pages/gui.tsx | 16 +- gui/src/pages/history.tsx | 18 +- gui/src/pages/localOnboarding.tsx | 297 ++++++++++++++++++ gui/src/pages/models.tsx | 76 +++-- gui/src/pages/onboarding/components.ts | 5 +- gui/src/pages/onboarding/onboarding.tsx | 40 ++- gui/src/redux/slices/stateSlice.ts | 4 +- gui/src/util/localStorage.ts | 1 + gui/src/util/modelData.ts | 9 +- 40 files changed, 820 insertions(+), 262 deletions(-) create mode 100644 extensions/vscode/src/util/cleanSlate.ts rename gui/src/components/{index.ts => index.tsx} (89%) create mode 100644 gui/src/pages/localOnboarding.tsx diff --git a/binary/src/core.ts b/binary/src/core.ts index 8cded9f25..63caec347 100644 --- a/binary/src/core.ts +++ b/binary/src/core.ts @@ -90,7 +90,7 @@ export class Core { // History on("history/list", (msg) => { - return historyManager.list(); + return historyManager.list(msg.data); }); on("history/delete", (msg) => { historyManager.delete(msg.data.id); diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 9750fa46a..f765b115a 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -81,6 +81,8 @@ function formatExternalSnippet( return lines.join("\n"); } +let shownGptClaudeWarning = false; + export async function getTabCompletion( token: AbortSignal, options: TabAutocompleteOptions, @@ -117,6 +119,7 @@ export async function getTabCompletion( } // Model + if (!llm) return; if (llm instanceof OpenAI) { llm.useLegacyCompletionsEndpoint = true; } else if ( @@ -127,7 +130,16 @@ export async function getTabCompletion( "The only free trial model supported for tab-autocomplete is starcoder-7b.", ); } - if (!llm) return; + + if ( + !shownGptClaudeWarning && + (llm.model.includes("gpt") || llm.model.includes("claude")) + ) { + shownGptClaudeWarning = true; + throw new Error( + `Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://continue.dev/docs/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, + ); + } // Prompt const fullPrefix = getRangeInString(fileContents, { diff --git a/core/config/default.ts b/core/config/default.ts index 131479800..adae7fe60 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -55,13 +55,13 @@ export const defaultConfig: SerializedContinueConfig = { }, ], contextProviders: [ + { name: "code", params: {} }, + { name: "docs", params: {} }, { name: "diff", params: {} }, - { - name: "open", - params: {}, - }, + { name: "open", params: {} }, { name: "terminal", params: {} }, { name: "problems", params: {} }, + { name: "folder", params: {} }, { name: "codebase", params: {} }, ], tabAutocompleteModel: { @@ -121,12 +121,7 @@ export const defaultConfigJetBrains: SerializedContinueConfig = { description: "Write unit tests for highlighted code", }, ], - contextProviders: [ - { - name: "open", - params: {}, - }, - ], + contextProviders: [{ name: "open", params: {} }], tabAutocompleteModel: { title: "Starcoder2 3b", provider: "ollama", diff --git a/core/config/handler.ts b/core/config/handler.ts index 0b93cbe78..c64eea703 100644 --- a/core/config/handler.ts +++ b/core/config/handler.ts @@ -1,12 +1,12 @@ import { ContinueConfig, ContinueRcJson, IDE, ILLM } from ".."; import { IdeSettings } from "../protocol"; +import { fetchwithRequestOptions } from "../util/fetchWithOptions"; import { Telemetry } from "../util/posthog"; import { BrowserSerializedContinueConfig, finalToBrowserConfig, loadFullConfigNode, } from "./load"; -import { fetchwithRequestOptions } from "../util/fetchWithOptions"; export class ConfigHandler { private savedConfig: ContinueConfig | undefined; @@ -16,7 +16,7 @@ export class ConfigHandler { private readonly ide: IDE, private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => void, - private readonly onConfigUpdate: () => void + private readonly onConfigUpdate: () => void, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; @@ -76,7 +76,7 @@ export class ConfigHandler { this.ide.readFile, workspaceConfigs, remoteConfigServerUrl, - ideInfo.ideType + ideInfo.ideType, ); this.savedConfig.allowAnonymousTelemetry = this.savedConfig.allowAnonymousTelemetry && @@ -86,7 +86,7 @@ export class ConfigHandler { await Telemetry.setup( this.savedConfig.allowAnonymousTelemetry ?? true, await this.ide.getUniqueId(), - ideInfo.extensionVersion + ideInfo.extensionVersion, ); return this.savedConfig; @@ -94,32 +94,43 @@ export class ConfigHandler { setupLlm(llm: ILLM): ILLM { llm._fetch = async (input, init) => { - const resp = await fetchwithRequestOptions( - new URL(input), - { ...init }, - llm.requestOptions - ); - - if (!resp.ok) { - let text = await resp.text(); - if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); - text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; - } else if (text.includes("/api/chat")) { - text = - "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; - } else { - text = - "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; - } - } - throw new Error( - `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}` + try { + const resp = await fetchwithRequestOptions( + new URL(input), + { ...init }, + llm.requestOptions, ); - } + if (!resp.ok) { + let text = await resp.text(); + if (resp.status === 404 && !resp.url.includes("/v1")) { + if (text.includes("try pulling it first")) { + const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + } else if (text.includes("/api/chat")) { + text = + "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; + } else { + text = + "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; + } + } + throw new Error( + `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`, + ); + } - return resp; + return resp; + } catch (e: any) { + if ( + e.code === "ECONNREFUSED" && + e.message.includes("http://127.0.0.1:11434") + ) { + throw new Error( + "Failed to connect to local Ollama instance. To start Ollama, first download it at https://ollama.ai.", + ); + } + throw new Error(`${e}`); + } }; llm.writeLog = async (log: string) => { diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index 1063d5791..ee2b10971 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -71,6 +71,11 @@ export function setupLocalMode( return { ...config, models: [ + { + title: "Llama 3", + provider: "ollama", + model: "llama3", + }, { title: "Ollama", provider: "ollama", diff --git a/core/protocol.ts b/core/protocol.ts index 43d5c729c..3e37b00ee 100644 --- a/core/protocol.ts +++ b/core/protocol.ts @@ -19,6 +19,11 @@ export type ProtocolGeneratorType = AsyncGenerator<{ content: T; }>; +export interface ListHistoryOptions { + offset?: number; + limit?: number; +} + export type Protocol = { // New "update/modelChange": [string, void]; @@ -27,7 +32,7 @@ export type Protocol = { abort: [undefined, void]; // History - "history/list": [undefined, SessionInfo[]]; + "history/list": [ListHistoryOptions, SessionInfo[]]; "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, PersistedSessionInfo]; "history/save": [PersistedSessionInfo, void]; @@ -82,6 +87,7 @@ export type Protocol = { }, string, ]; + "llm/listModels": [{ title: string }, string[] | undefined]; "llm/streamComplete": [ { prompt: string; diff --git a/core/util/history.ts b/core/util/history.ts index a7b4167e4..21313d51e 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -1,18 +1,26 @@ import * as fs from "fs"; import { PersistedSessionInfo, SessionInfo } from ".."; +import { ListHistoryOptions } from "../protocol"; import { getSessionFilePath, getSessionsListPath } from "./paths"; class HistoryManager { - list(): SessionInfo[] { + list(options: ListHistoryOptions): SessionInfo[] { const filepath = getSessionsListPath(); if (!fs.existsSync(filepath)) { return []; } const content = fs.readFileSync(filepath, "utf8"); - const sessions = JSON.parse(content).filter((session: any) => { + let sessions = JSON.parse(content).filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; }); + + // Apply limit and offset + if (options.limit) { + const offset = options.offset || 0; + sessions = sessions.slice(offset, offset + options.limit); + } + return sessions; } diff --git a/extensions/intellij/src/main/resources/continue_tutorial.py b/extensions/intellij/src/main/resources/continue_tutorial.py index 9a7194ad0..1c79f2c88 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.py +++ b/extensions/intellij/src/main/resources/continue_tutorial.py @@ -3,7 +3,7 @@ Welcome to Continue! _________ _____ _____ __ ____/______ _______ __ /____(_)_______ ____ _______ -_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ +_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ diff --git a/extensions/vscode/.continuerc.json b/extensions/vscode/.continuerc.json index 7fbb047a6..9f9190f70 100644 --- a/extensions/vscode/.continuerc.json +++ b/extensions/vscode/.continuerc.json @@ -5,5 +5,9 @@ "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", "description": "This is an example custom command. Use /config to edit it and create more" } + ], + "disableIndexing": true, + "models": [ + ] } diff --git a/extensions/vscode/continue_tutorial.py b/extensions/vscode/continue_tutorial.py index e332e22af..b19980706 100644 --- a/extensions/vscode/continue_tutorial.py +++ b/extensions/vscode/continue_tutorial.py @@ -1,15 +1,13 @@ """ _________ _____ _____ __ ____/______ _______ __ /____(_)_______ ____ _______ -_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ +_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ Welcome to Continue! This is a 2 minute tutorial. -You can either -- follow the instructions on your own, or -- follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section" +You can click the gray buttons, starting with "Highlight the function" to follow along. """ # region —————————————————————————— Part 1: Ask a question about code [Cmd+L] —————————————————————————— @@ -78,4 +76,4 @@ print_sum(["a", "b", "c"]) # endregion -# Ready to learn more? Check out the Continue documentation: https://continue.dev/docs \ No newline at end of file +# Ready to learn more? Check out the Continue documentation: https://continue.dev/docs diff --git a/extensions/vscode/media/welcome.md b/extensions/vscode/media/welcome.md index dac249e0a..1887f4641 100644 --- a/extensions/vscode/media/welcome.md +++ b/extensions/vscode/media/welcome.md @@ -2,13 +2,15 @@ ## ❗️ Before you get started -Continue is currently in the left sidebar, but we recommend moving it to the right. This way it won't cover your file explorer. You can move it back at any time. +Continue is currently in the left sidebar, but we recommend moving it to the right. This way it won't cover your file explorer. + +You can move it back at any time. If you close the sidebar, it can be re-opened with Cmd/Ctrl + L. ![Move Continue to right sidebar](./sidebar.gif) ## 🔑 Most important shortcuts -> If you've been using Continue, these have changed. You can always customize them in VS Code settings. +> If you'd prefer different keys, these shortcuts can be customized in VS Code settings. Cmd/Ctrl + L = Select code @@ -17,13 +19,3 @@ Continue is currently in the left sidebar, but we recommend moving it to the rig Cmd/Ctrl + I = Quick edit Cmd/Ctrl + Shift + R = Automatically debug terminal - -## ⚡️ Setting up tab autocomplete - -1. Download [Ollama](https://ollama.ai) -2. Download starcoder2:3b by running `ollama run starcoder2:3b` in the terminal -3. That's it! You can disable autocomplete at any time by clicking the `Continue` button in the status bar (bottom right of the VS Code window) - -> Learn how to customize your autocomplete experience in [our walkthrough](https://continue.dev/docs/walkthroughs/tab-autocomplete) - -![Autocomplete](./autocomplete.gif) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index b3e7c703c..799313459 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -17,7 +17,7 @@ "homepage": "https://continue.dev", "qna": "https://github.com/continuedev/continue/issues/new/choose", "license": "Apache-2.0", - "displayName": "Continue - Claude, CodeLlama, GPT-4, and more", + "displayName": "Continue - Llama 3, GPT-4, and more", "pricing": "Free", "description": "Open-source autopilot for software development - bring the power of ChatGPT to your IDE", "publisher": "Continue", @@ -41,6 +41,7 @@ "github", "copilot", "llama", + "3", "codegpt", "ai" ], @@ -149,6 +150,18 @@ "icon": "$(fullscreen)", "group": "Continue" }, + { + "command": "continue.openConfigJson", + "category": "Continue", + "title": "Open config.json", + "group": "Continue" + }, + { + "command": "continue.toggleTabAutocompleteEnabled", + "category": "Continue", + "title": "Toggle Autocomplete Enabled", + "group": "Continue" + }, { "command": "continue.shareSession", "category": "Continue", @@ -263,6 +276,16 @@ "mac": "cmd+k cmd+m", "key": "ctrl+k ctrl+m", "when": "!terminalFocus" + }, + { + "command": "continue.toggleTabAutocompleteEnabled", + "mac": "cmd+k cmd+a", + "key": "ctrl+k ctrl+a" + }, + { + "command": "continue.openConfigJson", + "mac": "cmd+k cmd+c", + "key": "ctrl+k ctrl+c" } ], "submenus": [ diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 5a7830d3a..a89664e3e 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -16,13 +16,19 @@ export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { private onError(e: any) { - vscode.window.showErrorMessage(e.message, "Documentation").then((val) => { + const options = ["Documentation"]; + if (e.message.includes("https://ollama.ai")) { + options.push("Download Ollama"); + } + vscode.window.showErrorMessage(e.message, ...options).then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) + "https://continue.dev/docs/walkthroughs/tab-autocomplete", + ), ); + } else if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai")); } }); } @@ -32,14 +38,14 @@ export class ContinueCompletionProvider constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, - private readonly tabAutocompleteModel: TabAutocompleteModel + private readonly tabAutocompleteModel: TabAutocompleteModel, ) { this.completionProvider = new CompletionProvider( this.configHandler, this.ide, this.tabAutocompleteModel.get.bind(this.tabAutocompleteModel), this.onError.bind(this), - getDefinitionsFromLsp + getDefinitionsFromLsp, ); } @@ -47,7 +53,7 @@ export class ContinueCompletionProvider document: vscode.TextDocument, position: vscode.Position, context: vscode.InlineCompletionContext, - token: vscode.CancellationToken + token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { const enableTabAutocomplete = @@ -75,14 +81,14 @@ export class ContinueCompletionProvider pos: { line: position.line, character: position.character }, recentlyEditedFiles: [], recentlyEditedRanges: [], - clipboardText: clipboardText + clipboardText: clipboardText, }; setupStatusBar(true, true); const outcome = await this.completionProvider.provideInlineCompletionItems( input, - signal + signal, ); if (!outcome || !outcome.completion) { @@ -107,13 +113,13 @@ export class ContinueCompletionProvider outcome.completion, new vscode.Range( position, - position.translate(0, outcome.completion.length) + position.translate(0, outcome.completion.length), ), { title: "Log Autocomplete Outcome", command: "continue.logAutocompleteOutcome", arguments: [outcome, logRejectionTimeout], - } + }, ), ]; } finally { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 8bc6dd3f4..fa85a3ea2 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -7,6 +7,7 @@ import { IDE } from "core"; import { AutocompleteOutcome } from "core/autocomplete/completionProvider"; import { ConfigHandler } from "core/config/handler"; import { logDevData } from "core/util/devdata"; +import { getConfigJsonPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import { ContinueGUIWebviewViewProvider } from "./debugPanel"; import { DiffManager } from "./diff/horizontal"; @@ -197,7 +198,7 @@ const commandsMap: ( "continue.toggleAuxiliaryBar": () => { vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); }, - "continue.quickEdit": async () => { + "continue.quickEdit": async (prompt?: string) => { const selectionEmpty = vscode.window.activeTextEditor?.selection.isEmpty; const editor = vscode.window.activeTextEditor; @@ -234,6 +235,7 @@ const commandsMap: ( : `Describe how to edit the highlighted code${addContextMsg}`, title: `${getPlatform() === "mac" ? "Cmd" : "Ctrl"}+I`, prompt: `[${defaultModelTitle}]`, + value: prompt, }; if (previousInput) { textInputOptions.value = previousInput + ", "; @@ -476,6 +478,9 @@ const commandsMap: ( extensionContext.subscriptions, ); }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, "continue.selectFilesAsContext": ( firstUri: vscode.Uri, uris: vscode.Uri[], diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index 3ce6f79c0..45bb82c10 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -220,6 +220,7 @@ export class VerticalPerLineDiffManager { ); } catch (e) { console.error("Error streaming diff:", e); + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); } finally { vscode.commands.executeCommand( "setContext", diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 85b8777e6..74cfe21c7 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -231,8 +231,10 @@ class VsCodeIde implements IDE { async runCommand(command: string): Promise { if (vscode.window.terminals.length) { - vscode.window.terminals[0].show(); - vscode.window.terminals[0].sendText(command, false); + const terminal = + vscode.window.activeTerminal ?? vscode.window.terminals[0]; + terminal.show(); + terminal.sendText(command, false); } else { const terminal = vscode.window.createTerminal(); terminal.show(); diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts index 3589f7ba4..bdc7de4fd 100644 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ b/extensions/vscode/src/lang-server/codeLens.ts @@ -4,7 +4,7 @@ import * as vscode from "vscode"; import { DIFF_DIRECTORY, DiffManager } from "../diff/horizontal"; import { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions"; -import { getAltOrOption, getMetaKeyLabel } from "../util/util"; +import { getAltOrOption, getMetaKeyLabel, getPlatform } from "../util/util"; import { getExtensionUri } from "../util/vscode"; class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { @@ -227,12 +227,15 @@ interface TutorialCodeLensItems { lineIncludes: string; commands: vscode.Command[]; } + +const cmdCtrl = getPlatform() === "mac" ? "Cmd" : "Ctrl"; + const actions: TutorialCodeLensItems[] = [ { - lineIncludes: "Step 2: Use the keyboard shortcut cmd/ctrl + M", + lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+L]`, commands: [ { - title: `Do it for me`, + title: `${cmdCtrl}+L`, command: "continue.focusContinueInput", }, ], @@ -253,17 +256,12 @@ const actions: TutorialCodeLensItems[] = [ ], }, { - lineIncludes: 'Step 3: Type "" and press Enter', + lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+I] to edit`, commands: [ { - title: `"/edit make this more efficient"`, - command: "continue.sendMainUserInput", - arguments: ["/edit make this more efficient"], - }, - { - title: `"/edit write comments for this function"`, - command: "continue.sendMainUserInput", - arguments: ["/edit write comments for this function"], + title: `${cmdCtrl}+I`, + command: "continue.quickEdit", + arguments: ["Add comments"], }, ], }, @@ -290,6 +288,15 @@ const actions: TutorialCodeLensItems[] = [ }, ], }, + { + lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+Shift+R]`, + commands: [ + { + title: `${cmdCtrl}+Shift+R`, + command: "continue.debugTerminal", + }, + ], + }, ]; class TutorialCodeLensProvider implements vscode.CodeLensProvider { @@ -346,26 +353,26 @@ class TutorialCodeLensProvider implements vscode.CodeLensProvider { } // Folding of the tutorial - const regionLines = lines - .map((line, i) => [line, i]) - .filter(([line, i]) => (line as string).startsWith("# region ")) - .map(([line, i]) => i); - for (const lineOfRegion of regionLines as number[]) { - const range = new vscode.Range(lineOfRegion, 0, lineOfRegion + 1, 0); + // const regionLines = lines + // .map((line, i) => [line, i]) + // .filter(([line, i]) => (line as string).startsWith("# region ")) + // .map(([line, i]) => i); + // for (const lineOfRegion of regionLines as number[]) { + // const range = new vscode.Range(lineOfRegion, 0, lineOfRegion + 1, 0); - const linesToFold = regionLines - .filter((i) => lineOfRegion !== i) - .flatMap((i) => { - return [i, (i as number) + 1]; - }); - codeLenses.push( - new vscode.CodeLens(range, { - title: `Begin Section`, - command: "continue.foldAndUnfold", - arguments: [linesToFold, [lineOfRegion, lineOfRegion + 1]], - }), - ); - } + // const linesToFold = regionLines + // .filter((i) => lineOfRegion !== i) + // .flatMap((i) => { + // return [i, (i as number) + 1]; + // }); + // codeLenses.push( + // new vscode.CodeLens(range, { + // title: `Begin Section`, + // command: "continue.foldAndUnfold", + // arguments: [linesToFold, [lineOfRegion, lineOfRegion + 1]], + // }), + // ); + // } return codeLenses; } diff --git a/extensions/vscode/src/util/cleanSlate.ts b/extensions/vscode/src/util/cleanSlate.ts new file mode 100644 index 000000000..837d93fec --- /dev/null +++ b/extensions/vscode/src/util/cleanSlate.ts @@ -0,0 +1,16 @@ +import { ExtensionContext } from "vscode"; +/** + * Clear all Continue-related artifacts to simulate a brand new user + */ +export function cleanSlate(context: ExtensionContext) { + // Commented just to be safe + // // Remove ~/.continue + // const continuePath = getContinueGlobalPath(); + // if (fs.existsSync(continuePath)) { + // fs.rmSync(continuePath, { recursive: true, force: true }); + // } + // // Clear extension's globalState + // context.globalState.keys().forEach((key) => { + // context.globalState.update(key, undefined); + // }); +} diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index b2f698013..c813a6cf1 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -56,6 +56,7 @@ export class TabAutocompleteModel { vscode.window .showWarningMessage( "Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs", + "Download Ollama", "Documentation", ) .then((value) => { @@ -65,6 +66,8 @@ export class TabAutocompleteModel { "https://continue.dev/docs/walkthroughs/tab-autocomplete", ), ); + } else if (value === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai")); } }); this.shownOllamaWarning = true; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 269b3074f..092c65e99 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -234,7 +234,7 @@ export class VsCodeWebviewProtocol { }); // History this.on("history/list", (msg) => { - return historyManager.list(); + return historyManager.list(msg.data); }); this.on("history/save", (msg) => { historyManager.save(msg.data); @@ -335,6 +335,17 @@ export class VsCodeWebviewProtocol { this.configHandler.reloadConfig(); }); + this.on("llm/listModels", async (msg) => { + try { + const model = await this.configHandler.llmFromTitle(msg.data.title); + const models = await model.listModels(); + return models; + } catch (e) { + console.warn("Error listing models", e); + return undefined; + } + }); + async function* llmStreamComplete( protocol: VsCodeWebviewProtocol, msg: Message, @@ -579,6 +590,7 @@ export class VsCodeWebviewProtocol { ? setupOptimizedMode : setupOptimizedExistingUserMode, ); + this.configHandler.reloadConfig(); }); this.on("openUrl", (msg) => { @@ -605,6 +617,9 @@ export class VsCodeWebviewProtocol { ); }); }); + this.on("copyText", async (msg) => { + await vscode.env.clipboard.writeText(msg.data.text); + }); } public request( diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 50ae708a1..13f205dbe 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -16,6 +16,7 @@ import { ContextSubmenuItem } from "core"; import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders"; import { useVscTheme } from "./hooks/useVscTheme"; import GUI from "./pages/gui"; +import LocalOnboarding from "./pages/localOnboarding"; import ExistingUserOnboarding from "./pages/onboarding/existingUserOnboarding"; import Onboarding from "./pages/onboarding/onboarding"; import Stats from "./pages/stats"; @@ -74,6 +75,10 @@ const router = createMemoryRouter([ path: "/existingUserOnboarding", element: , }, + { + path: "/localOnboarding", + element: , + }, { path: "/migration", element: , diff --git a/gui/src/components/HeaderButtonWithText.tsx b/gui/src/components/HeaderButtonWithText.tsx index b1b4f5241..9c5647a91 100644 --- a/gui/src/components/HeaderButtonWithText.tsx +++ b/gui/src/components/HeaderButtonWithText.tsx @@ -5,7 +5,7 @@ import { HeaderButton, StyledTooltip } from "."; import { v4 as uuidv4 } from "uuid"; interface HeaderButtonWithTextProps { - text: string; + text: string | undefined; onClick?: (e: any) => void; children: React.ReactNode; disabled?: boolean; @@ -15,6 +15,8 @@ interface HeaderButtonWithTextProps { onKeyDown?: (e: any) => void; tabIndex?: number; style?: React.CSSProperties; + backgroundColor?: string; + hoverBackgroundColor?: string; } const HeaderButtonWithText = React.forwardRef< @@ -29,6 +31,8 @@ const HeaderButtonWithText = React.forwardRef< return ( <> {props.children} - {tooltipPortalDiv && + {props.text && + tooltipPortalDiv && ReactDOM.createPortal( {props.text} diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index de33ed444..2cd23a5d9 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -7,8 +7,8 @@ import { useDispatch, useSelector } from "react-redux"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { + CustomScrollbarDiv, defaultBorderRadius, - vscBackground, vscForeground, vscInputBackground, } from "."; @@ -32,26 +32,9 @@ import ModelSelect from "./modelSelection/ModelSelect"; // #region Styled Components const FOOTER_HEIGHT = "1.8em"; -const LayoutTopDiv = styled.div` +const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; border-radius: ${defaultBorderRadius}; - scrollbar-base-color: transparent; - scrollbar-width: thin; - background-color: ${vscBackground}; - - & * { - ::-webkit-scrollbar { - width: 4px; - } - - ::-webkit-scrollbar:horizontal { - height: 4px; - } - - ::-webkit-scrollbar-thumb { - border-radius: 2px; - } - } `; const BottomMessageDiv = styled.div<{ displayOnBottom: boolean }>` @@ -103,6 +86,12 @@ const DropdownPortalDiv = styled.div` // #endregion +const HIDE_FOOTER_ON_PAGES = [ + "/onboarding", + "/existingUserOnboarding", + "/localOnboarding", +]; + const Layout = () => { const navigate = useNavigate(); const location = useLocation(); @@ -223,9 +212,10 @@ const Layout = () => { -
-
- {/* {localStorage.getItem("ide") === "jetbrains" || + {HIDE_FOOTER_ON_PAGES.includes(location.pathname) || ( +
+
+ {/* {localStorage.getItem("ide") === "jetbrains" || localStorage.getItem("hideFeature") === "true" || ( { color="yellow" /> )} */} - - {indexingProgress >= 1 && // Would take up too much space together with indexing progress - defaultModel?.provider === "free-trial" && - (location.pathname === "/settings" || - parseInt(localStorage.getItem("ftc") || "0") >= 125) && ( - + {indexingProgress >= 1 && // Would take up too much space together with indexing progress + defaultModel?.provider === "free-trial" && + (location.pathname === "/settings" || + parseInt(localStorage.getItem("ftc") || "0") >= 125) && ( + + )} + + {isJetBrains() || ( + )} - - {isJetBrains() || ( - - )} -
- { - navigate("/help"); - }} - > - - - { - // navigate("/settings"); - postToIde("openConfigJson", undefined); - }} - text="Configure Continue" - > - - -
+
+ { + navigate("/help"); + }} + > + + + { + // navigate("/settings"); + postToIde("openConfigJson", undefined); + }} + text="Configure Continue" + > + + +
+ )}

Add Docs

+

+ Continue pre-indexes many common documentation sites, but if there's one + you don't see in the dropdown, enter the URL here. Continue's indexing + engine will crawl the site and generate embeddings so that you can ask + questions. +

+ ; +} + export const TextArea = styled.textarea` padding: 8px; font-family: inherit; @@ -305,9 +325,14 @@ export const appear = keyframes` } `; -export const HeaderButton = styled.button<{ inverted: boolean | undefined }>` - background-color: ${({ inverted }) => - inverted ? vscForeground : "transparent"}; +export const HeaderButton = styled.button<{ + inverted: boolean | undefined; + backgroundColor?: string; + hoverBackgroundColor?: string; +}>` + background-color: ${({ inverted, backgroundColor }) => { + return backgroundColor ?? (inverted ? vscForeground : "transparent"); + }}; color: ${({ inverted }) => (inverted ? vscBackground : vscForeground)}; border: none; @@ -320,9 +345,9 @@ export const HeaderButton = styled.button<{ inverted: boolean | undefined }>` } &:hover { - background-color: ${({ inverted }) => + background-color: ${({ inverted, hoverBackgroundColor }) => typeof inverted === "undefined" || inverted - ? vscInputBackground + ? hoverBackgroundColor ?? vscInputBackground : "transparent"}; } display: flex; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index b594dd54a..ba6e23f3c 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -107,7 +107,7 @@ const ItemsDiv = styled.div` 0 0 0 1px rgba(0, 0, 0, 0.05), 0px 10px 20px rgba(0, 0, 0, 0.1); font-size: 0.9rem; - overflow: hidden; + overflow-x: hidden; padding: 0.2rem; position: relative; @@ -315,6 +315,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { ) : ( <> {subMenuTitle && {subMenuTitle}} + {/* */} {allItems.length ? ( allItems.map((item, index) => ( { ) : ( No results )} + {/* */} )} diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index 74b5d7a0a..7ab4b45fe 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -10,7 +10,7 @@ function getSuggestion( items: (props: { query: string }) => Promise, enterSubmenu: (editor: Editor, providerId: string) => void = (editor) => {}, onClose: () => void = () => {}, - onOpen: () => void = () => {} + onOpen: () => void = () => {}, ) { return { items, @@ -82,19 +82,19 @@ export function getMentionSuggestion( getSubmenuContextItemsRef: MutableRefObject< ( providerTitle: string | undefined, - query: string + query: string, ) => (ContextSubmenuItem & { providerTitle: string })[] >, enterSubmenu: (editor: Editor, providerId: string) => void, onClose: () => void, onOpen: () => void, - inSubmenu: MutableRefObject + inSubmenu: MutableRefObject, ) { const items = async ({ query }) => { if (inSubmenu.current) { const results = getSubmenuContextItemsRef.current( inSubmenu.current, - query + query, ); return results.map((result) => { return { @@ -111,7 +111,7 @@ export function getMentionSuggestion( ?.filter( (provider) => provider.title.toLowerCase().startsWith(query.toLowerCase()) || - provider.displayTitle.toLowerCase().startsWith(query.toLowerCase()) + provider.displayTitle.toLowerCase().startsWith(query.toLowerCase()), ) .map((provider) => ({ name: provider.displayTitle, @@ -144,7 +144,7 @@ export function getMentionSuggestion( action: () => { ideRequest( "openUrl", - "https://continue.dev/docs/customization/context-providers#built-in-context-providers" + "https://continue.dev/docs/customization/context-providers#built-in-context-providers", ); }, description: "", @@ -159,7 +159,7 @@ export function getMentionSuggestion( export function getCommandSuggestion( availableSlashCommandsRef: MutableRefObject, onClose: () => void, - onOpen: () => void + onOpen: () => void, ) { const items = async ({ query }) => { return ( diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index f0512163d..3c306a118 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -56,12 +56,17 @@ const commonTerminalCommands = [ "git", "curl", "wget", + "rbenv", + "gem", + "ruby", + "bundle", ]; function isTerminalCodeBlock(language: string | undefined, text: string) { return ( terminalLanguages.includes(language) || - (text.trim().split("\n").length === 1 && - commonTerminalCommands.some((c) => text.trim().startsWith(c))) + (language.length === 0 && + (text.trim().split("\n").length === 1 || + commonTerminalCommands.some((c) => text.trim().startsWith(c)))) ); } diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index d1c793fe2..e8acdd1a7 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -148,7 +148,7 @@ function ListBoxOption({ {option.title} {hovered && showDelete && ( { dispatch(setShowDialog(true)); dispatch( @@ -164,7 +164,8 @@ function ListBoxOption({ e.stopPropagation(); e.preventDefault(); }} - style={{ backgroundColor: vscInputBackground }} + backgroundColor={vscInputBackground} + hoverBackgroundColor={vscBackground} className="absolute right-0 p-1" > diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 562891b35..40644990c 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -8,6 +8,7 @@ import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { ideRequest } from "../util/ide"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; function truncateText(text: string, maxLength: number) { if (text.length > maxLength) { @@ -20,11 +21,14 @@ function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootState) => state.state); const defaultModel = useSelector(defaultModelSelector); const disableSessionTitles = useSelector( - (store: RootState) => store.state.config.disableSessionTitles + (store: RootState) => store.state.config.disableSessionTitles, ); - async function getHistory(): Promise { - return await ideRequest("history/list", undefined); + async function getHistory( + offset?: number, + limit?: number, + ): Promise { + return await ideRequest("history/list", { offset, limit }); } async function saveSession() { @@ -39,7 +43,7 @@ function useHistory(dispatch: Dispatch) { .split("\n") .filter((l) => l.trim() !== "") .slice(-1)[0] || "", - 50 + 50, ); if ( @@ -72,6 +76,7 @@ function useHistory(dispatch: Dispatch) { sessionId: stateCopy.sessionId, workspaceDirectory: window.workspacePaths?.[0] || "", }; + setLocalStorage("lastSessionId", stateCopy.sessionId); return await ideRequest("history/save", sessionInfo); } @@ -80,10 +85,31 @@ function useHistory(dispatch: Dispatch) { } async function loadSession(id: string): Promise { - return await ideRequest("history/load", { id }); + setLocalStorage("lastSessionId", state.sessionId); + const json: PersistedSessionInfo = await ideRequest("history/load", { id }); + dispatch(newSession(json)); + return json; } - return { getHistory, saveSession, deleteSession, loadSession }; + async function loadLastSession(): Promise { + const lastSessionId = getLocalStorage("lastSessionId"); + if (lastSessionId) { + return await loadSession(lastSessionId); + } + } + + function getLastSessionId(): string { + return getLocalStorage("lastSessionId"); + } + + return { + getHistory, + saveSession, + deleteSession, + loadSession, + loadLastSession, + getLastSessionId, + }; } export default useHistory; diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index b0097f3ce..a0c95e62a 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -1,5 +1,5 @@ import { ContextSubmenuItem } from "core"; -import { getBasename, getLastNPathParts } from "core/util"; +import { deduplicateArray, getBasename, getLastNPathParts } from "core/util"; import MiniSearch, { SearchResult } from "minisearch"; import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; @@ -13,6 +13,8 @@ const MINISEARCH_OPTIONS = { fuzzy: 2, }; +const MAX_LENGTH = 10; + function useSubmenuContextProviders() { // TODO: Refresh periodically @@ -24,7 +26,7 @@ function useSubmenuContextProviders() { }>({}); const contextProviderDescriptions = useSelector( - selectContextProviderDescriptions + selectContextProviderDescriptions, ); const [loaded, setLoaded] = useState(false); @@ -57,11 +59,17 @@ function useSubmenuContextProviders() { if (data.provider === "file") { const openFiles = await getOpenFileItems(); - setFallbackResults((prev) => ({ ...prev, file: openFiles })); + setFallbackResults((prev) => ({ + ...prev, + file: [ + ...openFiles, + ...data.submenuItems.slice(0, MAX_LENGTH - openFiles.length), + ], + })); } else { setFallbackResults((prev) => ({ ...prev, - [data.provider]: data.submenuItems.slice(0, 6), + [data.provider]: data.submenuItems.slice(0, MAX_LENGTH), })); } }); @@ -77,7 +85,13 @@ function useSubmenuContextProviders() { // Refresh open files periodically const interval = setInterval(async () => { const openFiles = await getOpenFileItems(); - setFallbackResults((prev) => ({ ...prev, file: openFiles })); + setFallbackResults((prev) => ({ + ...prev, + file: deduplicateArray( + [...openFiles, ...prev.file], + (a, b) => a.id === b.id, + ), + })); }, 2_000); return () => { @@ -103,11 +117,17 @@ function useSubmenuContextProviders() { if (description.title === "file") { const openFiles = await getOpenFileItems(); - setFallbackResults((prev) => ({ ...prev, file: openFiles })); + setFallbackResults((prev) => ({ + ...prev, + file: [ + ...openFiles, + ...items.slice(0, MAX_LENGTH - openFiles.length), + ], + })); } else { setFallbackResults((prev) => ({ ...prev, - [description.title]: items.slice(0, 6), + [description.title]: items.slice(0, MAX_LENGTH), })); } }); @@ -115,14 +135,14 @@ function useSubmenuContextProviders() { function getSubmenuSearchResults( providerTitle: string | undefined, - query: string + query: string, ): SearchResult[] { if (providerTitle === undefined) { // Return search combined from all providers const results = Object.keys(minisearches).map((providerTitle) => { const results = minisearches[providerTitle].search( query, - MINISEARCH_OPTIONS + MINISEARCH_OPTIONS, ); return results.map((result) => { return { ...result, providerTitle }; @@ -145,7 +165,7 @@ function useSubmenuContextProviders() { function getSubmenuContextItems( providerTitle: string | undefined, query: string, - limit: number = 10 + limit: number = MAX_LENGTH, ): (ContextSubmenuItem & { providerTitle: string })[] { const results = getSubmenuSearchResults(providerTitle, query); if (results.length === 0) { diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 963b9e08f..46917aede 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -1,4 +1,5 @@ import { + ArrowLeftIcon, ChatBubbleOvalLeftIcon, CodeBracketSquareIcon, ExclamationTriangleIcon, @@ -102,7 +103,7 @@ const NewSessionButton = styled.div` font-size: 12px; border-radius: ${defaultBorderRadius}; - padding: 2px 8px; + padding: 2px 6px; color: ${lightGray}; &:hover { @@ -327,7 +328,8 @@ function GUI(props: GUIProps) { ], ); - const { saveSession } = useHistory(dispatch); + const { saveSession, getLastSessionId, loadLastSession } = + useHistory(dispatch); useWebviewListener( "newSession", @@ -467,6 +469,16 @@ function GUI(props: GUIProps) { > New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"}) + ) : getLastSessionId() ? ( + { + loadLastSession(); + }} + className="mr-auto flex items-center gap-1" + > + + Last Session + ) : null} diff --git a/gui/src/pages/history.tsx b/gui/src/pages/history.tsx index 6110818ef..6ad34e0e4 100644 --- a/gui/src/pages/history.tsx +++ b/gui/src/pages/history.tsx @@ -1,5 +1,5 @@ import { ArrowLeftIcon, TrashIcon } from "@heroicons/react/24/outline"; -import { PersistedSessionInfo, SessionInfo } from "core"; +import { SessionInfo } from "core"; import MiniSearch from "minisearch"; import React, { Fragment, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; @@ -16,7 +16,6 @@ import { import HeaderButtonWithText from "../components/HeaderButtonWithText"; import useHistory from "../hooks/useHistory"; import { useNavigationListener } from "../hooks/useNavigationListener"; -import { newSession } from "../redux/slices/stateSlice"; import { getFontSize } from "../util"; const SearchBar = styled.input` @@ -106,10 +105,7 @@ function TableRow({ // Save current session saveSession(); - const json: PersistedSessionInfo = await loadSession( - session.sessionId - ); - dispatch(newSession(json)); + await loadSession(session.sessionId); navigate("/"); }} > @@ -165,7 +161,7 @@ function History() { const deleteSessionInUI = async (sessionId: string) => { setSessions((prev) => - prev.filter((session) => session.sessionId !== sessionId) + prev.filter((session) => session.sessionId !== sessionId), ); }; @@ -182,7 +178,7 @@ function History() { new MiniSearch({ fields: ["title"], storeFields: ["title", "sessionId", "id"], - }) + }), ); const [searchTerm, setSearchTerm] = useState(""); @@ -195,7 +191,7 @@ function History() { title: session.title, sessionId: session.sessionId, id: session.sessionId, - })) + })), ); }; fetchSessions(); @@ -227,8 +223,8 @@ function History() { .sort( (a, b) => parseDate(b.dateCreated).getTime() - - parseDate(a.dateCreated).getTime() - ) + parseDate(a.dateCreated).getTime(), + ), ); }, [filteringByWorkspace, sessions, searchTerm, minisearch]); diff --git a/gui/src/pages/localOnboarding.tsx b/gui/src/pages/localOnboarding.tsx new file mode 100644 index 000000000..390b3ad1d --- /dev/null +++ b/gui/src/pages/localOnboarding.tsx @@ -0,0 +1,297 @@ +import { CheckIcon, PlayIcon } from "@heroicons/react/24/outline"; +import { CheckCircleIcon as CheckCircleIconSolid } from "@heroicons/react/24/solid"; +import { useEffect, useState } from "react"; +import ReactDOM from "react-dom"; +import { useNavigate } from "react-router-dom"; +import styled from "styled-components"; +import { + Button, + StyledTooltip, + defaultBorderRadius, + lightGray, + vscButtonBackground, + vscButtonForeground, + vscForeground, +} from "../components"; +import { ideRequest } from "../util/ide"; +import { WebviewIde } from "../util/webviewIde"; +import { StyledButton } from "./onboarding/components"; + +const ModelPillDiv = styled.div<{ selected: boolean }>` + padding: 4px 4px; + border-radius: ${defaultBorderRadius}; + border: 0.5px solid ${lightGray}; + background-color: ${({ selected }) => + selected ? vscButtonBackground : "transparent"}; + color: ${({ selected }) => (selected ? vscButtonForeground : vscForeground)}; + cursor: pointer; + transition: background-color 0.1s ease-out; + + text-align: center; + align-items: center; + + &:hover { + color: ${vscButtonForeground}; + background-color: ${vscButtonBackground}; + } +`; + +function CheckMarkHeader(props: { children: string; complete: boolean }) { + return ( +
+ {props.complete ? ( + + ) : ( +
+ )} +

{props.children}

+
+ ); +} + +const RunInTerminalDiv = styled.div<{ clicked: boolean }>` + padding-left: 8px; + padding-right: 8px; + display: flex; + border-radius: ${defaultBorderRadius}; + width: fit-content; + gap: 8px; + + ${({ clicked }) => clicked && "background-color: #0f02;"} + + align-items: center; + + border: 1px solid ${lightGray}; + + cursor: pointer; + &:hover { + background-color: ${({ clicked }) => (clicked ? "#0f02" : "#fff1")}; + } +`; + +function RunInTerminalButton(props: { command: string }) { + const [clicked, setClicked] = useState(false); + + const id = `info-hover-${encodeURIComponent(props.command)}`; + const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); + + return ( + <> +
+ { + new WebviewIde().runCommand(props.command); + setClicked(true); + setTimeout(() => setClicked(false), 2000); + ideRequest("copyText", { text: props.command }); + }} + > +
+            
+              {props.command}
+            
+          
+ {clicked ? ( + + ) : ( + + )} +
+
+ {tooltipPortalDiv && + ReactDOM.createPortal( + + Run in terminal + , + tooltipPortalDiv, + )} + + ); +} + +// The "Ollama" title is assumed from core/config/onboarding.ts +const assumedModelTitle = "Ollama"; +const recommendedChatModel = "llama3"; +const recommendedAutocompleteModel = "starcoder2:3b"; + +function LocalOnboarding() { + const navigate = useNavigate(); + + const [stage1Done, setStage1Done] = useState(false); + const [stage2Done, setStage2Done] = useState(false); + const [stage3Done, setStage3Done] = useState(false); + + const [ollamaModels, setOllamaModels] = useState( + undefined, + ); + const [ollamaConnectionStatus, setOllamaConnectionStatus] = useState< + "waitingToDownload" | "downloading" | "verified" + >("waitingToDownload"); + + const [selectedModel, setSelectedModel] = useState( + undefined, + ); + + useEffect(() => { + if (ollamaModels?.some((model) => model.startsWith(recommendedChatModel))) { + setStage2Done(true); + + // Send an empty request to load the model + ideRequest("llm/complete", { + completionOptions: {}, + prompt: "", + title: assumedModelTitle, + }); + } + }, [ollamaModels]); + + useEffect(() => { + if ( + ollamaModels?.some((model) => + model.startsWith(recommendedAutocompleteModel), + ) + ) { + setStage3Done(true); + } + }, [ollamaModels]); + + useEffect(() => { + const checkModels = async () => { + const models = await ideRequest("llm/listModels", { + title: assumedModelTitle, + }); + if (Array.isArray(models)) { + setOllamaConnectionStatus("verified"); + setStage1Done(true); + setOllamaModels(models); + } + }; + checkModels(); + const interval = setInterval(checkModels, 1000); + + return () => { + clearInterval(interval); + }; + }, [ollamaConnectionStatus]); + + return ( +
+

Set up your local LLM

+ + 1. Download Ollama + + {ollamaConnectionStatus === "verified" || ( + <> +

+ Click below to download Ollama from https://ollama.ai. Once + downloaded, you only need to start the application. +

+ + + )} + {ollamaConnectionStatus === "downloading" && ( +

Checking for connection to Ollama...

+ )} + {ollamaConnectionStatus === "verified" &&

Ollama is connected!

} +

+ + 2. Download a model for chat + + {stage1Done && ( + <> + We recommend using Llama 3, the latest open-source model trained by + Meta. +

+ + + )} +

+ + 3. Download a model for tab autocomplete + + {stage1Done && ( + <> + We recommend using Starcoder 2, a state-of-the-art 3b parameter + autocomplete model trained by Hugging Face. +

+ + + )} + {/* {ollamaModels?.length > 0 || ( +
+

+ It looks like you don't have any models downloaded. Click here to + download the recommended model, "starcoder2:3b". This will take up + 1.7GB of space. +

+
+ +
+
+ )} */} + {/*
+ {ollamaModels?.map((model) => { + return ( + setSelectedModel(model)} + > + {model} + + ); + })} +
*/} +

+
+ { + navigate("/"); + }} + > + Continue + +
+
+ ); +} + +export default LocalOnboarding; diff --git a/gui/src/pages/models.tsx b/gui/src/pages/models.tsx index f2636dd39..ca8a3579f 100644 --- a/gui/src/pages/models.tsx +++ b/gui/src/pages/models.tsx @@ -95,34 +95,54 @@ function Models() { ) : ( - {Object.entries(MODEL_INFO).map(([name, pkg]) => ( - { - const model = { - ...pkg.params, - ..._.merge( - {}, - ...(pkg.dimensions?.map((dimension, i) => { - if (!dimensionChoices?.[i]) return {}; - return { - ...dimension.options[dimensionChoices[i]], - }; - }) || []) - ), - provider: PROVIDER_INFO[selectedProvider].provider, - }; - postToIde("config/addModel", { model }); - dispatch(setDefaultModel(model.title)); - navigate("/"); - }} - /> - ))} + {MODEL_INFO.map((pkg) => { + if (typeof pkg === "string") { + return ( +
+

{pkg}

+
+
+ ); + } else { + return ( + { + const model = { + ...pkg.params, + ..._.merge( + {}, + ...(pkg.dimensions?.map((dimension, i) => { + if (!dimensionChoices?.[i]) return {}; + return { + ...dimension.options[dimensionChoices[i]], + }; + }) || []), + ), + provider: PROVIDER_INFO[selectedProvider].provider, + }; + postToIde("config/addModel", { model }); + dispatch(setDefaultModel(model.title)); + navigate("/"); + }} + /> + ); + } + })}
)} diff --git a/gui/src/pages/onboarding/components.ts b/gui/src/pages/onboarding/components.ts index 0ee5dd475..de8d50495 100644 --- a/gui/src/pages/onboarding/components.ts +++ b/gui/src/pages/onboarding/components.ts @@ -7,7 +7,7 @@ import { vscForeground, } from "../../components"; -export const StyledButton = styled(Button)` +export const StyledButton = styled(Button)<{ blurColor?: string }>` margin-left: auto; background-color: transparent; color: ${vscForeground}; @@ -15,7 +15,8 @@ export const StyledButton = styled(Button)` &:hover { ${(props) => - !props.disabled && `box-shadow: 0 0 4px 4px ${vscButtonBackground};`} + !props.disabled && + `box-shadow: 0 0 4px 4px ${props.blurColor ?? vscButtonBackground};`} } `; diff --git a/gui/src/pages/onboarding/onboarding.tsx b/gui/src/pages/onboarding/onboarding.tsx index 20bbdbd46..29555a35d 100644 --- a/gui/src/pages/onboarding/onboarding.tsx +++ b/gui/src/pages/onboarding/onboarding.tsx @@ -42,11 +42,11 @@ function Onboarding() { Embeddings: Local sentence-transformers model

- Autocomplete: Starcoder2 3b (manual setup with Ollama, LM - Studio, etc.) + Autocomplete: Starcoder2 3b (set up with Ollama, LM Studio, + etc.)

- Chat: Manual setup with Ollama, LM Studio, etc. + Chat: Llama 3 with Ollama, LM Studio, etc.

)}

@@ -106,19 +106,47 @@ function Onboarding() { This can always be done later.

+ {selected === 2 && ( +

+ Use config.json to configure your own{" "} + models,{" "} + + context providers + + ,{" "} + + slash commands + + , and more. +

+ )}
{ - postToIde("showTutorial", undefined); postToIde("completeOnboarding", { mode: ["local", "optimized", "custom"][selected] as any, }); setLocalStorage("onboardingComplete", true); - postToIde("index/forceReIndex", undefined); - navigate("/"); + + if (selected === 0) { + navigate("/localOnboarding"); + } else { + // Only needed when we switch from the default (local) embeddings provider + postToIde("index/forceReIndex", undefined); + // Don't show the tutorial above yet because there's another step to complete at /localOnboarding + postToIde("showTutorial", undefined); + navigate("/"); + } }} > Continue diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 99d52ae72..b25edd7a5 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -164,7 +164,9 @@ export const stateSlice = createSlice({ ) => { const defaultModelTitle = config.models.find((model) => model.title === state.defaultModelTitle) - ?.title || config.models[0].title; + ?.title || + config.models[0]?.title || + ""; state.config = config; state.defaultModelTitle = defaultModelTitle; }, diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index faddd64f6..2ad952bd3 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -1,6 +1,7 @@ type LocalStorageTypes = { onboardingComplete: boolean; mainTextEntryCounter: number; + lastSessionId: string | undefined; }; export function getLocalStorage( diff --git a/gui/src/util/modelData.ts b/gui/src/util/modelData.ts index 17bfe50bd..429a1f2b8 100644 --- a/gui/src/util/modelData.ts +++ b/gui/src/util/modelData.ts @@ -644,18 +644,23 @@ const AUTODETECT: ModelPackage = { providerOptions: [], }; -export const MODEL_INFO: ModelPackage[] = [ +export const MODEL_INFO: (ModelPackage | string)[] = [ + "OpenAI", gpt4turbo, gpt4, gpt35turbo, + "Anthropic", claude3Opus, claude3Sonnet, claude3Haiku, + claude2, + "Cohere", commandR, commandRPlus, + "Gemini", gemini15Pro, geminiPro, - claude2, + "Open Source", deepseek, mistral, codellama70bTrial,