🚧 /edit

This commit is contained in:
Nate Sesti 2023-10-30 12:04:03 -07:00
parent 818d0fd52e
commit bd8035fa84
17 changed files with 389 additions and 340 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

@ -699,10 +699,6 @@ class IdeProtocolClient {
const contents = await this.getTerminalContents();
this.send("debugTerminal", v4(), { contents });
}
deleteAtIndex(index: number) {
this.send("deleteAtIndex", v4(), { index });
}
}
export default IdeProtocolClient;

View file

@ -6,6 +6,7 @@ import { extensionContext, ideProtocolClient } from "./activation/activate";
import { getMetaKeyLabel, getPlatform } from "./util/util";
import { devDataPath } from "./activation/environmentSetup";
import { uriFromFilePath } from "./util/vscode";
import { debugPanelWebview } from "./debugPanel";
interface DiffInfo {
originalFilepath: string;
@ -297,7 +298,7 @@ class DiffManager {
}
// Stop the step at step_index in case it is still streaming
ideProtocolClient.deleteAtIndex(diffInfo.step_index);
debugPanelWebview?.postMessage({ type: "stopSession" });
vscode.workspace.textDocuments
.find((doc) => doc.uri.fsPath === newFilepath)

View file

@ -788,7 +788,13 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}, [inputFocused]);
return (
<div ref={topRef}>
<div
ref={topRef}
style={{
paddingTop: "4px",
backgroundColor: vscBackground,
}}
>
{selectedContextItems.length === 0 && props.isMainInput && (
<div
style={{

View file

@ -1,10 +1,11 @@
import { Dispatch } from "@reduxjs/toolkit";
import ContinueGUIClientProtocol from "./ContinueGUIClientProtocol";
import { useCallback, useEffect } from "react";
import { useCallback, useEffect, useState } from "react";
import {
addContextItem,
addHighlightedCode,
processSessionUpdate,
setActive,
setTitle,
} from "../redux/slices/sessionStateReducer";
import { setServerStatusMessage } from "../redux/slices/miscSlice";
@ -22,24 +23,30 @@ function useSetup(
) {
const serverUrl = useSelector((store: RootStore) => store.config.apiUrl);
const active = useSelector((store: RootStore) => store.sessionState.active);
const nVisibleSteps = useSelector(
(store: RootStore) =>
store.sessionState.history.filter((step) => !step.hide).length
);
const title = useSelector((store: RootStore) => store.sessionState.title);
const history = useSelector((store: RootStore) => store.sessionState.history);
const possiblyGetTitle = useCallback(async () => {
console.log("possiblyGetTitle", title, history);
if (
!active &&
title === "New Session" &&
history.filter((step) => !step.hide).length > 3
) {
const title = await client.getSessionTitle(history);
dispatch(setTitle(title));
}
}, [active, nVisibleSteps, history, title, client]);
const [requestedTitle, setRequestedTitle] = useState(false);
useEffect(() => {
// Override persisted state
dispatch(setActive(false));
}, []);
useEffect(() => {
(async () => {
if (
!requestedTitle &&
!active &&
title === "New Session" &&
history.filter((step) => !step.hide).length > 2
) {
setRequestedTitle(true);
const title = await client.getSessionTitle(history);
dispatch(setTitle(title));
}
})();
}, [active, history, title, client, requestedTitle]);
// Setup requiring client
useEffect(() => {
@ -48,7 +55,6 @@ function useSetup(
// Listen for updates to the session state
client.onSessionUpdate((update) => {
dispatch(processSessionUpdate(update));
possiblyGetTitle();
});
client.onAddContextItem((item) => {
@ -80,12 +86,14 @@ function useSetup(
case "serverStatus":
dispatch(setServerStatusMessage(event.data.message));
break;
case "stopSession":
client?.stopSession();
break;
}
};
window.addEventListener("message", eventListener);
postToIde("onLoad", {});
return () => window.removeEventListener("message", eventListener);
}, []);
}, [client]);
// Save theme colors to local storage
useEffect(() => {

View file

@ -88,6 +88,7 @@ export const sessionStateSlice = createSlice({
...state,
history: payload.session_state.history,
context_items: payload.session_state.context_items,
contextItemsAtIndex: {},
active: false,
title: payload.title,
};
@ -96,6 +97,7 @@ export const sessionStateSlice = createSlice({
...state,
history: [],
context_items: [],
contextItemsAtIndex: {},
active: false,
title: "New Session",
};

View file

@ -263,31 +263,36 @@ class Autopilot:
depth=self._step_depth,
)
def handle_step_update(update: UpdateStep):
if isinstance(update, SessionUpdate):
return update
elif isinstance(update, str):
return SessionUpdate(index=index, update=DeltaStep(description=update))
elif isinstance(update, Observation):
return SessionUpdate(
index=index, update=DeltaStep(observations=[update])
)
elif isinstance(update, DeltaStep) or isinstance(update, SetStep):
return SessionUpdate(index=index, update=update)
else:
logger.warning(f"Unknown type yielded from Step: {update}")
# Try to run step and handle errors
try:
async for update in step.run(self.sdk):
if self.stopped:
# TODO: Early stopping
for update in step.on_stop(self.sdk):
yield handle_step_update(update)
return
if isinstance(update, str):
yield SessionUpdate(
index=index, update=DeltaStep(description=update)
)
elif isinstance(update, Observation):
yield SessionUpdate(
index=index, update=DeltaStep(observations=[update])
)
elif isinstance(update, DeltaStep) or isinstance(update, SetStep):
yield SessionUpdate(index=index, update=update)
else:
logger.warning(f"Unknown type yielded from Step: {update}")
yield handle_step_update(update)
except Exception as e:
continue_custom_exception = self.handle_error(e, step)
yield SessionUpdate(index=index, update=DeltaStep(hide=False))
yield SessionUpdate(index=index, update=SetStep(hide=False))
while self.session_state.history[index].name != step.name:
yield SessionUpdate(index=index, update=DeltaStep(hide=True))
yield SessionUpdate(index=index, update=SetStep(hide=True))
index -= 1
# i is now the index of the step that we want to show/rerun
@ -336,6 +341,9 @@ class Autopilot:
await self.handle_session_update(update)
async def handle_session_update(self, update: AutopilotGeneratorOutput):
if update is None:
return
if isinstance(update, StepDescription):
index = len(self.session_state.history)
self.session_state.history.append(update)
@ -372,16 +380,6 @@ class Autopilot:
self.config.models.remove_logger(logger_id)
async def reject_diff(self, step_index: int):
# idk...
# Hide the edit step and the UserInputStep before it
self.history.timeline[step_index].step.hide = True
for i in range(step_index - 1, -1, -1):
if isinstance(self.history.timeline[i].step, UserInputStep):
self.history.timeline[i].step.hide = True
break
await self.update_subscribers()
async def select_context_item(self, id: str, query: str):
# sdk.gui.select_context_item???
await self.context_manager.select_context_item(id, query)

View file

@ -135,11 +135,6 @@ class DeltaStep(BaseModel):
return super().dict(*args, **kwargs)
UpdateStep = Union[
DeltaStep, SetStep
] # TODO: Pydantic doesn't seem to be respecting the type, changes to the other on init
class StepDescription(BaseModel):
step_type: str
name: str
@ -166,7 +161,7 @@ class StepDescription(BaseModel):
)
]
def update(self, update: UpdateStep):
def update(self, update: "UpdateStep"):
if isinstance(update, DeltaStep):
for key, value in update.dict(exclude_none=True).items():
setattr(self, key, getattr(self, key) + value)
@ -177,7 +172,7 @@ class StepDescription(BaseModel):
class SessionUpdate(BaseModel):
index: int
update: UpdateStep
update: "UpdateStep"
stop: Optional[bool] = None
class Config:
@ -190,6 +185,10 @@ class SessionUpdate(BaseModel):
return d
UpdateStep = Union[DeltaStep, SetStep, SessionUpdate]
SessionUpdate.update_forward_refs()
StepGenerator = AsyncGenerator[Union[str, UpdateStep, Observation], None]
AutopilotGeneratorOutput = Union[SessionUpdate, StepDescription]
AutopilotGenerator = AsyncGenerator[AutopilotGeneratorOutput, None]
@ -339,6 +338,9 @@ class Step(ContinueBaseModel):
return self.description
return "Running step: " + self.name
def on_stop(self, sdk: ContinueSDK):
yield None
def dict(self, *args, **kwargs):
d = super().dict(*args, **kwargs)
# Make sure description is always a string

View file

@ -1,6 +1,9 @@
import asyncio
import os
from typing import Coroutine, List, Optional, Union
from ..plugins.context_providers.highlighted_code import HighlightedCodeContextProvider
from ..models.filesystem import RangeInFile
from ..models.filesystem_edit import (
@ -74,6 +77,10 @@ class ContinueSDK:
def context_items(self) -> List[ContextItem]:
return self.__autopilot.session_state.context_items
@property
def stopped(self):
return self.__autopilot.stopped
def write_log(self, message: str):
self.history.timeline[self.history.current_index].logs.append(message)
@ -94,8 +101,7 @@ class ContinueSDK:
raise Exception(f"Path {path} does not exist")
async def run_step(self, step: Step) -> StepGenerator:
async for update in self.__autopilot.run_step(step):
yield update
await self.__autopilot.run_step(step)
async def apply_filesystem_edit(
self, edit: FileSystemEdit, name: str = None, description: str = None
@ -183,18 +189,20 @@ class ContinueSDK:
path = await self._ensure_absolute_path(path)
return await self.run_step(FileSystemEditStep(edit=DeleteDirectory(path=path)))
def get_code_context(
async def get_code_context(
self, only_editing: bool = False
) -> List[RangeInFileWithContents]:
highlighted_ranges = self.__autopilot.context_manager.context_providers[
"code"
].highlighted_ranges
context = (
list(filter(lambda x: x.item.editing, highlighted_ranges))
if only_editing
else highlighted_ranges
editing = filter(
lambda x: x.editable and (x.editing or not only_editing), self.context_items
)
return await asyncio.gather(
*[
HighlightedCodeContextProvider.get_range_in_file_with_contents(
self.ide, item
)
for item in editing
]
)
return [c.rif for c in context]
async def add_context_item(self, item: ContextItem):
await self.gui.add_context_item(item)

View file

@ -22,7 +22,14 @@ from ..models.filesystem_edit import (
FileSystemEdit,
)
from .main import ChatMessage, ContinueCustomException, SetStep, Step
from .main import (
ChatMessage,
ContinueCustomException,
DeltaStep,
SessionUpdate,
SetStep,
Step,
)
from .observation import TextObservation, UserInputObservation
@ -189,6 +196,13 @@ class DefaultModelEditCodeStep(Step):
else:
return None
def on_stop(self, sdk: ContinueSDK):
index = len(sdk.history)
for i in range(index - 1, -1, -1):
yield SessionUpdate(index=i, update=SetStep(hide=True))
if sdk.history[i].step_type == "UserInputStep":
break
async def get_prompt_parts(
self, rif: RangeInFileWithContents, sdk: ContinueSDK, full_file_contents: str
):
@ -418,7 +432,7 @@ Please output the code to be inserted at the cursor in order to fulfill the user
+ "\n".join(full_suffix_lines)
)
step_index = sdk.history.current_index
step_index = len(sdk.history) - 1
await sdk.ide.showDiff(rif.filepath, new_file_contents, step_index)
@ -617,6 +631,9 @@ Please output the code to be inserted at the cursor in order to fulfill the user
try:
last_task_time = time.time()
async for chunk in generator:
if sdk.stopped:
return
# Stop early if it is repeating the file_suffix or the step was deleted
if repeating_file_suffix:
break

View file

@ -34,6 +34,9 @@ class RangeInFile(BaseModel):
def translated(self, lines: int):
return RangeInFile(filepath=self.filepath, range=self.range.translated(lines))
def with_contents(self, contents: str) -> "RangeInFileWithContents":
return RangeInFileWithContents.from_range_in_file(self, contents)
class RangeInFileWithContents(RangeInFile):
"""A range in a file with the contents of the range."""

View file

@ -76,18 +76,25 @@ class HighlightedCodeContextProvider(ContextProvider):
return items
async def get_chat_message(self, item: ContextItem) -> List[ContextItem]:
@staticmethod
async def get_range_in_file_with_contents(
ide, item: ContextItem
) -> RangeInFileWithContents:
lines = item.description.name.split("(")[1].split(")")[0].split("-")
fresh_content = await self.ide.readRangeInFile(
RangeInFile(
filepath=item.description.description,
range=Range.from_shorthand(int(lines[0]), 0, int(lines[1]), 0),
)
rif = RangeInFile(
filepath=item.description.description,
range=Range.from_shorthand(int(lines[0]), 0, int(lines[1]), 0),
)
contents = await ide.readRangeInFile(rif)
return rif.with_contents(contents)
async def get_chat_message(self, item: ContextItem) -> List[ContextItem]:
rif = await HighlightedCodeContextProvider.get_range_in_file_with_contents(
self.ide, item
)
return ChatMessage(
role="user",
content=f"Code in this file is highlighted ({item.description.name}):\n```\n{fresh_content}\n```",
content=f"Code in this file is highlighted ({item.description.name}):\n```\n{rif.contents}\n```",
summary=f"Code in this file is highlighted: {item.description.name}",
)

View file

@ -14,7 +14,11 @@ 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, GenerateShellCommandStep]
REPLACEMENT_SLASH_COMMAND_STEPS = [
AnswerQuestionChroma,
GenerateShellCommandStep,
EditHighlightedCodeStep,
]
def parse_slash_command(inp: str, config: ContinueConfig) -> Union[None, Step]:

View file

@ -52,7 +52,7 @@ class CreateCodebaseIndexChroma(Step):
if index.exists():
return
yield DeltaStep(hide=False)
yield SetStep(hide=False)
async for progress in index.build(sdk, ignore_files=self.ignore_files):
yield SetStep(
description=f"Generating codebase embeddings... {int(progress*100)}%",
@ -122,7 +122,7 @@ class AnswerQuestionChroma(Step):
context_items.append(ctx_item)
await sdk.add_context_item(ctx_item)
yield DeltaStep(hide=True)
yield SetStep(hide=True)
model = sdk.models.chat.model
# if model == "gpt-4":

View file

@ -302,7 +302,9 @@ class EditHighlightedCodeStep(Step):
return "Editing code"
async def run(self, sdk: ContinueSDK):
range_in_files = sdk.get_code_context(only_editing=True)
yield "Editing file..."
range_in_files = await sdk.get_code_context(only_editing=True)
# If nothing highlighted, insert at the cursor if possible
if len(range_in_files) == 0:

View file

@ -11,6 +11,10 @@ from typing import (
Optional,
)
from ...core.main import SessionState
from ...core.autopilot import Autopilot
from ...libs.util.create_async_task import create_async_task
from ...models.filesystem import (
FileSystem,
@ -173,8 +177,6 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
self.onAcceptRejectDiff(data["accepted"], data["stepIndex"])
elif msg.message_type == "mainUserInput":
self.onMainUserInput(data["input"])
elif msg.message_type == "deleteAtIndex":
self.onDeleteAtIndex(data["index"])
elif msg.message_type in [
"highlightedCode",
"openFiles",
@ -274,13 +276,6 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
posthog_logger.capture_event("accept_reject_diff", {"accepted": accepted})
dev_data_logger.capture("accept_reject_diff", {"accepted": accepted})
if not accepted:
if autopilot := self.__get_autopilot():
create_async_task(
autopilot.reject_diff(step_index),
self.on_error,
)
def onFileSystemUpdate(self, update: FileSystemEdit):
# Access to Autopilot (so SessionManager)
pass