notebook -> gui

This commit is contained in:
Nate Sesti 2023-06-02 01:05:59 -04:00
parent 769bf31da0
commit ad86eff7b0
29 changed files with 129 additions and 179 deletions

View file

@ -1,26 +0,0 @@
from typing import List
import pluggy
from .step import hookspecs
from .step.libs import hello_world
builtin_libs = [hello_world]
def get_plugin_manager(use_plugins: List[str]) -> pluggy.PluginManager:
pm = pluggy.PluginManager("continue.step")
pm.add_hookspecs(hookspecs)
pm.load_setuptools_entrypoints("continue.step")
# Only use plugins that are specified in the config file
for plugin, name in pm.list_name_plugin():
if name not in use_plugins:
pm.set_blocked(plugin)
# Print warning if plugin not found
for name in use_plugins:
if not pm.has_plugin(name):
print(f"Plugin {name} not found.")
for lib in builtin_libs:
pm.register(lib)
return pm

View file

@ -1,21 +0,0 @@
def load_validator_plugin(config: ValidatorPluginConfig) -> Validator:
if config.name == "continue.tb_validator":
return PythonTracebackValidator(config.cmd, config.cwd)
elif config.name == "continue.pytest_validator":
return PytestValidator(cwd=config.cwd)
else:
raise KeyError("Unknown validator plugin name")
def load_llm_plugin(config: LLMPluginConfig) -> LLM:
if config.provider == "openai":
return OpenAI(api_key=config.api_key)
else:
raise KeyError("Unknown LLM provider: " + config.provider)
def load_policy_plugin(config: PolicyPluginConfig) -> Policy:
if config.name == "continue.random_policy":
return RandomPolicy()
elif config.name == "continue.dfs_policy":
return DFSPolicy()
else:
raise KeyError("Unknown policy plugin name")

View file

@ -1,4 +0,0 @@
import pluggy
hookimpl = pluggy.HookimplMarker("continue.policy")
"""Marker to be imported and used in plugins (and for own implementations)"""

View file

@ -1,10 +0,0 @@
from typing import List, Tuple
import pluggy
from ...libs.policy import Policy, Step
hookspec = pluggy.HookspecMarker("continue.policy")
class PolicyPlugin(Policy):
@hookspec
def next(self) -> Step:
"""Get the next step to run"""

View file

@ -1,20 +0,0 @@
from plugins import policy
from ....core.main import History, Step
class AlternatingPolicy:
"""A Policy that alternates between two steps."""
def __init__(self, first: Step, second: Step):
self.first = first
self.second = second
self.last_was_first = False
@policy.hookimpl
def next(self, history: History) -> Step:
if self.last_was_first:
self.last_was_first = False
return self.second
else:
self.last_was_first = True
return self.first

View file

@ -1,4 +0,0 @@
import pluggy
hookimpl = pluggy.HookimplMarker("continue.step")
"""Marker to be imported and used in plugins (and for own implementations)"""

View file

@ -1,15 +0,0 @@
from typing import Coroutine
import pluggy
from ...core.main import Step
from ...core.observation import Observation
from ...core.sdk import ContinueSDK
hookspec = pluggy.HookspecMarker("continue.step")
# Perhaps Actions should be generic about what their inputs must be.
class StepPlugin(Step):
@hookspec
async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:
"""Run"""

View file

@ -1,9 +0,0 @@
from ....plugins import step
from ....libs.steps import ContinueSDK
class HelloWorldStep:
"""A Step that prints "Hello World!"."""
@step.hookimpl
def run(sdk: ContinueSDK):
print("Hello World!")

View file

@ -5,13 +5,13 @@ from pydantic import BaseModel
from uvicorn.main import Server
from .session_manager import SessionManager, session_manager, Session
from .notebook_protocol import AbstractNotebookProtocolServer
from .gui_protocol import AbstractGUIProtocolServer
from ..libs.util.queue import AsyncSubscriptionQueue
import asyncio
import nest_asyncio
nest_asyncio.apply()
router = APIRouter(prefix="/notebook", tags=["notebook"])
router = APIRouter(prefix="/gui", tags=["gui"])
# Graceful shutdown by closing websockets
original_handler = Server.handle_exit
@ -43,7 +43,7 @@ T = TypeVar("T", bound=BaseModel)
# You should probably abstract away the websocket stuff into a separate class
class NotebookProtocolServer(AbstractNotebookProtocolServer):
class GUIProtocolServer(AbstractGUIProtocolServer):
websocket: WebSocket
session: Session
sub_queue: AsyncSubscriptionQueue = AsyncSubscriptionQueue()
@ -107,7 +107,7 @@ async def websocket_endpoint(websocket: WebSocket, session: Session = Depends(we
print("Session started")
session_manager.register_websocket(session.session_id, websocket)
protocol = NotebookProtocolServer(session)
protocol = GUIProtocolServer(session)
protocol.websocket = websocket
# Update any history that may have happened before connection

View file

@ -2,7 +2,7 @@ from typing import Any
from abc import ABC, abstractmethod
class AbstractNotebookProtocolServer(ABC):
class AbstractGUIProtocolServer(ABC):
@abstractmethod
async def handle_json(self, data: Any):
"""Handle a json message"""

View file

@ -12,7 +12,7 @@ from ..models.filesystem import FileSystem, RangeInFile, EditDiff, RealFileSyste
from ..models.main import Traceback
from ..models.filesystem_edit import AddDirectory, AddFile, DeleteDirectory, DeleteFile, FileSystemEdit, FileEdit, FileEditWithFullContents, RenameDirectory, RenameFile, SequentialFileSystemEdit
from pydantic import BaseModel
from .notebook import SessionManager, session_manager
from .gui import SessionManager, session_manager
from .ide_protocol import AbstractIdeProtocolServer
@ -106,8 +106,8 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
return resp_model.parse_obj(resp)
async def handle_json(self, message_type: str, data: Any):
if message_type == "openNotebook":
await self.openNotebook()
if message_type == "openGUI":
await self.openGUI()
elif message_type == "setFileOpen":
await self.setFileOpen(data["filepath"], data["open"])
elif message_type == "fileEdits":
@ -131,9 +131,9 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
"open": open
})
async def openNotebook(self):
async def openGUI(self):
session_id = self.session_manager.new_session(self)
await self._send_json("openNotebook", {
await self._send_json("openGUI", {
"sessionId": session_id
})
@ -148,7 +148,7 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
self._receive_json(ShowSuggestionResponse)
for i in range(len(suggestions))
]) # WORKING ON THIS FLOW HERE. Fine now to just await for response, instead of doing something fancy with a "waiting" state on the autopilot.
# Just need connect the suggestionId to the IDE (and the notebook)
# Just need connect the suggestionId to the IDE (and the gui)
return any([r.accepted for r in responses])
# ------------------------------- #
@ -168,11 +168,11 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
# Access to Autopilot (so SessionManager)
pass
def onCloseNotebook(self, session_id: str):
def onCloseGUI(self, session_id: str):
# Accesss to SessionManager
pass
def onOpenNotebookRequest(self):
def onOpenGUIRequest(self):
pass
def onFileEdits(self, edits: List[FileEditWithFullContents]):

View file

@ -24,8 +24,8 @@ class AbstractIdeProtocolServer(ABC):
"""Set whether a file is open"""
@abstractmethod
async def openNotebook(self):
"""Open a notebook"""
async def openGUI(self):
"""Open a GUI"""
@abstractmethod
async def showSuggestionsAndWait(self, suggestions: List[FileEdit]) -> bool:
@ -44,12 +44,12 @@ class AbstractIdeProtocolServer(ABC):
"""Called when a file system update is received"""
@abstractmethod
def onCloseNotebook(self, session_id: str):
"""Called when a notebook is closed"""
def onCloseGUI(self, session_id: str):
"""Called when a GUI is closed"""
@abstractmethod
def onOpenNotebookRequest(self):
"""Called when a notebook is requested to be opened"""
def onOpenGUIRequest(self):
"""Called when a GUI is requested to be opened"""
@abstractmethod
async def getOpenFiles(self) -> List[str]:

View file

@ -2,14 +2,14 @@ import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .ide import router as ide_router
from .notebook import router as notebook_router
from .gui import router as gui_router
import uvicorn
import argparse
app = FastAPI()
app.include_router(ide_router)
app.include_router(notebook_router)
app.include_router(gui_router)
# Add CORS support
app.add_middleware(

View file

@ -1,8 +0,0 @@
# Autopilot
`Autopilot` contains the
- History
- LLM
- Policy
- IDE

View file

@ -0,0 +1,30 @@
# Autopilot
**TODO: Better explain in one sentence what this is and what its purpose is**
:::info
The **autopilot** is the main loop, completing steps and then deciding the next step and repeating
:::
## Details
The Autopilot class is the center of Continue. Every step is initiated from the Autopilot, which provides it with a ContinueSDK.
- Records history
- Allows reversal
- Injects SDK
- Has policy to decide what step to take next
- Accepts user input and acts on it
- Main event loop
- Contains main classes that are provided through the SDK, including LLM, History, IDE
---
- An autopilot takes user input from the React app
- You can see this happening in `server/gui.py`
- It basically queues user inputs, pops off the most recent, runs that as a "UserInputStep", uses its Policy to run other steps until the next step is None, and then pops off the next user input. When nothing left, just waits for more
- `Autopilot` contains the
- History
- LLM
- Policy
- IDE

View file

@ -3,11 +3,11 @@
The `GUI` enables you to guide steps and makes everything transparent, so you can review all steps that were automated, giving you the opportunity to undo and rerun any that ran incorrectly.
**From GUI to Core**
- Natural language instructions from the developer
- Hover / clicked on a step
- Other user input
**From Core to GUI**
- Updates to state (e.g. a new step)
**Q: do we call this the Continue GUI or Notebook?**
- Updates to state (e.g. a new step)

View file

@ -24,9 +24,9 @@ Get the workspace directory
Set whether a file is open
### openNotebook
### openGUI
Open a notebook
Open a gui
### showSuggestionsAndWait
@ -44,13 +44,13 @@ Called when a traceback is received
Called when a file system update is received
### onCloseNotebook
### onCloseGUI
Called when a notebook is closed
Called when a gui is closed
### onOpenNotebookRequest
### onOpenGUIRequest
Called when a notebook is requested to be opened
Called when a gui is requested to be opened
### getOpenFiles
@ -78,4 +78,4 @@ Apply a file edit
### saveFile
Save a file
Save a file

View file

@ -0,0 +1,37 @@
# How `Continue` works
![Continue Architecture Diagram](/img/continue-architecture.png)
## Overview
The `Continue` library consists of an [SDK](./concepts/sdk.md), a [GUI](./concepts/gui.md), and a [Core](./concepts/core.md) that brings everything together.
The [SDK](./concepts/sdk.md) gives you access to the tools (e.g. open a directory, edit a file, call a model, etc.) needed to define steps that integrate LLMs into your IDE.
The [GUI](./concepts/gui.md) lets you transparently review every automated step, providing the opportunity to undo and rerun any that ran incorrectly.
The [Core](./concepts/core.md) holds the main event loop, responsible for connecting IDE, SDK, and GUI and deciding which steps to take next.
## Details
**TODO: Refactor all of this and make it fit with language above**
- Continue connects any code editor (primarily VS Code right now) to a server (the Continue server) that can take actions in the editor in accordance with defined recipes at the request of a user through the GUI
- What this looks like:
- The Continue VS Code extension runs the ContinueIdeProtocol, launches the Continue Python server in the background, and opens the Continue GUI in a side-panel.
- The Continue server is the brain, communication center, and source of truth, interacting with VS Code through the ContinueIdeProtocol and with the GUI through the GUIProtocol.
- Communication between the extension and GUI happens through the Continue server.
- When you type a natural language command in the GUI, this is sent to the Continue server, where the `Autopilot` class takes action, potentially using the ContinueIdeProtocol to request actions be taken in the IDE, and then updates the GUI to display the new history.
- `core` directory contains major concepts
- This includes Autopilot, Policy, SDK (all in their own files so far)
- It also includes `main.py`, which contains History, HistoryNode, Step, and others
- You'll find `env.py` here too, which is a common place to load environment variables, which can then be imported from here
- `libs` contains misc. stuff
- `llm` for language model utilities
- `steps` for builtin Continue steps
- `util` for very misc. stuff
- `chroma` for chroma code that deals with codebase embeddings
- `models` contains all the Pydantic models and `generate_json_schema.py`, a script that converts them to JSONSchema .json files in `schema/json`
- `server` runs the servers that communicate with a) the React app (`gui.py`) and b) the IDE (`ide.py`)
- `ide_protocol.py` is just the abstract version of what is implemented in `ide.py`, and `main.py` runs both `gui.py` and `ide.py` as a single FastAPI server. This is the entry point to the Continue server, and acts as a bridge between IDE and React app
- We use OpenAPI/JSONSchema to define types so that it's really easy to bring them across language barriers. Use Pydantic types, then run `poetry run typegen` from the root of continuedev folder to generate JSONSchema json files in the `schema/json` folder. Then `npm run typegen` from the extension folder generates the types that are used within the extension.

View file

@ -4,7 +4,7 @@ import { Provider } from "react-redux";
import store from "./redux/store";
import WelcomeTab from "./tabs/welcome";
import ChatTab from "./tabs/chat";
import Notebook from "./tabs/notebook";
import GUI from "./tabs/gui";
function App() {
return (
@ -13,8 +13,8 @@ function App() {
<DebugPanel
tabs={[
{
element: <Notebook />,
title: "Notebook",
element: <GUI />,
title: "GUI",
},
// { element: <MainTab />, title: "Debug Panel" },
// { element: <WelcomeTab />, title: "Welcome" },

View file

@ -1,4 +1,4 @@
abstract class AbstractContinueNotebookClientProtocol {
abstract class AbstractContinueGUIClientProtocol {
abstract sendMainInput(input: string): void;
abstract reverseToIndex(index: number): void;
@ -10,4 +10,4 @@ abstract class AbstractContinueNotebookClientProtocol {
abstract onStateUpdate(state: any): void;
}
export default AbstractContinueNotebookClientProtocol;
export default AbstractContinueGUIClientProtocol;

View file

@ -1,9 +1,9 @@
import AbstractContinueNotebookClientProtocol from "./ContinueNotebookClientProtocol";
import AbstractContinueGUIClientProtocol from "./ContinueGUIClientProtocol";
// import { Messenger, WebsocketMessenger } from "../../../src/util/messenger";
import { Messenger, WebsocketMessenger } from "./messenger";
import { VscodeMessenger } from "./vscodeMessenger";
class ContinueNotebookClientProtocol extends AbstractContinueNotebookClientProtocol {
class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
messenger: Messenger;
// Server URL must contain the session ID param
serverUrlWithSessionId: string;
@ -46,4 +46,4 @@ class ContinueNotebookClientProtocol extends AbstractContinueNotebookClientProto
}
}
export default ContinueNotebookClientProtocol;
export default ContinueGUIClientProtocol;

View file

@ -1,15 +1,15 @@
import React, { useEffect, useState } from "react";
import { RootStore } from "../redux/store";
import { useSelector } from "react-redux";
import ContinueNotebookClientProtocol from "./useContinueNotebookProtocol";
import ContinueGUIClientProtocol from "./useContinueGUIProtocol";
import { postVscMessage } from "../vscode";
function useContinueNotebookProtocol(useVscodeMessagePassing: boolean = true) {
function useContinueGUIProtocol(useVscodeMessagePassing: boolean = true) {
const sessionId = useSelector((state: RootStore) => state.config.sessionId);
const serverHttpUrl = useSelector((state: RootStore) => state.config.apiUrl);
const [client, setClient] = useState<
ContinueNotebookClientProtocol | undefined
>(undefined);
const [client, setClient] = useState<ContinueGUIClientProtocol | undefined>(
undefined
);
useEffect(() => {
if (!sessionId || !serverHttpUrl) {
@ -22,12 +22,12 @@ function useContinueNotebookProtocol(useVscodeMessagePassing: boolean = true) {
const serverUrlWithSessionId =
serverHttpUrl.replace("http", "ws") +
"/notebook/ws?session_id=" +
"/gui/ws?session_id=" +
encodeURIComponent(sessionId);
console.log("Creating websocket", serverUrlWithSessionId);
console.log("Using vscode message passing", useVscodeMessagePassing);
const newClient = new ContinueNotebookClientProtocol(
const newClient = new ContinueGUIClientProtocol(
serverUrlWithSessionId,
useVscodeMessagePassing
);
@ -36,4 +36,4 @@ function useContinueNotebookProtocol(useVscodeMessagePassing: boolean = true) {
return client;
}
export default useContinueNotebookProtocol;
export default useContinueGUIProtocol;

View file

@ -14,9 +14,9 @@ import StepContainer from "../components/StepContainer";
import { useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import useContinueWebsocket from "../hooks/useWebsocket";
import useContinueNotebookProtocol from "../hooks/useWebsocket";
import useContinueGUIProtocol from "../hooks/useWebsocket";
let TopNotebookDiv = styled.div`
let TopGUIDiv = styled.div`
display: grid;
grid-template-columns: 1fr;
`;
@ -29,11 +29,11 @@ let UserInputQueueItem = styled.div`
text-align: center;
`;
interface NotebookProps {
interface GUIProps {
firstObservation?: any;
}
function Notebook(props: NotebookProps) {
function GUI(props: GUIProps) {
const [waitingForSteps, setWaitingForSteps] = useState(false);
const [userInputQueue, setUserInputQueue] = useState<string[]>([]);
const [history, setHistory] = useState<History | undefined>();
@ -156,7 +156,7 @@ function Notebook(props: NotebookProps) {
// } as any
// );
const client = useContinueNotebookProtocol();
const client = useContinueGUIProtocol();
useEffect(() => {
console.log("CLIENT ON STATE UPDATE: ", client, client?.onStateUpdate);
@ -207,7 +207,7 @@ function Notebook(props: NotebookProps) {
// const iterations = useSelector(selectIterations);
return (
<TopNotebookDiv>
<TopGUIDiv>
{typeof client === "undefined" && (
<>
<Loader></Loader>
@ -258,8 +258,8 @@ function Notebook(props: NotebookProps) {
}}
></MainTextInput>
<ContinueButton onClick={onMainTextInput}></ContinueButton>
</TopNotebookDiv>
</TopGUIDiv>
);
}
export default Notebook;
export default GUI;

View file

@ -59,10 +59,10 @@ export function activateExtension(
})
),
]).then(() => {
ideProtocolClient?.openNotebook();
ideProtocolClient?.openGUI();
});
} else {
ideProtocolClient.openNotebook().then(() => {
ideProtocolClient.openGUI().then(() => {
// openCapturedTerminal();
});
}

View file

@ -62,11 +62,11 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
"continue.acceptSuggestion": acceptSuggestionCommand,
"continue.rejectSuggestion": rejectSuggestionCommand,
"continue.openDebugPanel": () => {
ideProtocolClient.openNotebook();
ideProtocolClient.openGUI();
},
"continue.focusContinueInput": async () => {
if (!debugPanelWebview) {
await ideProtocolClient.openNotebook();
await ideProtocolClient.openGUI();
}
debugPanelWebview?.postMessage({
type: "focusContinueInput",

View file

@ -97,7 +97,7 @@ class IdeProtocolClient {
this.openFile(data.filepath);
// TODO: Close file
break;
case "openNotebook":
case "openGUI":
case "connected":
break;
default:
@ -133,17 +133,17 @@ class IdeProtocolClient {
// ------------------------------------ //
// Initiate Request
closeNotebook(sessionId: string) {
closeGUI(sessionId: string) {
this.panels.get(sessionId)?.dispose();
this.panels.delete(sessionId);
}
async openNotebook() {
async openGUI() {
console.log("OPENING NOTEBOOK");
if (this.messenger === null) {
console.log("MESSENGER IS NULL");
}
const resp = await this.messenger?.sendAndReceive("openNotebook", {});
const resp = await this.messenger?.sendAndReceive("openGUI", {});
const sessionId = resp.sessionId;
console.log("SESSION ID", sessionId);