✨ Improved onboarding experience (#1155)

* 🚸 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
This commit is contained in:
Nate Sesti 2024-04-19 17:55:16 -07:00 • committed by GitHub
parent 86f6811066
commit 49cb06df70
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
40 changed files with 820 additions and 262 deletions

View file

@ -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);

View file

@ -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, {

View file

@ -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",

View file

@ -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<IdeSettings>,
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) => {

View file

@ -71,6 +71,11 @@ export function setupLocalMode(
return {
...config,
models: [
{
title: "Llama 3",
provider: "ollama",
model: "llama3",
},
{
title: "Ollama",
provider: "ollama",

View file

@ -19,6 +19,11 @@ export type ProtocolGeneratorType<T> = 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;

View file

@ -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;
}

View file

@ -3,7 +3,7 @@ Welcome to Continue!
_________ _____ _____
__ ____/______ _______ __ /____(_)_______ ____ _______
_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
/ /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
\____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/

View file

@ -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": [
]
}

View file

@ -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
# Ready to learn more? Check out the Continue documentation: https://continue.dev/docs

View file

@ -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 <kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd>.
![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.
<kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd> = Select code
@ -17,13 +19,3 @@ Continue is currently in the left sidebar, but we recommend moving it to the rig
<kbd>Cmd/Ctrl</kbd> + <kbd>I</kbd> = Quick edit
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = 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)

View file

@ -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": [

View file

@ -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<InlineCompletionItem[] | InlineCompletionList> {
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 {

View file

@ -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[],

View file

@ -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",

View file

@ -231,8 +231,10 @@ class VsCodeIde implements IDE {
async runCommand(command: string): Promise<void> {
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();

View file

@ -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 "<your edit request>" 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;
}

View file

@ -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);
// });
}

View file

@ -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;

View file

@ -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<WebviewProtocol["llm/streamComplete"][0]>,
@ -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<T extends keyof ReverseWebviewProtocol>(

View file

@ -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: <ExistingUserOnboarding />,
},
{
path: "/localOnboarding",
element: <LocalOnboarding />,
},
{
path: "/migration",
element: <MigrationPage />,

View file

@ -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 (
<>
<HeaderButton
hoverBackgroundColor={props.hoverBackgroundColor}
backgroundColor={props.backgroundColor}
data-tooltip-id={`header_button_${id}`}
inverted={props.inverted}
disabled={props.disabled}
@ -49,7 +53,8 @@ const HeaderButtonWithText = React.forwardRef<
>
{props.children}
</HeaderButton>
{tooltipPortalDiv &&
{props.text &&
tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id={`header_button_${id}`} place="bottom">
{props.text}

View file

@ -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 = () => {
<GridDiv>
<Outlet />
<DropdownPortalDiv id="model-select-top-div"></DropdownPortalDiv>
<Footer>
<div className="mr-auto flex gap-2 items-center">
{/* {localStorage.getItem("ide") === "jetbrains" ||
{HIDE_FOOTER_ON_PAGES.includes(location.pathname) || (
<Footer>
<div className="mr-auto flex gap-2 items-center">
{/* {localStorage.getItem("ide") === "jetbrains" ||
localStorage.getItem("hideFeature") === "true" || (
<SparklesIcon
className="cursor-pointer"
@ -253,43 +243,44 @@ const Layout = () => {
color="yellow"
/>
)} */}
<ModelSelect />
{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) && (
<ProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={250}
<ModelSelect />
{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) && (
<ProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={250}
/>
)}
{isJetBrains() || (
<IndexingProgressBar
currentlyIndexing={indexingTask}
completed={indexingProgress * 100}
total={100}
/>
)}
{isJetBrains() || (
<IndexingProgressBar
currentlyIndexing={indexingTask}
completed={indexingProgress * 100}
total={100}
/>
)}
</div>
<HeaderButtonWithText
text="Help"
onClick={() => {
navigate("/help");
}}
>
<QuestionMarkCircleIcon width="1.4em" height="1.4em" />
</HeaderButtonWithText>
<HeaderButtonWithText
onClick={() => {
// navigate("/settings");
postToIde("openConfigJson", undefined);
}}
text="Configure Continue"
>
<Cog6ToothIcon width="1.4em" height="1.4em" />
</HeaderButtonWithText>
</Footer>
</div>
<HeaderButtonWithText
text="Help"
onClick={() => {
navigate("/help");
}}
>
<QuestionMarkCircleIcon width="1.4em" height="1.4em" />
</HeaderButtonWithText>
<HeaderButtonWithText
onClick={() => {
// navigate("/settings");
postToIde("openConfigJson", undefined);
}}
text="Configure Continue"
>
<Cog6ToothIcon width="1.4em" height="1.4em" />
</HeaderButtonWithText>
</Footer>
)}
</GridDiv>
<BottomMessageDiv

View file

@ -37,6 +37,13 @@ function AddDocsDialog() {
<div className="p-4">
<h3>Add Docs</h3>
<p>
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.
</p>
<Input
type="url"
placeholder="URL"

View file

@ -139,20 +139,40 @@ export const Button = styled.button`
}
`;
export const StyledTooltip = styled(Tooltip)`
font-size: 12px;
background-color: ${vscEditorBackground};
color: ${vscForeground};
border-radius: ${defaultBorderRadius};
box-shadow: 0 0 1px 0 ${vscForeground};
padding: 2px;
padding-left: 4px;
padding-right: 4px;
z-index: 1000;
export const CustomScrollbarDiv = styled.div`
scrollbar-base-color: transparent;
scrollbar-width: thin;
background-color: ${vscBackground};
max-width: 80vw;
& * {
::-webkit-scrollbar {
width: 4px;
}
::-webkit-scrollbar:horizontal {
height: 4px;
}
::-webkit-scrollbar-thumb {
border-radius: 2px;
}
}
`;
const TooltipStyles = {
fontSize: "12px",
backgroundColor: vscInputBackground,
boxShadow: `0px 0px 2px 1px ${vscBadgeBackground}`,
color: vscForeground,
padding: "2px 6px",
zIndex: 1000,
maxWidth: "80vw",
};
export function StyledTooltip(props) {
return <Tooltip {...props} style={TooltipStyles} />;
}
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;

View file

@ -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 && <ItemDiv className="mb-2">{subMenuTitle}</ItemDiv>}
{/* <CustomScrollbarDiv className="overflow-y-scroll max-h-96"> */}
{allItems.length ? (
allItems.map((item, index) => (
<ItemDiv
@ -369,6 +370,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
) : (
<ItemDiv className="item">No results</ItemDiv>
)}
{/* </CustomScrollbarDiv> */}
</>
)}
</ItemsDiv>

View file

@ -10,7 +10,7 @@ function getSuggestion(
items: (props: { query: string }) => Promise<ComboBoxItem[]>,
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<string | undefined>
inSubmenu: MutableRefObject<string | undefined>,
) {
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<ComboBoxItem[]>,
onClose: () => void,
onOpen: () => void
onOpen: () => void,
) {
const items = async ({ query }) => {
return (

View file

@ -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))))
);
}

View file

@ -148,7 +148,7 @@ function ListBoxOption({
<span>{option.title}</span>
{hovered && showDelete && (
<HeaderButtonWithText
text="Delete"
text={undefined}
onClick={(e) => {
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"
>
<TrashIcon width="1.2em" height="1.2em" />

View file

@ -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<SessionInfo[]> {
return await ideRequest("history/list", undefined);
async function getHistory(
offset?: number,
limit?: number,
): Promise<SessionInfo[]> {
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<PersistedSessionInfo> {
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<PersistedSessionInfo> {
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;

View file

@ -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) {

View file

@ -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"})
</NewSessionButton>
) : getLastSessionId() ? (
<NewSessionButton
onClick={async () => {
loadLastSession();
}}
className="mr-auto flex items-center gap-1"
>
<ArrowLeftIcon width="11px" height="11px" />
Last Session
</NewSessionButton>
) : null}
</div>
</TopGuiDiv>

View file

@ -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]);

View file

@ -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 (
<div className="flex gap-4 items-center">
{props.complete ? (
<CheckCircleIconSolid
width="24px"
height="24px"
color="#0b0"
className="flex-none"
></CheckCircleIconSolid>
) : (
<div
className="flex-none border border-solid rounded-full w-5 h-5 mt-1"
style={{ borderColor: lightGray }}
></div>
)}
<h3>{props.children}</h3>
</div>
);
}
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 (
<>
<div
className="flex items-center justify-center mt-8"
data-tooltip-id={id}
>
<RunInTerminalDiv
clicked={clicked}
style={{ border: `0.5px solid ${lightGray}` }}
className="grid-cols-2"
onClick={() => {
new WebviewIde().runCommand(props.command);
setClicked(true);
setTimeout(() => setClicked(false), 2000);
ideRequest("copyText", { text: props.command });
}}
>
<pre>
<code
style={{
color: vscForeground,
backgroundColor: "transparent",
}}
>
{props.command}
</code>
</pre>
{clicked ? (
<CheckIcon
width="20px"
height="20px"
className="cursor-pointer hover:bg-white"
color="#0b0"
/>
) : (
<PlayIcon
width="20px"
height="20px"
className="cursor-pointer hover:bg-white"
/>
)}
</RunInTerminalDiv>
</div>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id={id} place="top">
Run in terminal
</StyledTooltip>,
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<string[] | undefined>(
undefined,
);
const [ollamaConnectionStatus, setOllamaConnectionStatus] = useState<
"waitingToDownload" | "downloading" | "verified"
>("waitingToDownload");
const [selectedModel, setSelectedModel] = useState<string | undefined>(
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 (
<div className="p-8 overflow-y-scroll">
<h1 className="text-center">Set up your local LLM</h1>
<CheckMarkHeader complete={stage1Done}>
1. Download Ollama
</CheckMarkHeader>
{ollamaConnectionStatus === "verified" || (
<>
<p>
Click below to download Ollama from https://ollama.ai. Once
downloaded, you only need to start the application.
</p>
<div className="text-center">
<a href="https://ollama.ai">
<Button onClick={() => setOllamaConnectionStatus("downloading")}>
Download Ollama
</Button>
</a>
</div>
</>
)}
{ollamaConnectionStatus === "downloading" && (
<p>Checking for connection to Ollama...</p>
)}
{ollamaConnectionStatus === "verified" && <p>Ollama is connected!</p>}
<br></br>
<CheckMarkHeader complete={stage2Done}>
2. Download a model for chat
</CheckMarkHeader>
{stage1Done && (
<>
We recommend using Llama 3, the latest open-source model trained by
Meta.
<br></br>
<RunInTerminalButton
command={`ollama run ${recommendedChatModel}`}
></RunInTerminalButton>
</>
)}
<br></br>
<CheckMarkHeader complete={stage3Done}>
3. Download a model for tab autocomplete
</CheckMarkHeader>
{stage1Done && (
<>
We recommend using Starcoder 2, a state-of-the-art 3b parameter
autocomplete model trained by Hugging Face.
<br></br>
<RunInTerminalButton
command={`ollama run ${recommendedAutocompleteModel}`}
></RunInTerminalButton>
</>
)}
{/* {ollamaModels?.length > 0 || (
<div>
<p>
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.
</p>
<div className="text-right">
<Button onClick={() => {}}>Download Starcoder 2</Button>
</div>
</div>
)} */}
{/* <div className="flex gap-1 flex-wrap">
{ollamaModels?.map((model) => {
return (
<ModelPillDiv
selected={selectedModel === model}
onClick={() => setSelectedModel(model)}
>
{model}
</ModelPillDiv>
);
})}
</div> */}
<br></br>
<div className="flex flex-col justify-end mt-8">
<StyledButton
disabled={false}
onClick={() => {
navigate("/");
}}
>
Continue
</StyledButton>
</div>
</div>
);
}
export default LocalOnboarding;

View file

@ -95,34 +95,54 @@ function Models() {
</GridDiv>
) : (
<GridDiv>
{Object.entries(MODEL_INFO).map(([name, pkg]) => (
<ModelCard
title={pkg.title}
description={pkg.description}
tags={pkg.tags}
icon={pkg.icon}
dimensions={pkg.dimensions}
providerOptions={pkg.providerOptions}
onClick={(e, dimensionChoices, selectedProvider) => {
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 (
<div className="-my-8 grid grid-cols-[auto_1fr] w-full items-center">
<h3 className="">{pkg}</h3>
<hr
className="ml-2"
style={{
height: "0px",
width: "calc(100% - 16px)",
color: lightGray,
border: `1px solid ${lightGray}`,
borderRadius: "2px",
}}
></hr>
</div>
);
} else {
return (
<ModelCard
title={pkg.title}
description={pkg.description}
tags={pkg.tags}
icon={pkg.icon}
dimensions={pkg.dimensions}
providerOptions={pkg.providerOptions}
onClick={(e, dimensionChoices, selectedProvider) => {
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("/");
}}
/>
);
}
})}
</GridDiv>
)}

View file

@ -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};`}
}
`;

View file

@ -42,11 +42,11 @@ function Onboarding() {
<b>Embeddings:</b> Local sentence-transformers model
<br />
<br />
<b>Autocomplete:</b> Starcoder2 3b (manual setup with Ollama, LM
Studio, etc.)
<b>Autocomplete:</b> Starcoder2 3b (set up with Ollama, LM Studio,
etc.)
<br />
<br />
<b>Chat:</b> Manual setup with Ollama, LM Studio, etc.
<b>Chat:</b> Llama 3 with Ollama, LM Studio, etc.
</p>
)}
<br></br>
@ -106,19 +106,47 @@ function Onboarding() {
This can always be done later.
</p>
</Div>
{selected === 2 && (
<p className="px-3">
Use <code>config.json</code> to configure your own{" "}
<a href="https://continue.dev/docs/model-setup/overview">models</a>,{" "}
<a href="https://continue.dev/docs/customization/context-providers">
context providers
</a>
,{" "}
<a href="https://continue.dev/docs/customization/slash-commands">
slash commands
</a>
, and <a href="https://continue.dev/docs/reference/config">more</a>.
</p>
)}
<br />
<div className="flex">
<StyledButton
blurColor={
selected === 0
? greenButtonColor
: selected === 1
? "#be841b"
: "#1b84be"
}
disabled={selected < 0}
onClick={() => {
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

View file

@ -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;
},

View file

@ -1,6 +1,7 @@
type LocalStorageTypes = {
onboardingComplete: boolean;
mainTextEntryCounter: number;
lastSessionId: string | undefined;
};
export function getLocalStorage<T extends keyof LocalStorageTypes>(

View file

@ -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,