Merge pull request #2978 from continuedev/dallin/header-not-footer

Remove Footer
This commit is contained in:
Nate Sesti 2024-11-20 22:35:38 -08:00 • committed by GitHub
commit a68a8775db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 650 additions and 319 deletions

View file

@ -12,6 +12,7 @@ import {
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath } from "../util/paths.js";
import { ConfigResult } from "./load.js";
import {
@ -84,6 +85,18 @@ export class ConfigHandler {
return this.profiles.filter((p) => p.profileId !== this.selectedProfileId);
}
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
await this.ide.openFile(getConfigJsonPath());
} else {
await this.ide.openUrl(
"https://app.continue.dev/",
// `https://app.continue.dev/workspaces/${openProfileId}/chat`,
);
}
}
private async fetchControlPlaneProfiles() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient

View file

@ -28,7 +28,11 @@ import { DevDataSqliteDb } from "./util/devdataSqlite";
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import {
editConfigJson,
getConfigJsonPath,
setupInitialDotContinueDirectory,
} from "./util/paths";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -264,6 +268,10 @@ export class Core {
await this.configHandler.reloadConfig();
});
on("config/openProfile", async (msg) => {
await this.configHandler.openConfigProfile(msg.data.profileId);
});
on("config/reload", (msg) => {
void this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();

1
core/index.d.ts vendored
View file

@ -526,6 +526,7 @@ export interface IDE {
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
openFile(path: string): Promise<void>;
openUrl(url: string): Promise<void>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;

View file

@ -69,6 +69,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, BrowserSerializedContinueConfig];
"config/listProfiles": [undefined, ProfileDescription[]];
"config/openProfile": [{ profileId: string | undefined }, void];
"context/getContextItems": [
{
name: string;

View file

@ -28,6 +28,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
showVirtualFile: [{ name: string; content: string }, void];
getContinueDir: [undefined, string];
openFile: [{ path: string }, void];
openUrl: [string, void];
runCommand: [{ command: string }, void];
getSearchResults: [{ query: string }, string];
subprocess: [{ command: string; cwd?: string }, [string, string]];
@ -49,11 +50,17 @@ export type ToIdeFromWebviewOrCoreProtocol = {
];
getProblems: [{ filepath: string }, Problem[]];
getOpenFiles: [undefined, string[]];
getCurrentFile: [undefined, undefined | {
isUntitled: boolean;
path: string;
contents: string;
}];
getCurrentFile: [
undefined,
(
| undefined
| {
isUntitled: boolean;
path: string;
contents: string;
}
),
];
getPinnedFiles: [undefined, string[]];
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
readRangeInFile: [{ filepath: string; range: Range }, string];

View file

@ -30,7 +30,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
@ -101,7 +100,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
openSettings: [undefined, void];
/**
* @deprecated Use navigateTo with a path instead.
*/

View file

@ -21,6 +21,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/reload",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@ -53,7 +55,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
//
"completeOnboarding",
"addAutocompleteModel",
"config/listProfiles",
"profiles/switch",
"didChangeSelectedProfile",
];
@ -71,4 +72,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"didChangeAvailableProfiles",
"setTTSActive",
"getWebviewHistoryLength",
"signInToControlPlane",
"openDialogMessage",
];

View file

@ -23,4 +23,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
];
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
signInToControlPlane: [undefined, void];
openDialogMessage: ["account", void];
};

View file

@ -191,6 +191,10 @@ class FileSystemIde implements IDE {
return Promise.resolve();
}
openUrl(url: string): Promise<void> {
return Promise.resolve();
}
runCommand(command: string): Promise<void> {
return Promise.resolve();
}

View file

@ -163,6 +163,10 @@ export class MessageIde implements IDE {
await this.request("openFile", { path });
}
async openUrl(url: string): Promise<void> {
await this.request("openUrl", url);
}
async runCommand(command: string): Promise<void> {
await this.request("runCommand", { command });
}

View file

@ -1,7 +1,7 @@
import * as fs from "fs";
import * as os from "os";
import { pathToFileURL } from "url";
import * as path from "path";
import * as JSONC from "comment-json";
import dotenv from "dotenv";
@ -41,6 +41,9 @@ export function getGlobalContinueIgnorePath(): string {
return continueIgnorePath;
}
/*
Deprecated, replace with getContinueGlobalUri where possible
*/
export function getContinueGlobalPath(): string {
// This is ~/.continue on mac/linux
const continuePath = CONTINUE_GLOBAL_DIR;
@ -50,6 +53,10 @@ export function getContinueGlobalPath(): string {
return continuePath;
}
export function getContinueGlobalUri(): string {
return pathToFileURL(CONTINUE_GLOBAL_DIR).href;
}
export function getSessionsFolderPath(): string {
const sessionsPath = path.join(getContinueGlobalPath(), "sessions");
if (!fs.existsSync(sessionsPath)) {
@ -94,6 +101,10 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
return p;
}
export function getConfigJsonUri(): string {
return getContinueGlobalUri() + "/config.json";
}
export function getConfigTsPath(): string {
const p = path.join(getContinueGlobalPath(), "config.ts");
if (!fs.existsSync(p)) {

View file

@ -192,9 +192,6 @@ class ContinueBrowser(val project: Project, url: String) {
}
"reloadWindow" -> {}
"openConfigJson" -> {
ide?.setFileOpen(getConfigJsonPath())
}
"readRangeInFile" -> {
val data = data.asJsonObject

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.231",
"version": "0.9.232",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.231",
"version": "0.9.232",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -219,9 +219,10 @@
"group": "Continue"
},
{
"command": "continue.openConfigJson",
"command": "continue.openConfig",
"category": "Continue",
"title": "Open config.json",
"title": "Open Continue Config",
"icon": "$(gear)",
"group": "Continue"
},
{
@ -250,12 +251,25 @@
"icon": "$(history)",
"group": "Continue"
},
{
"command": "continue.viewLogs",
"category": "Continue",
"title": "View History",
"group": "Continue"
},
{
"command": "continue.navigateTo",
"category": "Continue",
"title": "Navigate to a path",
"group": "Continue"
},
{
"command": "continue.openMorePage",
"category": "Continue",
"title": "More",
"icon": "$(ellipsis)",
"group": "Continue"
},
{
"command": "continue.writeCommentsForCode",
"category": "Continue",
@ -315,6 +329,20 @@
"category": "Continue",
"title": "Focus Continue Chat",
"group": "Continue"
},
{
"command": "continue.signInToControlPlane",
"title": "Sign In",
"category": "Continue",
"group": "Continue",
"icon": "$(account)"
},
{
"command": "continue.openAccountDialog",
"title": "Account",
"category": "Continue",
"group": "Continue",
"icon": "$(account)"
}
],
"keybindings": [
@ -492,6 +520,26 @@
"command": "continue.toggleFullScreen",
"group": "navigation@3",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.openConfig",
"group": "navigation@4",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.signInToControlPlane",
"group": "navigation@5",
"when": "(view == continue.continueGUIView) && config.continue.enableContinueForTeams && !continue.isSignedInToControlPlane"
},
{
"command": "continue.openAccountDialog",
"group": "navigation@5",
"when": "(view == continue.continueGUIView) && config.continue.enableContinueForTeams && continue.isSignedInToControlPlane"
},
{
"command": "continue.openMorePage",
"group": "navigation@6",
"when": "view == continue.continueGUIView"
}
],
"editor/title": [

View file

@ -485,6 +485,11 @@ class VsCodeIde implements IDE {
return "";
}
}
async openUrl(url: string): Promise<void> {
await vscode.env.openExternal(vscode.Uri.parse(url));
}
async showDiff(
filepath: string,
newContents: string,

View file

@ -580,10 +580,6 @@ const getCommandsMap: (
vscode.commands.executeCommand("continue.continueGUIView.focus");
sidebar.webviewProtocol?.request("addModel", undefined);
},
"continue.openSettingsUI": () => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
sidebar.webviewProtocol?.request("openSettings", undefined);
},
"continue.sendMainUserInput": (text: string) => {
sidebar.webviewProtocol?.request("userInput", {
input: text,
@ -683,8 +679,10 @@ const getCommandsMap: (
vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow");
},
"continue.openConfigJson": () => {
ide.openFile(getConfigJsonPath());
"continue.openConfig": () => {
core.invoke("config/openProfile", {
profileId: undefined,
});
},
"continue.selectFilesAsContext": async (
firstUri: vscode.Uri,
@ -857,7 +855,7 @@ const getCommandsMap: (
vscode.commands.executeCommand("continue.toggleFullScreen");
} else if (selectedOption === "$(question) Open help center") {
focusGUI();
vscode.commands.executeCommand("continue.navigateTo", "/more");
vscode.commands.executeCommand("continue.navigateTo", "/more", true);
}
quickPick.dispose();
});
@ -877,10 +875,19 @@ const getCommandsMap: (
client.sendFeedback(feedback, lastLines);
}
},
"continue.navigateTo": (path: string) => {
sidebar.webviewProtocol?.request("navigateTo", { path });
"continue.openMorePage": () => {
vscode.commands.executeCommand("continue.navigateTo", "/more", true);
},
"continue.navigateTo": (path: string, toggle: boolean) => {
sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
focusGUI();
},
"continue.signInToControlPlane": () => {
sidebar.webviewProtocol?.request("signInToControlPlane", undefined);
},
"continue.openAccountDialog": () => {
sidebar.webviewProtocol?.request("openDialogMessage", "account");
},
};
};

View file

@ -321,9 +321,13 @@ export class VsCodeExtension {
// When GitHub sign-in status changes, reload config
vscode.authentication.onDidChangeSessions(async (e) => {
if (e.provider.id === "github") {
this.configHandler.reloadConfig();
} else if (e.provider.id === controlPlaneEnv.AUTH_TYPE) {
if (e.provider.id === controlPlaneEnv.AUTH_TYPE) {
vscode.commands.executeCommand(
"setContext",
"continue.isSignedInToControlPlane",
true,
);
const sessionInfo = await getControlPlaneSessionInfo(true);
this.webviewProtocolPromise.then(async (webviewProtocol) => {
void webviewProtocol.request("didChangeControlPlaneSessionInfo", {
@ -336,6 +340,16 @@ export class VsCodeExtension {
void this.core.invoke("didChangeControlPlaneSessionInfo", {
sessionInfo,
});
} else {
vscode.commands.executeCommand(
"setContext",
"continue.isSignedInToControlPlane",
false,
);
if (e.provider.id === "github") {
this.configHandler.reloadConfig();
}
}
});

View file

@ -19,7 +19,6 @@ import {
} from "core/protocol/passThrough";
import { getBasename } from "core/util";
import { InProcessMessenger, Message } from "core/util/messenger";
import { getConfigJsonPath } from "core/util/paths";
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
@ -108,10 +107,6 @@ export class VsCodeMessenger {
);
});
this.onWebview("openConfigJson", (msg) => {
this.ide.openFile(getConfigJsonPath());
});
this.onWebview("readRangeInFile", async (msg) => {
return await vscode.workspace
.openTextDocument(msg.data.filepath)

View file

@ -35,7 +35,7 @@ export class ConfigPyCodeLensProvider implements vscode.CodeLensProvider {
codeLenses.push(
new vscode.CodeLens(range, {
title: "✏️ Edit in UI",
command: "continue.openSettingsUI",
command: "continue.openConfigUI", // command likely doesn't exist anymore, check
}),
);
}

View file

@ -132,7 +132,9 @@ export function registerAllCodeLensProviders(
context.subscriptions.push(verticalPerLineCodeLensProvider);
context.subscriptions.push(suggestionsCodeLensDisposable);
context.subscriptions.push(diffsCodeLensDisposable);
context.subscriptions.push(configPyCodeLensDisposable);
// was opening config UI from config.json. Not currently applicable.
// context.subscriptions.push(configPyCodeLensDisposable);
return { verticalDiffCodeLens };
}

View file

@ -0,0 +1,155 @@
import { Listbox, Transition } from "@headlessui/react";
import { ChevronUpDownIcon } from "@heroicons/react/24/outline";
import { Fragment, useContext } from "react";
import styled from "styled-components";
import {
Button,
SecondaryButton,
vscInputBackground,
vscInputBorder,
vscListActiveBackground,
vscListActiveForeground,
} from ".";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAuth } from "../context/Auth";
import { setSelectedProfileId } from "../redux/slices/stateSlice";
import { useDispatch } from "react-redux";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import { NewSessionButton } from "./mainInput/NewSessionButton";
const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>`
background-color: ${({ selected }) =>
selected ? vscListActiveBackground : vscInputBackground};
cursor: pointer;
padding: 6px 8px;
&:hover {
background-color: ${vscListActiveBackground};
color: ${vscListActiveForeground};
}
`;
function AccountDialog() {
const ideMessenger = useContext(IdeMessengerContext);
const {
session,
logout,
login,
profiles,
selectedProfile,
controlServerBetaEnabled,
} = useAuth();
// These shouldn't usually show but just to be safe
if (!session?.account?.id) {
return (
<div className="p-4">
<h1>Account</h1>
<p>Not signed in</p>
<Button onClick={login}>Login</Button>
</div>
);
}
if (!controlServerBetaEnabled) {
return (
<div className="p-4">
<h1>Account</h1>
<p>
Continue for teams is not enabled. You can enable it in your IDE
settings
</p>
<p>Using local config.</p>
<Button>Close</Button>
</div>
);
}
const dispatch = useDispatch();
const changeProfileId = (id: string) => {
ideMessenger.post("didChangeSelectedProfile", { id });
dispatch(setSelectedProfileId(id));
};
return (
<div className="p-4">
<h1>Account</h1>
<p className="">Select a workspace</p>
<Listbox value={"local"} onChange={changeProfileId}>
{({ open }) => (
<div className="relative">
<Listbox.Button
className="bg-vsc-background hover:bg-vsc-input-background text-vsc-foreground xs:w-[170px] relative m-0 flex w-[130px] cursor-pointer items-center justify-between rounded-md px-3 py-2 text-left sm:w-[220px]"
style={{
borderTop: `1px solid ${vscInputBorder}`,
borderLeft: `1px solid ${vscInputBorder}`,
borderRight: `1px solid ${vscInputBorder}`,
borderBottom: `1px solid ${vscInputBorder}`,
}}
>
<span className="lines lines-1">{selectedProfile?.title}</span>
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon className="h-5 w-5" aria-hidden="true" />
</div>
</Listbox.Button>
<Transition
as={Fragment}
show={open}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Listbox.Options className="bg-vsc-background max-h-80vh xs:w-[170px] absolute w-[130px] overflow-y-scroll rounded-sm p-0 sm:w-[220px]">
{profiles.map((option, idx) => (
<StyledListboxOption
key={idx}
selected={selectedProfile.id === option.id}
value={option.id}
className="w-full"
>
<div className="lines lines-1 relative flex h-5 items-center justify-between gap-3 pr-2">
{option.title}
</div>
</StyledListboxOption>
))}
{profiles.length === 0 ? (
<div className="px-4 py-2">
<i>No workspaces found</i>
</div>
) : null}
</Listbox.Options>
</Transition>
</div>
)}
</Listbox>
<p className="mt-6">
{session.account.label === ""
? "Signed in"
: `Signed in as ${session.account.label}`}
</p>
<NewSessionButton className="border border-solid" onClick={logout}>
Sign out
</NewSessionButton>
<div className="mt-3 flex flex-row">
<Button
className="basis-1/4"
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
}}
>
Done
</Button>
</div>
</div>
);
}
export default AccountDialog;

View file

@ -10,7 +10,9 @@ function AddModelButtonSubtext() {
This will update your{" "}
<span
className="cursor-pointer underline"
onClick={() => ideMessenger.post("openConfigJson", undefined)}
onClick={() =>
ideMessenger.post("config/openLocalConfigFile", undefined)
}
>
config file
</span>

View file

@ -1,92 +1,22 @@
import {
Cog6ToothIcon,
EllipsisHorizontalCircleIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import { RootState } from "../redux/store";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip";
import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar";
import ProfileSwitcher from "./ProfileSwitcher";
function Footer() {
const navigate = useNavigate();
const { pathname } = useLocation();
const defaultModel = useSelector(defaultModelSelector);
const ideMessenger = useContext(IdeMessengerContext);
const selectedProfileId = useSelector(
(store: RootState) => store.state.selectedProfileId,
);
const configError = useSelector(
(store: RootState) => store.state.configError,
);
function onClickMore() {
navigate(pathname === ROUTES.MORE ? "/" : ROUTES.MORE);
if (defaultModel?.provider === "free-trial") {
return (
<footer className="flex flex-col border-0 border-t border-solid border-t-zinc-700 px-2 py-2">
<FreeTrialProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={FREE_TRIAL_LIMIT_REQUESTS}
/>
</footer>
);
}
function onClickError() {
navigate(pathname === ROUTES.CONFIG_ERROR ? "/" : ROUTES.CONFIG_ERROR);
}
function onClickSettings() {
if (selectedProfileId === "local") {
ideMessenger.post("openConfigJson", undefined);
} else {
ideMessenger.post(
"openUrl",
`http://app.continue.dev/workspaces/${selectedProfileId}/chat`,
);
}
}
return (
<footer className="flex h-7 items-center justify-between overflow-hidden border-0 border-t border-solid border-t-zinc-700 p-2">
<div className="flex max-w-[40vw] gap-2">
<ProfileSwitcher />
{defaultModel?.provider === "free-trial" && (
<FreeTrialProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={FREE_TRIAL_LIMIT_REQUESTS}
/>
)}
</div>
<div className="flex gap-1">
{configError && (
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="Config error"
onClick={onClickError}
>
<ExclamationTriangleIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
)}
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="More"
onClick={onClickMore}
>
<EllipsisHorizontalCircleIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
onClick={onClickSettings}
text="Configure Continue"
>
<Cog6ToothIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
</div>
</footer>
);
return null;
}
export default Footer;

View file

@ -12,7 +12,7 @@ import {
setEditStatus,
startEditMode,
} from "../redux/slices/editModeState";
import { setShowDialog } from "../redux/slices/uiStateSlice";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import {
updateApplyState,
updateCurCheckpoint,
@ -25,6 +25,8 @@ import TextDialog from "./dialogs";
import Footer from "./Footer";
import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard";
import PostHogPageView from "./PosthogPageView";
import AccountDialog from "./AccountDialog";
import { AuthProvider } from "../context/Auth";
const LayoutTopDiv = styled(CustomScrollbarDiv)`
height: 100%;
@ -50,22 +52,6 @@ const GridDiv = styled.div`
overflow-x: visible;
`;
const ModelDropdownPortalDiv = styled.div`
background-color: ${vscInputBackground};
position: relative;
margin-left: 8px;
z-index: 200;
font-size: ${getFontSize()};
`;
const ProfileDropdownPortalDiv = styled.div`
background-color: ${vscInputBackground};
position: relative;
margin-left: 8px;
z-index: 200;
font-size: ${getFontSize() - 2};
`;
const Layout = () => {
const navigate = useNavigate();
const location = useLocation();
@ -109,6 +95,17 @@ const Layout = () => {
};
}, [timeline]);
useWebviewListener(
"openDialogMessage",
async (message) => {
if (message === "account") {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AccountDialog />));
}
},
[],
);
useWebviewListener(
"addModel",
async () => {
@ -117,10 +114,6 @@ const Layout = () => {
[navigate],
);
useWebviewListener("openSettings", async () => {
ideMessenger.post("openConfigJson", undefined);
});
useWebviewListener(
"viewHistory",
async () => {
@ -217,56 +210,55 @@ const Layout = () => {
}, [location]);
return (
<LastSessionProvider>
<LayoutTopDiv>
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
<AuthProvider>
<LastSessionProvider>
<LayoutTopDiv>
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
/>
<GridDiv className="">
<PostHogPageView />
<Outlet />
{hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && (
<div
className="z-50 cursor-pointer bg-red-600 p-4 text-center text-white"
role="alert"
onClick={() => navigate(ROUTES.CONFIG_ERROR)}
>
<strong className="font-bold">Error!</strong>{" "}
<span className="block sm:inline">
Could not load config.json
</span>
<div className="mt-2 underline">Learn More</div>
</div>
)}
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
<GridDiv className="">
<PostHogPageView />
<Outlet />
{hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && (
<div
className="z-50 cursor-pointer bg-red-600 p-4 text-center text-white"
role="alert"
onClick={() => navigate(ROUTES.CONFIG_ERROR)}
>
<strong className="font-bold">Error!</strong>{" "}
<span className="block sm:inline">
Could not load config.json
</span>
<div className="mt-2 underline">Learn More</div>
</div>
)}
<ModelDropdownPortalDiv id="model-select-top-div"></ModelDropdownPortalDiv>
<ProfileDropdownPortalDiv id="profile-select-top-div"></ProfileDropdownPortalDiv>
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
</LayoutTopDiv>
</LastSessionProvider>
</LayoutTopDiv>
</LastSessionProvider>
</AuthProvider>
);
};

View file

@ -43,9 +43,9 @@ function ConfirmationDialog(props: ConfirmationDialogProps) {
<SecondaryButton
style={{ color: lightGray }}
onClick={() => {
props.onCancel?.();
dispatch(setShowDialog(false));
dispatch(setDialogMessage(undefined));
props.onCancel?.();
}}
>
Cancel

View file

@ -37,7 +37,7 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
return (
<>
<div
className="flex cursor-default items-center gap-1"
className="flex flex-1 cursor-default select-none items-center justify-center gap-1"
data-tooltip-id="usage_progress_bar"
>
<ExclamationCircleIcon width="18px" height="18px" color="red" />
@ -54,21 +54,14 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
return (
<>
<div
className="flex cursor-pointer flex-col text-[10px] text-gray-400"
className="flex flex-1 cursor-pointer flex-row items-center gap-2 text-[10px] text-gray-400 sm:gap-3"
data-tooltip-id="usage_progress_bar"
onClick={onClick}
>
<div className="xs:flex mb-0 hidden justify-between">
<span>
Free trial <span className="hidden sm:inline">requests</span>
</span>
<span>
{completed} / {total}
</span>
</div>
<div className="my-1.5 flex h-1.5 w-[40vw] rounded-md border border-solid border-gray-400">
<span>
Free trial <span className="hidden sm:inline">requests</span>
</span>
<div className="flex h-1.5 flex-1 rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg transition-all duration-200 ease-in-out ${
completed / total > 0.75 ? "bg-amber-500" : "bg-stone-500"
@ -78,6 +71,9 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
}}
/>
</div>
<span>
{completed} / {total}
</span>
</div>
<ToolTip id="usage_progress_bar" place="top">
{`Click to use your own API key or local LLM (required after ${FREE_TRIAL_LIMIT_REQUESTS} inputs)`}

View file

@ -169,7 +169,7 @@ function ModelOption({
e.stopPropagation();
e.preventDefault();
ideMessenger.post("openConfigJson", undefined);
ideMessenger.post("config/openLocalConfigFile", undefined);
}
function handleOptionClick(e) {

184
gui/src/context/Auth.tsx Normal file
View file

@ -0,0 +1,184 @@
// AuthContext.tsx
import React, {
createContext,
useContext,
useState,
useEffect,
useMemo,
} from "react";
import { ControlPlaneSessionInfo } from "core/control-plane/client";
import { useDispatch, useSelector } from "react-redux";
import ConfirmationDialog from "../components/dialogs/ConfirmationDialog";
import { IdeMessengerContext } from "./IdeMessenger";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { RootState } from "../redux/store";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice";
import { useWebviewListener } from "../hooks/useWebviewListener";
import AccountDialog from "../components/AccountDialog";
interface AuthContextType {
session: ControlPlaneSessionInfo | undefined;
logout: () => void;
login: () => void;
selectedProfile: ProfileDescription | undefined;
profiles: ProfileDescription[];
controlServerBetaEnabled: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [session, setSession] = useState<ControlPlaneSessionInfo | undefined>(
undefined,
);
const [profiles, setProfiles] = useState<ProfileDescription[]>([]);
const selectedProfileId = useSelector(
(store: RootState) => store.state.selectedProfileId,
);
const selectedProfile = useMemo(() => {
return profiles.find((p) => p.id === selectedProfileId);
}, [profiles, selectedProfileId]);
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useDispatch();
const lastControlServerBetaEnabledStatus = useSelector(
(state: RootState) => state.misc.lastControlServerBetaEnabledStatus,
);
const login = () => {
ideMessenger
.request("getControlPlaneSessionInfo", { silent: false })
.then((result) => {
if (result.status === "error") {
return;
}
const session = result.content;
setSession(session);
// If this is the first time the user has logged in, explain how profiles work
if (!getLocalStorage("shownProfilesIntroduction")) {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
text={
"Welcome to Continue for teams! Using the toggle in the bottom right, you can switch between your local profile (defined by config.json) and team profiles (defined in the Continue for teams web app). Each profile defines a set of models, slash commands, context providers, and other settings to customize Continue."
}
hideCancelButton={true}
confirmText="Ok"
onConfirm={() => {}}
/>,
),
);
setLocalStorage("shownProfilesIntroduction", true);
}
});
};
const logout = () => {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
confirmText="Yes, log out"
text={"Are you sure you want to log out of Continue?"}
onConfirm={() => {
ideMessenger.post("logoutOfControlPlane", undefined);
}}
onCancel={() => {
dispatch(setDialogMessage(<AccountDialog />));
dispatch(setShowDialog(true));
}}
/>,
),
);
};
useWebviewListener("didChangeControlPlaneSessionInfo", async (data) => {
setSession(data.sessionInfo);
});
useWebviewListener("signInToControlPlane", async () => {
login();
});
useEffect(() => {
ideMessenger
.request("getControlPlaneSessionInfo", { silent: true })
.then(
(result) => result.status === "success" && setSession(result.content),
);
}, []);
const [controlServerBetaEnabled, setControlServerBetaEnabled] =
useState(false);
useEffect(() => {
ideMessenger.ide.getIdeSettings().then(({ enableControlServerBeta }) => {
setControlServerBetaEnabled(enableControlServerBeta);
dispatch(setLastControlServerBetaEnabledStatus(enableControlServerBeta));
const shouldShowPopup =
!lastControlServerBetaEnabledStatus && enableControlServerBeta;
if (shouldShowPopup) {
ideMessenger.ide.showToast("info", "Continue for Teams enabled");
}
});
}, []);
useWebviewListener(
"didChangeIdeSettings",
async (msg) => {
const { settings } = msg;
setControlServerBetaEnabled(settings.enableControlServerBeta);
dispatch(
setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta),
);
},
[],
);
useEffect(() => {
ideMessenger
.request("config/listProfiles", undefined)
.then(
(result) => result.status === "success" && setProfiles(result.content),
);
}, []);
useWebviewListener(
"didChangeAvailableProfiles",
async (data) => {
setProfiles(data.profiles);
},
[],
);
return (
<AuthContext.Provider
value={{
session,
logout,
login,
selectedProfile,
profiles,
controlServerBetaEnabled,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};

View file

@ -87,7 +87,9 @@ function AddModelForm({
};
ideMessenger.post("config/addModel", { model });
ideMessenger.post("openConfigJson", undefined);
ideMessenger.post("config/openProfile", {
profileId: "local",
});
dispatch(setDefaultModel({ title: model.title, force: true }));

View file

@ -1,83 +0,0 @@
import { ControlPlaneSessionInfo } from "core/control-plane/client";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import ConfirmationDialog from "../components/dialogs/ConfirmationDialog";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
export function useAuth(): {
session: ControlPlaneSessionInfo | undefined;
logout: () => void;
login: () => void;
} {
const [session, setSession] = useState<ControlPlaneSessionInfo | undefined>(
undefined,
);
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useDispatch();
useWebviewListener("didChangeControlPlaneSessionInfo", async (data) => {
setSession(data.sessionInfo);
});
useEffect(() => {
ideMessenger
.request("getControlPlaneSessionInfo", { silent: true })
.then(
(result) => result.status === "success" && setSession(result.content),
);
}, []);
const login = () => {
ideMessenger
.request("getControlPlaneSessionInfo", { silent: false })
.then((result) => {
if (result.status === "error") {
return;
}
const session = result.content;
setSession(session);
// If this is the first time the user has logged in, explain how profiles work
if (!getLocalStorage("shownProfilesIntroduction")) {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
text={
"Welcome to Continue for teams! Using the toggle in the bottom right, you can switch between your local profile (defined by config.json) and team profiles (defined in the Continue for teams web app). Each profile defines a set of models, slash commands, context providers, and other settings to customize Continue."
}
hideCancelButton={true}
confirmText="Ok"
onConfirm={() => {}}
/>,
),
);
setLocalStorage("shownProfilesIntroduction", true);
}
});
};
const logout = () => {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
confirmText="Yes, log out"
text={"Are you sure you want to log out of Continue?"}
onConfirm={() => {
ideMessenger.post("logoutOfControlPlane", undefined);
}}
/>,
),
);
};
return {
session,
logout,
login,
};
}

View file

@ -82,6 +82,7 @@ function useSetup(dispatch: Dispatch) {
sessionIdRef.current = sessionId;
}, [sessionId, history, ideMessenger, dispatch]);
// ON LOAD
useEffect(() => {
// Override persisted state
dispatch(setInactive());
@ -100,6 +101,18 @@ function useSetup(dispatch: Dispatch) {
dispatch(setVscMachineId(msg.vscMachineId));
// dispatch(setVscMediaUrl(msg.vscMediaUrl));
});
// Save theme colors to local storage for immediate loading in JetBrains
if (isJetBrains()) {
for (const colorVar of VSC_THEME_COLOR_VARS) {
if (document.body.style.getPropertyValue(colorVar)) {
localStorage.setItem(
colorVar,
document.body.style.getPropertyValue(colorVar),
);
}
}
}
}, []);
const { streamResponse } = useChatHandler(dispatch, ideMessenger);
@ -166,19 +179,7 @@ function useSetup(dispatch: Dispatch) {
[defaultModelTitle],
);
// Save theme colors to local storage for immediate loading in JetBrains
useEffect(() => {
if (isJetBrains()) {
for (const colorVar of VSC_THEME_COLOR_VARS) {
if (document.body.style.getPropertyValue(colorVar)) {
localStorage.setItem(
colorVar,
document.body.style.getPropertyValue(colorVar),
);
}
}
}
}, []);
}
export default useSetup;

View file

@ -211,7 +211,9 @@ function AddNewModel() {
className="mt-12"
disabled={false}
onClick={(e) => {
ideMessenger.post("openConfigJson", undefined);
ideMessenger.post("config/openProfile", {
profileId: "local",
});
}}
>
<h3 className="my-2 text-center">

View file

@ -98,7 +98,9 @@ function IndexingProgress() {
}
break;
case "disabled":
ideMessenger.post("openConfigJson", undefined);
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
break;
case "done":
ideMessenger.post("index/forceReIndex", undefined);

View file

@ -54,11 +54,11 @@ import { RootState } from "../../redux/store";
import {
getFontSize,
getMetaKeyLabel,
isJetBrains,
isMetaEquivalentKeyPressed,
} from "../../util";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import ConfigErrorIndicator from "./ConfigError";
import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks";
import { useFindWidget } from "../../components/find/FindWidget";
@ -419,37 +419,29 @@ export function Chat() {
pointerEvents: active ? "none" : "auto",
}}
>
{state.history.length > 0 ? (
<div className="xs:inline mt-2 hidden">
<NewSessionButton
onClick={() => {
saveSession();
}}
className="mr-auto"
>
<span className="xs:inline hidden">
New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"})
</span>
</NewSessionButton>
</div>
) : (
<>
{getLastSessionId() ? (
<div className="xs:inline mt-2 hidden">
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
<div className="xs:inline hidden">
{state.history.length === 0 && getLastSessionId() ? (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
}}
className="mr-auto flex items-center gap-2"
className="flex items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
Last Session
</NewSessionButton>
</div>
) : null}
</div>
<ConfigErrorIndicator />
</div>
{state.history.length === 0 && (
<>
{onboardingCard.show && (
<div className="mx-2 mt-10">
<OnboardingCard activeTab={onboardingCard.activeTab} />

View file

@ -0,0 +1,36 @@
import { useLocation, useNavigate } from "react-router-dom";
import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip";
import { useSelector } from "react-redux";
import { ROUTES } from "../../util/navigation";
import { RootState } from "../../redux/store";
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
const ConfigErrorIndicator = () => {
const configError = useSelector(
(store: RootState) => store.state.configError,
);
const navigate = useNavigate();
const { pathname } = useLocation();
function onClickError() {
navigate(pathname === ROUTES.CONFIG_ERROR ? "/" : ROUTES.CONFIG_ERROR);
}
if (!configError?.length) {
return null;
}
// TODO: add a tooltip
return (
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="Config error"
onClick={onClickError}
>
<ExclamationTriangleIcon className="h-4 w-4 text-red-600" />
</HeaderButtonWithToolTip>
);
};
export default ConfigErrorIndicator;