🚧 slash commands and context providers

This commit is contained in:
Nate Sesti 2023-10-29 15:41:05 -07:00
parent 1f1ef85827
commit daaecd1985
27 changed files with 726 additions and 447 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,22 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type ContextProviderDescription = ContextProviderDescription1;
export type Title = string;
export type DisplayTitle = string;
export type Description = string;
export type Dynamic = boolean;
export type RequiresQuery = boolean;
export interface ContextProviderDescription1 {
title: Title;
display_title: DisplayTitle;
description: Description;
dynamic: Dynamic;
requires_query: RequiresQuery;
[k: string]: unknown;
}

View file

@ -0,0 +1,16 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type SlashCommandDescription = SlashCommandDescription1;
export type Name = string;
export type Description = string;
export interface SlashCommandDescription1 {
name: Name;
description: Description;
[k: string]: unknown;
}

View file

@ -66,7 +66,11 @@ class IdeProtocolClient {
});
this.socket.on("message", (message) => {
const { messageType, data, messageId } = JSON.parse(message);
const {
message_type: messageType,
data,
message_id: messageId,
} = message;
this.handleMessage(messageType, data, messageId).catch((err) => {
console.log("Error handling message: ", err);
vscode.window

View file

@ -123,21 +123,6 @@ export function setupDebugPanel(
panel.webview.onDidReceiveMessage(async (data) => {
switch (data.type) {
case "onLoad": {
panel.webview.postMessage({
type: "onLoad",
vscMachineId: getUniqueId(),
apiUrl: getContinueServerUrl(),
workspacePaths: vscode.workspace.workspaceFolders?.map(
(folder) => folder.uri.fsPath
),
vscMediaUrl,
dataSwitchOn: vscode.workspace
.getConfiguration("continue")
.get<boolean>("dataSwitch"),
});
break;
}
case "websocketForwardingOpen": {
let url = data.url;
if (typeof sockets[url] === "undefined") {
@ -252,6 +237,13 @@ export function setupDebugPanel(
<script>localStorage.setItem("ide", "vscode")</script>
<script>window.windowId = "${windowId}"</script>
<script>window.serverUrl = "${getContinueServerUrl()}"</script>
<script>window.vscMachineId = "${getUniqueId()}"</script>
<script>window.vscMediaUrl = "${vscMediaUrl}"</script>
<script>window.workspacePaths = ${JSON.stringify(
vscode.workspace.workspaceFolders?.map(
(folder) => folder.uri.fsPath
) || []
)}</script>
</body>
</html>`;
}

View file

@ -2,31 +2,17 @@ import GUI from "./pages/gui";
import History from "./pages/history";
import Help from "./pages/help";
import Layout from "./components/Layout";
import { createContext, useEffect } from "react";
import { createContext } from "react";
import useContinueGUIProtocol from "./hooks/useWebsocket";
import ContinueGUIClientProtocol from "./hooks/ContinueGUIClientProtocol";
import { useDispatch } from "react-redux";
import {
setApiUrl,
setVscMachineId,
setSessionId,
setVscMediaUrl,
setDataSwitchOn,
setWorkspacePaths,
} from "./redux/slices/configSlice";
import {
setHighlightedCode,
setServerStatusMessage,
} from "./redux/slices/miscSlice";
import { postVscMessage } from "./vscode";
import { RouterProvider, createMemoryRouter } from "react-router-dom";
import ErrorPage from "./pages/error";
import SettingsPage from "./pages/settings";
import Models from "./pages/models";
import HelpPage from "./pages/help";
import ModelConfig from "./pages/modelconfig";
import { usePostHog } from "posthog-js/react";
import { processSessionUpdate } from "./redux/slices/sessionStateReducer";
import useSetup from "./hooks/useSetup";
const router = createMemoryRouter([
{
@ -76,65 +62,9 @@ export const GUIClientContext = createContext<
function App() {
const client = useContinueGUIProtocol(false);
const posthog = usePostHog();
const dispatch = useDispatch();
useEffect(() => {
if (!client) return;
client.onSessionUpdate((update) => {
console.log(update);
dispatch(processSessionUpdate(update));
});
}, [client]);
useEffect(() => {
const eventListener = (event: any) => {
switch (event.data.type) {
case "onLoad":
dispatch(setApiUrl(event.data.apiUrl));
dispatch(setVscMachineId(event.data.vscMachineId));
dispatch(setSessionId(event.data.sessionId));
dispatch(setVscMediaUrl(event.data.vscMediaUrl));
dispatch(setDataSwitchOn(event.data.dataSwitchOn));
if (event.data.uniqueId) {
posthog?.identify(event.data.vscMachineId);
}
dispatch(setWorkspacePaths(event.data.workspacePaths));
break;
case "highlightedCode":
dispatch(setHighlightedCode(event.data.rangeInFile));
break;
case "serverStatus":
dispatch(setServerStatusMessage(event.data.message));
break;
}
};
window.addEventListener("message", eventListener);
postVscMessage("onLoad", {});
return () => window.removeEventListener("message", eventListener);
}, []);
useEffect(() => {
if (document.body.style.getPropertyValue("--vscode-editor-foreground")) {
localStorage.setItem(
"--vscode-editor-foreground",
document.body.style.getPropertyValue("--vscode-editor-foreground")
);
}
if (document.body.style.getPropertyValue("--vscode-editor-background")) {
localStorage.setItem(
"--vscode-editor-background",
document.body.style.getPropertyValue("--vscode-editor-background")
);
}
if (document.body.style.getPropertyValue("--vscode-list-hoverBackground")) {
localStorage.setItem(
"--vscode-list-hoverBackground",
document.body.style.getPropertyValue("--vscode-list-hoverBackground")
);
}
}, []);
useSetup(client, dispatch);
return (
<GUIClientContext.Provider value={client}>

View file

@ -66,7 +66,6 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
}
runFromState(sessionState: SessionState) {
console.log(this.messenger);
this.messenger?.send("run_from_state", { state: sessionState });
}

93
gui/src/hooks/useSetup.ts Normal file
View file

@ -0,0 +1,93 @@
import { Dispatch } from "@reduxjs/toolkit";
import ContinueGUIClientProtocol from "./ContinueGUIClientProtocol";
import { useEffect } from "react";
import { processSessionUpdate } from "../redux/slices/sessionStateReducer";
import {
setHighlightedCode,
setServerStatusMessage,
} from "../redux/slices/miscSlice";
import { postVscMessage } from "../vscode";
import { useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import {
setContextProviders,
setSlashCommands,
} from "../redux/slices/serverStateReducer";
async function clientSetup(
client: ContinueGUIClientProtocol,
dispatch: Dispatch<any>,
serverUrl: string
) {
// Listen for updates to the session state
client.onSessionUpdate((update) => {
console.log(update);
dispatch(processSessionUpdate(update));
});
fetch(`${serverUrl}/slash_commands`).then(async (resp) => {
const sc = await resp.json();
console.log(sc);
dispatch(setSlashCommands(sc));
});
fetch(`${serverUrl}/context_providers`).then(async (resp) => {
const cp = await resp.json();
console.log(cp);
dispatch(setContextProviders(cp));
});
}
function useSetup(
client: ContinueGUIClientProtocol | undefined,
dispatch: Dispatch<any>
) {
const serverUrl = useSelector((store: RootStore) => store.config.apiUrl);
// Setup requiring client
useEffect(() => {
if (!client) return;
clientSetup(client, dispatch, serverUrl);
}, [client]);
// IDE event listeners
useEffect(() => {
const eventListener = (event: any) => {
switch (event.data.type) {
case "highlightedCode":
dispatch(setHighlightedCode(event.data.rangeInFile));
break;
case "serverStatus":
dispatch(setServerStatusMessage(event.data.message));
break;
}
};
window.addEventListener("message", eventListener);
postVscMessage("onLoad", {});
return () => window.removeEventListener("message", eventListener);
}, []);
// Save theme colors to local storage
useEffect(() => {
if (document.body.style.getPropertyValue("--vscode-editor-foreground")) {
localStorage.setItem(
"--vscode-editor-foreground",
document.body.style.getPropertyValue("--vscode-editor-foreground")
);
}
if (document.body.style.getPropertyValue("--vscode-editor-background")) {
localStorage.setItem(
"--vscode-editor-background",
document.body.style.getPropertyValue("--vscode-editor-background")
);
}
if (document.body.style.getPropertyValue("--vscode-list-hoverBackground")) {
localStorage.setItem(
"--vscode-list-hoverBackground",
document.body.style.getPropertyValue("--vscode-list-hoverBackground")
);
}
}, []);
}
export default useSetup;

View file

@ -1,27 +1,15 @@
import React, { useEffect, useState } from "react";
import { RootStore } from "../redux/store";
import { useSelector } from "react-redux";
import ContinueGUIClientProtocol from "./ContinueGUIClientProtocol";
import { postVscMessage } from "../vscode";
function useContinueGUIProtocol(useVscodeMessagePassing: boolean = true) {
// if (localStorage.getItem("ide") === "jetbrains") {
// useVscodeMessagePassing = false;
// }
const serverHttpUrl = useSelector((state: RootStore) => state.config.apiUrl);
const [client, setClient] = useState<ContinueGUIClientProtocol | undefined>(
undefined
);
useEffect(() => {
if (!serverHttpUrl) {
if (useVscodeMessagePassing) {
postVscMessage("onLoad", {});
}
}
}, [serverHttpUrl]);
useEffect(() => {
const serverUrl = (window as any).serverUrl;

View file

@ -1,11 +1,17 @@
import { createSlice } from "@reduxjs/toolkit";
import { RootStore } from "../store";
const windowAny: any = window;
export const configSlice = createSlice({
name: "config",
initialState: {
apiUrl: "http://localhost:8000",
vscMediaUrl: localStorage.getItem("vscMediaUrl") || undefined,
apiUrl: windowAny.serverUrl || "http://localhost:8000",
vscMediaUrl:
windowAny.vscMediaUrl || localStorage.getItem("vscMediaUrl") || undefined,
workspacePaths: windowAny.workspacePaths || [],
vscMachineId: windowAny.vscMachineId || undefined,
windowId: windowAny.windowId || undefined,
} as RootStore["config"],
reducers: {
setWorkspacePaths: (

View file

@ -102,10 +102,29 @@ export const serverStateSlice = createSlice({
initialState,
reducers: {
temporarilyPushToUserInputQueue: (state, action) => {
state.userInputQueue = [...state.userInputQueue, action.payload];
return {
...state,
userInputQueue: [...state.userInputQueue, action.payload],
};
},
setSlashCommands: (state, action) => {
return {
...state,
slashCommands: action.payload,
};
},
setContextProviders: (state, action) => {
return {
...state,
contextProviders: action.payload,
};
},
},
});
export const { temporarilyPushToUserInputQueue } = serverStateSlice.actions;
export const {
temporarilyPushToUserInputQueue,
setContextProviders,
setSlashCommands,
} = serverStateSlice.actions;
export default serverStateSlice.reducer;

View file

@ -41,7 +41,7 @@ export const sessionStateSlice = createSlice({
...state.history[payload.index],
};
if (payload.update.name) {
(step.name = step.name ?? "") + payload.update.name;
step.name = (step.name ?? "") + payload.update.name;
}
if (payload.update.description) {
step.description =

View file

@ -13,6 +13,8 @@ import {
SlashCommand,
} from "../schema/ContinueConfig";
import { ContextItem } from "../schema/ContextItem";
import { ContextProviderDescription } from "../schema/ContextProviderDescription";
import { SlashCommandDescription } from "../schema/SlashCommandDescription";
export interface ChatMessage {
role: "system" | "user" | "assistant";
@ -24,10 +26,8 @@ export interface RootStore {
workspacePaths: string[] | undefined;
apiUrl: string;
vscMachineId: string | undefined;
sessionId: string | undefined;
sessionStarted: number | undefined;
vscMediaUrl: string | undefined;
dataSwitchOn: boolean | undefined;
windowId: string | undefined;
};
misc: {
highlightedCode: RangeInFile | undefined;
@ -46,10 +46,10 @@ export interface RootStore {
serverState: {
meilisearchUrl: string | undefined;
userInputQueue: string[];
slashCommands: SlashCommand[];
slashCommands: SlashCommandDescription[];
selectedContextItems: ContextItem[];
config: ContinueConfig;
contextProviders: ContextProvider[];
contextProviders: ContextProviderDescription[];
savedContextGroups: any[]; // TODO: Context groups
};
}

View file

@ -0,0 +1,22 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type ContextProviderDescription = ContextProviderDescription1;
export type Title = string;
export type DisplayTitle = string;
export type Description = string;
export type Dynamic = boolean;
export type RequiresQuery = boolean;
export interface ContextProviderDescription1 {
title: Title;
display_title: DisplayTitle;
description: Description;
dynamic: Dynamic;
requires_query: RequiresQuery;
[k: string]: unknown;
}

View file

@ -0,0 +1,16 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type SlashCommandDescription = SlashCommandDescription1;
export type Name = string;
export type Description = string;
export interface SlashCommandDescription1 {
name: Name;
description: Description;
[k: string]: unknown;
}

View file

@ -0,0 +1,39 @@
{
"title": "ContextProviderDescription",
"$ref": "#/definitions/continuedev__core__main__ContextProviderDescription",
"definitions": {
"continuedev__core__main__ContextProviderDescription": {
"title": "ContextProviderDescription",
"type": "object",
"properties": {
"title": {
"title": "Title",
"type": "string"
},
"display_title": {
"title": "Display Title",
"type": "string"
},
"description": {
"title": "Description",
"type": "string"
},
"dynamic": {
"title": "Dynamic",
"type": "boolean"
},
"requires_query": {
"title": "Requires Query",
"type": "boolean"
}
},
"required": [
"title",
"display_title",
"description",
"dynamic",
"requires_query"
]
}
}
}

View file

@ -0,0 +1,24 @@
{
"title": "SlashCommandDescription",
"$ref": "#/definitions/continuedev__core__main__SlashCommandDescription",
"definitions": {
"continuedev__core__main__SlashCommandDescription": {
"title": "SlashCommandDescription",
"type": "object",
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"description": {
"title": "Description",
"type": "string"
}
},
"required": [
"name",
"description"
]
}
}
}

View file

@ -270,7 +270,7 @@ class Autopilot:
yield SessionUpdate(
index=index, update=DeltaStep(observations=[update])
)
elif isinstance(update, UpdateStep):
elif isinstance(update, DeltaStep) or isinstance(update, SetStep):
yield SessionUpdate(index=index, update=update)
else:
logger.warning(f"Unknown type yielded from Step: {update}")

View file

@ -5,7 +5,7 @@ from pydantic import BaseModel, Field, validator
from ..libs.llm.openai_free_trial import OpenAIFreeTrial
from .context import ContextProvider
from .main import Policy, Step
from .main import ContextProviderDescription, Policy, SlashCommandDescription, Step
from .models import Models
@ -23,12 +23,24 @@ class SlashCommand(BaseModel):
"step": self.step.__name__,
}
def slash_command_description(self) -> SlashCommandDescription:
return SlashCommandDescription(
name=self.name,
description=self.description,
)
class CustomCommand(BaseModel):
name: str
prompt: str
description: str
def slash_command_description(self) -> SlashCommandDescription:
return SlashCommandDescription(
name=self.name,
description=self.description,
)
class ContinueConfig(BaseModel):
"""
@ -130,3 +142,44 @@ class ContinueConfig(BaseModel):
return ContinueConfig.load_default(retry=False)
else:
raise e
def get_slash_command_descriptions(self) -> List[SlashCommandDescription]:
custom_commands = (
list(
map(
lambda x: x.slash_command_description(),
self.custom_commands,
)
)
or []
)
slash_commands = (
list(
map(
lambda x: x.slash_command_description(),
self.slash_commands,
)
)
or []
)
cmds = custom_commands + slash_commands
cmds.sort(key=lambda x: x.name == "edit", reverse=True)
return cmds
def get_context_provider_descriptions(self) -> List[ContextProviderDescription]:
"""
Returns a list of ContextProviderDescriptions
"""
return [
provider.get_description()
for provider in self.context_providers
if provider.title != "code" # Code isn't used with '@'
] + [
ContextProviderDescription(
title="file",
display_title="Files",
description="Reference files in the current workspace",
dynamic=False,
requires_query=False,
)
]

View file

@ -78,6 +78,15 @@ class ContextProvider(BaseModel):
[], description="List of selected items in the ContextProvider"
)
def get_description(self) -> ContextProviderDescription:
return ContextProviderDescription(
title=self.title,
display_title=self.display_title,
description=self.description,
dynamic=self.dynamic,
requires_query=self.requires_query,
)
def dict(self, *args, **kwargs):
original_dict = super().dict(*args, **kwargs)
original_dict.pop("sdk", None)

View file

@ -118,6 +118,10 @@ class SetStep(BaseModel):
observations: Optional[List[Observation]] = None
logs: Optional[List[str]] = None
def dict(self, *args, **kwargs):
kwargs["exclude_none"] = True
return super().dict(*args, **kwargs)
class DeltaStep(BaseModel):
name: Optional[str] = None
@ -315,7 +319,7 @@ class Policy(ContinueBaseModel):
class Step(ContinueBaseModel):
name: str = None
hide: bool = False
description: Union[str, None] = None
description: str = ""
class_name: str = "Step"

View file

@ -4,7 +4,14 @@ from pydantic import schema_json_of
from ..core.config import ContinueConfig
from ..core.context import ContextItem, ContextItemId
from ..core.main import SessionInfo, SessionState, SessionUpdate, ContinueError
from ..core.main import (
SessionInfo,
SessionState,
SessionUpdate,
ContinueError,
SlashCommandDescription,
ContextProviderDescription,
)
from ..core.models import Models
from ..libs.llm.base import LLM
from .filesystem import FileEdit, RangeInFile
@ -16,7 +23,14 @@ MODELS_TO_GENERATE = (
[Position, Range, Traceback, TracebackFrame]
+ [RangeInFile, FileEdit]
+ [FileEditWithFullContents]
+ [SessionInfo, SessionState, SessionUpdate, ContinueError]
+ [
SessionInfo,
SessionState,
SessionUpdate,
ContinueError,
SlashCommandDescription,
ContextProviderDescription,
]
+ [ContinueConfig]
+ [ContextItem, ContextItemId]
+ [Models]

View file

@ -8,12 +8,13 @@ from ..steps.chat import SimpleChatStep
from ..steps.custom_command import CustomCommandStep
from ..steps.main import EditHighlightedCodeStep
from ..steps.steps_on_startup import StepsOnStartupStep
from ..steps.cmd import GenerateShellCommandStep
# When importing with importlib from config.py, the classes do not pass isinstance checks.
# Mapping them here is a workaround.
# Original description of the problem: https://github.com/continuedev/continue/pull/581#issuecomment-1778138841
REPLACEMENT_SLASH_COMMAND_STEPS = [AnswerQuestionChroma]
REPLACEMENT_SLASH_COMMAND_STEPS = [AnswerQuestionChroma, GenerateShellCommandStep]
def parse_slash_command(inp: str, config: ContinueConfig) -> Union[None, Step]:

View file

@ -29,12 +29,16 @@ async def disconnect(sid):
@sio.event
async def message(sid, data):
try:
if isinstance(data, str):
data = json.loads(data)
message = WebsocketsMessage.parse_obj(data)
except json.JSONDecodeError:
logger.critical(f"Error decoding json: {data}")
return
except ValidationError as e:
logger.critical(f"Error validating json: {e}")
tb = "\n".join(traceback.format_exception(e, e, e.__traceback__))
logger.critical(f"Error validating json: {tb}")
return
try:

View file

@ -39,12 +39,16 @@ async def disconnect(sid):
@sio.event
async def message(sid, data):
try:
if isinstance(data, str):
data = json.loads(data)
message = WebsocketsMessage.parse_obj(data)
except json.JSONDecodeError:
logger.critical(f"Error decoding json: {data}")
return
except ValidationError as e:
logger.critical(f"Error validating json: {e}")
tb = "\n".join(traceback.format_exception(e, e, e.__traceback__))
logger.critical(f"Error validating json: {tb}")
return
try:

View file

@ -2,7 +2,10 @@ import argparse
import asyncio
import atexit
from contextlib import asynccontextmanager
from typing import Optional
from typing import List, Optional
from ..core.main import ContextProviderDescription, SlashCommandDescription
from ..core.config import ContinueConfig, SlashCommand
import uvicorn
from fastapi import FastAPI
@ -50,6 +53,23 @@ app.add_middleware(
allow_headers=["*"],
)
# region: Base endpoints
root_config = ContinueConfig.load_default()
@app.get("/slash_commands")
def get_slash_commands() -> List[SlashCommandDescription]:
return root_config.get_slash_command_descriptions()
@app.get("/context_providers")
def get_context_providers() -> List[ContextProviderDescription]:
return root_config.get_context_provider_descriptions()
# endregion
def run_server(
port: int = 65432, host: str = "127.0.0.1", meilisearch_url: Optional[str] = None