🚧 highlighted code
This commit is contained in:
parent
fd4c256fba
commit
8030c8900f
33 changed files with 869 additions and 798 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
11
extensions/vscode/schema/ContinueConfig.d.ts
vendored
11
extensions/vscode/schema/ContinueConfig.d.ts
vendored
|
|
@ -135,10 +135,6 @@ export type PolicyOverride = Policy;
|
|||
* The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.
|
||||
*/
|
||||
export type Title1 = string;
|
||||
/**
|
||||
* The ContinueSDK instance accessible by the ContextProvider
|
||||
*/
|
||||
export type Sdk = ContinueSDK;
|
||||
/**
|
||||
* The display title of the ContextProvider shown in the dropdown menu
|
||||
*/
|
||||
|
|
@ -305,7 +301,7 @@ export interface Policy {
|
|||
*/
|
||||
export interface ContextProvider {
|
||||
title: Title1;
|
||||
sdk?: Sdk;
|
||||
ide?: Ide;
|
||||
display_title: DisplayTitle;
|
||||
description: Description3;
|
||||
dynamic: Dynamic;
|
||||
|
|
@ -313,10 +309,7 @@ export interface ContextProvider {
|
|||
selected_items?: SelectedItems;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
/**
|
||||
* To avoid circular imports
|
||||
*/
|
||||
export interface ContinueSDK {
|
||||
export interface Ide {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
/**
|
||||
|
|
|
|||
35
extensions/vscode/schema/RangeInFileWithContents.d.ts
vendored
Normal file
35
extensions/vscode/schema/RangeInFileWithContents.d.ts
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
/* 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 RangeInFileWithContents = RangeInFileWithContents1;
|
||||
export type Filepath = string;
|
||||
export type Line = number;
|
||||
export type Character = number;
|
||||
export type Contents = string;
|
||||
|
||||
/**
|
||||
* A range in a file with the contents of the range.
|
||||
*/
|
||||
export interface RangeInFileWithContents1 {
|
||||
filepath: Filepath;
|
||||
range: Range;
|
||||
contents: Contents;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
/**
|
||||
* A range in a file. 0-indexed.
|
||||
*/
|
||||
export interface Range {
|
||||
start: Position;
|
||||
end: Position;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
export interface Position {
|
||||
line: Line;
|
||||
character: Character;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
|
@ -17,25 +17,26 @@ function addHighlightedCodeToContext(edit: boolean) {
|
|||
if (selection.isEmpty) return;
|
||||
const range = new vscode.Range(selection.start, selection.end);
|
||||
const contents = editor.document.getText(range);
|
||||
ideProtocolClient?.sendHighlightedCode(
|
||||
[
|
||||
{
|
||||
filepath: editor.document.uri.fsPath,
|
||||
contents,
|
||||
range: {
|
||||
start: {
|
||||
line: selection.start.line,
|
||||
character: selection.start.character,
|
||||
},
|
||||
end: {
|
||||
line: selection.end.line,
|
||||
character: selection.end.character,
|
||||
},
|
||||
},
|
||||
const rangeInFileWithContents = {
|
||||
filepath: editor.document.uri.fsPath,
|
||||
contents,
|
||||
range: {
|
||||
start: {
|
||||
line: selection.start.line,
|
||||
character: selection.start.character,
|
||||
},
|
||||
],
|
||||
edit
|
||||
);
|
||||
end: {
|
||||
line: selection.end.line,
|
||||
character: selection.end.character,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "highlightedCode",
|
||||
rangeInFileWithContents,
|
||||
edit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
getUniqueId,
|
||||
openEditorAndRevealRange,
|
||||
} from "./util/vscode";
|
||||
import { RangeInFile } from "../schema/RangeInFile";
|
||||
import { RangeInFileWithContents } from "../schema/RangeInFileWithContents";
|
||||
import { setFocusedOnContinueInput } from "./commands";
|
||||
import { ideProtocolClient, windowId } from "./activation/activate";
|
||||
import * as io from "socket.io-client";
|
||||
|
|
@ -50,30 +50,6 @@ export function setupDebugPanel(
|
|||
|
||||
const nonce = getNonce();
|
||||
|
||||
vscode.window.onDidChangeTextEditorSelection((e) => {
|
||||
if (e.selections[0].isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rangeInFile: RangeInFile = {
|
||||
range: e.selections[0] as any,
|
||||
filepath: e.textEditor.document.fileName,
|
||||
};
|
||||
const filesystem = {
|
||||
[rangeInFile.filepath]: e.textEditor.document.getText(),
|
||||
};
|
||||
panel.webview.postMessage({
|
||||
type: "highlightedCode",
|
||||
rangeInFile,
|
||||
filesystem,
|
||||
});
|
||||
|
||||
panel.webview.postMessage({
|
||||
type: "workspacePath",
|
||||
value: vscode.workspace.workspaceFolders?.[0].uri.fsPath,
|
||||
});
|
||||
});
|
||||
|
||||
async function connectWebsocket(url: string) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onMessage = (message: any) => {
|
||||
|
|
|
|||
|
|
@ -48,7 +48,12 @@ import {
|
|||
} from "../util/jetbrains";
|
||||
import FileIcon from "./FileIcon";
|
||||
import { ContextItem } from "../schema/ContextItem";
|
||||
import { newSession, setActive } from "../redux/slices/sessionStateReducer";
|
||||
import {
|
||||
addContextItem,
|
||||
addContextItemAtIndex,
|
||||
newSession,
|
||||
setActive,
|
||||
} from "../redux/slices/sessionStateReducer";
|
||||
|
||||
const SEARCH_INDEX_NAME = "continue_context_items";
|
||||
|
||||
|
|
@ -345,11 +350,9 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
|
|||
});
|
||||
const selectedContextItems = useSelector((state: RootStore) => {
|
||||
if (props.index) {
|
||||
// TODO
|
||||
return [];
|
||||
// return state.serverState.history.timeline[props.index].context_used || [];
|
||||
return state.sessionState.contextItemsAtIndex[props.index] || [];
|
||||
} else {
|
||||
return state.serverState.selectedContextItems;
|
||||
return state.sessionState.context_items;
|
||||
}
|
||||
});
|
||||
const timeline = useSelector(
|
||||
|
|
@ -391,6 +394,20 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
|
|||
|
||||
const [prevInputValue, setPrevInputValue] = useState("");
|
||||
|
||||
const selectContextItem = useCallback(
|
||||
async (id: string, query: string) => {
|
||||
const contextItem = await client?.getContextItem(id, query);
|
||||
if (props.isMainInput) {
|
||||
dispatch(addContextItem(contextItem));
|
||||
} else if (props.index) {
|
||||
dispatch(
|
||||
addContextItemAtIndex({ item: contextItem, index: props.index })
|
||||
);
|
||||
}
|
||||
},
|
||||
[client, props.index]
|
||||
);
|
||||
|
||||
const onInputValueChangeCallback = useCallback(
|
||||
({ inputValue, highlightedIndex }: any) => {
|
||||
// Clear the input
|
||||
|
|
@ -658,17 +675,6 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
|
|||
|
||||
const deleteButtonDivRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
const selectContextItem = useCallback(
|
||||
(id: string, query: string) => {
|
||||
if (props.isMainInput) {
|
||||
client?.selectContextItem(id, query);
|
||||
} else if (props.index) {
|
||||
client?.selectContextItemAtIndex(id, query, props.index);
|
||||
}
|
||||
},
|
||||
[client, props.index]
|
||||
);
|
||||
|
||||
const selectContextItemFromDropdown = useCallback(
|
||||
(event: any) => {
|
||||
const newItem = items[downshiftProps.highlightedIndex];
|
||||
|
|
@ -865,106 +871,98 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
|
|||
>
|
||||
<TrashIcon width="1.4em" height="1.4em" />
|
||||
</HiddenHeaderButtonWithText>
|
||||
{(props.isMainInput
|
||||
? selectedContextItems
|
||||
: (timeline[props.index!].context_used as any) || []
|
||||
)
|
||||
// TODO: Need to store context_used somewhere
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<PillButton
|
||||
areMultipleItems={selectedContextItems.length > 1}
|
||||
key={`${item.description.id.item_id}${idx}`}
|
||||
item={item}
|
||||
editing={
|
||||
item.editing &&
|
||||
(inputRef.current as any)?.value?.startsWith("/edit")
|
||||
}
|
||||
editingAny={(inputRef.current as any)?.value?.startsWith(
|
||||
"/edit"
|
||||
)}
|
||||
stepIndex={props.index}
|
||||
index={idx}
|
||||
onDelete={() => {
|
||||
client?.deleteContextWithIds(
|
||||
[item.description.id],
|
||||
props.index
|
||||
);
|
||||
inputRef.current?.focus();
|
||||
if (
|
||||
(item.description.id.item_id ===
|
||||
focusedContextItem?.description.id.item_id &&
|
||||
focusedContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name) ||
|
||||
(item.description.id.item_id ===
|
||||
previewingContextItem?.description.id.item_id &&
|
||||
previewingContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name)
|
||||
) {
|
||||
setPreviewingContextItem(undefined);
|
||||
setFocusedContextItem(undefined);
|
||||
}
|
||||
}}
|
||||
onClick={(e) => {
|
||||
if (
|
||||
item.description.id.item_id ===
|
||||
focusedContextItem?.description.id.item_id &&
|
||||
{selectedContextItems.map((item, idx) => {
|
||||
return (
|
||||
<PillButton
|
||||
areMultipleItems={selectedContextItems.length > 1}
|
||||
key={`${item.description.id.item_id}${idx}`}
|
||||
item={item}
|
||||
editing={
|
||||
item.editing &&
|
||||
(inputRef.current as any)?.value?.startsWith("/edit")
|
||||
}
|
||||
editingAny={(inputRef.current as any)?.value?.startsWith(
|
||||
"/edit"
|
||||
)}
|
||||
stepIndex={props.index}
|
||||
index={idx}
|
||||
onDelete={() => {
|
||||
client?.deleteContextWithIds(
|
||||
[item.description.id],
|
||||
props.index
|
||||
);
|
||||
inputRef.current?.focus();
|
||||
if (
|
||||
(item.description.id.item_id ===
|
||||
focusedContextItem?.description.id.item_id &&
|
||||
focusedContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
) {
|
||||
setFocusedContextItem(undefined);
|
||||
} else {
|
||||
setFocusedContextItem(item);
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
setFocusedContextItem(undefined);
|
||||
}}
|
||||
toggleViewContent={() => {
|
||||
setPreviewingContextItem((prev) => {
|
||||
if (!prev) return item;
|
||||
if (
|
||||
prev.description.id.item_id ===
|
||||
item.description.id.item_id &&
|
||||
prev.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
) {
|
||||
return undefined;
|
||||
} else {
|
||||
return item;
|
||||
}
|
||||
});
|
||||
}}
|
||||
previewing={
|
||||
item.description.id.item_id ===
|
||||
item.description.id.provider_name) ||
|
||||
(item.description.id.item_id ===
|
||||
previewingContextItem?.description.id.item_id &&
|
||||
previewingContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
previewingContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name)
|
||||
) {
|
||||
setPreviewingContextItem(undefined);
|
||||
setFocusedContextItem(undefined);
|
||||
}
|
||||
focusing={
|
||||
}}
|
||||
onClick={(e) => {
|
||||
if (
|
||||
item.description.id.item_id ===
|
||||
focusedContextItem?.description.id.item_id &&
|
||||
focusedContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
) {
|
||||
setFocusedContextItem(undefined);
|
||||
} else {
|
||||
setFocusedContextItem(item);
|
||||
}
|
||||
prefixInputWithEdit={(should) => {
|
||||
}}
|
||||
onBlur={() => {
|
||||
setFocusedContextItem(undefined);
|
||||
}}
|
||||
toggleViewContent={() => {
|
||||
setPreviewingContextItem((prev) => {
|
||||
if (!prev) return item;
|
||||
if (
|
||||
!should &&
|
||||
inputRef.current?.value.startsWith("/edit")
|
||||
prev.description.id.item_id ===
|
||||
item.description.id.item_id &&
|
||||
prev.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
) {
|
||||
downshiftProps.setInputValue(
|
||||
inputRef.current?.value.replace("/edit ", "")
|
||||
);
|
||||
return undefined;
|
||||
} else {
|
||||
return item;
|
||||
}
|
||||
if (downshiftProps.inputValue.startsWith("/edit")) return;
|
||||
});
|
||||
}}
|
||||
previewing={
|
||||
item.description.id.item_id ===
|
||||
previewingContextItem?.description.id.item_id &&
|
||||
previewingContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
}
|
||||
focusing={
|
||||
item.description.id.item_id ===
|
||||
focusedContextItem?.description.id.item_id &&
|
||||
focusedContextItem?.description.id.provider_name ===
|
||||
item.description.id.provider_name
|
||||
}
|
||||
prefixInputWithEdit={(should) => {
|
||||
if (!should && inputRef.current?.value.startsWith("/edit")) {
|
||||
downshiftProps.setInputValue(
|
||||
`/edit ${downshiftProps.inputValue}`
|
||||
inputRef.current?.value.replace("/edit ", "")
|
||||
);
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
}
|
||||
if (downshiftProps.inputValue.startsWith("/edit")) return;
|
||||
downshiftProps.setInputValue(
|
||||
`/edit ${downshiftProps.inputValue}`
|
||||
);
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{/* {selectedContextItems.length > 0 && (
|
||||
<HeaderButtonWithText
|
||||
onClick={() => {
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@ abstract class AbstractContinueGUIClientProtocol {
|
|||
|
||||
abstract selectContextItem(id: string, query: string): void;
|
||||
|
||||
abstract getContextItem(id: string, query: string): Promise<ContextItem>;
|
||||
|
||||
abstract selectContextItemAtIndex(
|
||||
id: string,
|
||||
query: string,
|
||||
|
|
|
|||
|
|
@ -96,6 +96,12 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
|
|||
});
|
||||
}
|
||||
|
||||
onAddContextItem(callback: (item: ContextItem) => void) {
|
||||
this.messenger?.onMessageType("add_context_item", (data: ContextItem) => {
|
||||
callback(data);
|
||||
});
|
||||
}
|
||||
|
||||
onAvailableSlashCommands(
|
||||
callback: (commands: { name: string; description: string }[]) => void
|
||||
) {
|
||||
|
|
@ -141,6 +147,13 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
|
|||
this.messenger?.send("select_context_item", { id, query });
|
||||
}
|
||||
|
||||
async getContextItem(id: string, query: string): Promise<ContextItem> {
|
||||
return await this.messenger?.sendAndReceive("get_context_item", {
|
||||
id,
|
||||
query,
|
||||
});
|
||||
}
|
||||
|
||||
selectContextItemAtIndex(id: string, query: string, index: number): void {
|
||||
this.messenger?.send("select_context_item_at_index", {
|
||||
id,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
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";
|
||||
addContextItem,
|
||||
addHighlightedCode,
|
||||
processSessionUpdate,
|
||||
} from "../redux/slices/sessionStateReducer";
|
||||
import { setServerStatusMessage } from "../redux/slices/miscSlice";
|
||||
import { postToIde } from "../vscode";
|
||||
import { useSelector } from "react-redux";
|
||||
import { RootStore } from "../redux/store";
|
||||
|
|
@ -24,6 +25,10 @@ async function clientSetup(
|
|||
dispatch(processSessionUpdate(update));
|
||||
});
|
||||
|
||||
client.onAddContextItem((item) => {
|
||||
dispatch(addContextItem(item));
|
||||
});
|
||||
|
||||
fetch(`${serverUrl}/slash_commands`).then(async (resp) => {
|
||||
const sc = await resp.json();
|
||||
dispatch(setSlashCommands(sc));
|
||||
|
|
@ -52,7 +57,12 @@ function useSetup(
|
|||
const eventListener = (event: any) => {
|
||||
switch (event.data.type) {
|
||||
case "highlightedCode":
|
||||
dispatch(setHighlightedCode(event.data.rangeInFile));
|
||||
dispatch(
|
||||
addHighlightedCode({
|
||||
rangeInFileWithContents: event.data.rangeInFileWithContents,
|
||||
edit: event.data.edit,
|
||||
})
|
||||
);
|
||||
break;
|
||||
case "serverStatus":
|
||||
dispatch(setServerStatusMessage(event.data.message));
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
import { RootStore } from "../store";
|
||||
|
||||
const selectHighlightedCode = (state: RootStore) => state.misc.highlightedCode;
|
||||
|
||||
export { selectHighlightedCode };
|
||||
|
|
@ -3,14 +3,10 @@ import { createSlice } from "@reduxjs/toolkit";
|
|||
export const miscSlice = createSlice({
|
||||
name: "misc",
|
||||
initialState: {
|
||||
highlightedCode: "",
|
||||
takenAction: false,
|
||||
serverStatusMessage: "Continue Server Starting",
|
||||
},
|
||||
reducers: {
|
||||
setHighlightedCode: (state: any, action) => {
|
||||
state.highlightedCode = action.payload;
|
||||
},
|
||||
setTakenActionTrue: (state: any, action) => {
|
||||
state.takenAction = true;
|
||||
},
|
||||
|
|
@ -20,9 +16,5 @@ export const miscSlice = createSlice({
|
|||
},
|
||||
});
|
||||
|
||||
export const {
|
||||
setHighlightedCode,
|
||||
setTakenActionTrue,
|
||||
setServerStatusMessage,
|
||||
} = miscSlice.actions;
|
||||
export const { setTakenActionTrue, setServerStatusMessage } = miscSlice.actions;
|
||||
export default miscSlice.reducer;
|
||||
|
|
|
|||
|
|
@ -3,9 +3,11 @@ import { StepDescription } from "../../schema/SessionState";
|
|||
import { SessionUpdate } from "../../schema/SessionUpdate";
|
||||
import { ContextItem } from "../../schema/ContextItem";
|
||||
import { PersistedSessionInfo } from "../../schema/PersistedSessionInfo";
|
||||
import { v4 } from "uuid";
|
||||
|
||||
export interface SessionFullState {
|
||||
history: StepDescription[];
|
||||
contextItemsAtIndex: { [index: number]: ContextItem[] };
|
||||
context_items: ContextItem[];
|
||||
active: boolean;
|
||||
title: string;
|
||||
|
|
@ -18,6 +20,7 @@ export const sessionStateSlice = createSlice({
|
|||
context_items: [],
|
||||
active: false,
|
||||
title: "New Session",
|
||||
contextItemsAtIndex: {},
|
||||
},
|
||||
reducers: {
|
||||
processSessionUpdate: (
|
||||
|
|
@ -121,6 +124,64 @@ export const sessionStateSlice = createSlice({
|
|||
};
|
||||
return { ...state, history: newHistory };
|
||||
},
|
||||
addContextItem: (
|
||||
state: SessionFullState,
|
||||
{ payload }: { payload: ContextItem }
|
||||
) => {
|
||||
return {
|
||||
...state,
|
||||
context_items: [...state.context_items, payload],
|
||||
};
|
||||
},
|
||||
addContextItemAtIndex: (
|
||||
state: SessionFullState,
|
||||
{ payload }: { payload: { item: ContextItem; index: number } }
|
||||
) => {
|
||||
return {
|
||||
...state,
|
||||
contextItemsAtIndex: {
|
||||
...state.contextItemsAtIndex,
|
||||
[payload.index]: [
|
||||
...(state.contextItemsAtIndex[payload.index] ?? []),
|
||||
payload.item,
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
addHighlightedCode: (
|
||||
state: SessionFullState,
|
||||
{
|
||||
payload,
|
||||
}: {
|
||||
payload: { rangeInFileWithContents: any; edit: boolean };
|
||||
}
|
||||
) => {
|
||||
// TODO: Merging
|
||||
let contextItems = [...state.context_items].map((item) => {
|
||||
return { ...item, editing: false };
|
||||
});
|
||||
const lineNums = `(${
|
||||
payload.rangeInFileWithContents.range.start.line + 1
|
||||
}-${payload.rangeInFileWithContents.range.end.line + 1})`;
|
||||
const base = payload.rangeInFileWithContents.filepath
|
||||
.split(/[\\/]/)
|
||||
.pop();
|
||||
contextItems.push({
|
||||
description: {
|
||||
name: `${base} ${lineNums}`,
|
||||
description: payload.rangeInFileWithContents.filepath,
|
||||
id: {
|
||||
provider_title: "code",
|
||||
item_id: v4(),
|
||||
},
|
||||
},
|
||||
content: payload.rangeInFileWithContents.contents,
|
||||
editing: payload.edit,
|
||||
editable: true,
|
||||
});
|
||||
|
||||
return { ...state, context_items: contextItems };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -130,5 +191,8 @@ export const {
|
|||
processSessionUpdate,
|
||||
newSession,
|
||||
deleteAtIndex,
|
||||
addContextItem,
|
||||
addContextItemAtIndex,
|
||||
addHighlightedCode,
|
||||
} = sessionStateSlice.actions;
|
||||
export default sessionStateSlice.reducer;
|
||||
|
|
|
|||
|
|
@ -7,11 +7,7 @@ import serverStateReducer from "./slices/serverStateReducer";
|
|||
import sessionStateReducer, {
|
||||
SessionFullState,
|
||||
} from "./slices/sessionStateReducer";
|
||||
import {
|
||||
ContextProvider,
|
||||
ContinueConfig,
|
||||
SlashCommand,
|
||||
} from "../schema/ContinueConfig";
|
||||
import { ContinueConfig } from "../schema/ContinueConfig";
|
||||
import { ContextItem } from "../schema/ContextItem";
|
||||
import { ContextProviderDescription } from "../schema/ContextProviderDescription";
|
||||
import { SlashCommandDescription } from "../schema/SlashCommandDescription";
|
||||
|
|
@ -30,7 +26,6 @@ export interface RootStore {
|
|||
windowId: string | undefined;
|
||||
};
|
||||
misc: {
|
||||
highlightedCode: RangeInFile | undefined;
|
||||
takenAction: boolean;
|
||||
serverStatusMessage: string;
|
||||
};
|
||||
|
|
|
|||
11
gui/src/schema/ContinueConfig.d.ts
vendored
11
gui/src/schema/ContinueConfig.d.ts
vendored
|
|
@ -135,10 +135,6 @@ export type PolicyOverride = Policy;
|
|||
* The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.
|
||||
*/
|
||||
export type Title1 = string;
|
||||
/**
|
||||
* The ContinueSDK instance accessible by the ContextProvider
|
||||
*/
|
||||
export type Sdk = ContinueSDK;
|
||||
/**
|
||||
* The display title of the ContextProvider shown in the dropdown menu
|
||||
*/
|
||||
|
|
@ -305,7 +301,7 @@ export interface Policy {
|
|||
*/
|
||||
export interface ContextProvider {
|
||||
title: Title1;
|
||||
sdk?: Sdk;
|
||||
ide?: Ide;
|
||||
display_title: DisplayTitle;
|
||||
description: Description3;
|
||||
dynamic: Dynamic;
|
||||
|
|
@ -313,10 +309,7 @@ export interface ContextProvider {
|
|||
selected_items?: SelectedItems;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
/**
|
||||
* To avoid circular imports
|
||||
*/
|
||||
export interface ContinueSDK {
|
||||
export interface Ide {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
/**
|
||||
|
|
|
|||
35
gui/src/schema/RangeInFileWithContents.d.ts
vendored
Normal file
35
gui/src/schema/RangeInFileWithContents.d.ts
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
/* 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 RangeInFileWithContents = RangeInFileWithContents1;
|
||||
export type Filepath = string;
|
||||
export type Line = number;
|
||||
export type Character = number;
|
||||
export type Contents = string;
|
||||
|
||||
/**
|
||||
* A range in a file with the contents of the range.
|
||||
*/
|
||||
export interface RangeInFileWithContents1 {
|
||||
filepath: Filepath;
|
||||
range: Range;
|
||||
contents: Contents;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
/**
|
||||
* A range in a file. 0-indexed.
|
||||
*/
|
||||
export interface Range {
|
||||
start: Position;
|
||||
end: Position;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
export interface Position {
|
||||
line: Line;
|
||||
character: Character;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
|
@ -70,6 +70,7 @@
|
|||
},
|
||||
"description": {
|
||||
"title": "Description",
|
||||
"default": "",
|
||||
"type": "string"
|
||||
},
|
||||
"class_name": {
|
||||
|
|
@ -298,12 +299,6 @@
|
|||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"ContinueSDK": {
|
||||
"title": "ContinueSDK",
|
||||
"description": "To avoid circular imports",
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"ContextItemId": {
|
||||
"title": "ContextItemId",
|
||||
"description": "A ContextItemId is a unique identifier for a ContextItem.",
|
||||
|
|
@ -384,14 +379,8 @@
|
|||
"description": "The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.",
|
||||
"type": "string"
|
||||
},
|
||||
"sdk": {
|
||||
"title": "Sdk",
|
||||
"description": "The ContinueSDK instance accessible by the ContextProvider",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/ContinueSDK"
|
||||
}
|
||||
]
|
||||
"ide": {
|
||||
"title": "Ide"
|
||||
},
|
||||
"display_title": {
|
||||
"title": "Display Title",
|
||||
|
|
|
|||
64
schema/json/RangeInFileWithContents.json
Normal file
64
schema/json/RangeInFileWithContents.json
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"title": "RangeInFileWithContents",
|
||||
"$ref": "#/definitions/continuedev__models__filesystem__RangeInFileWithContents",
|
||||
"definitions": {
|
||||
"Position": {
|
||||
"title": "Position",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"line": {
|
||||
"title": "Line",
|
||||
"type": "integer"
|
||||
},
|
||||
"character": {
|
||||
"title": "Character",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"line",
|
||||
"character"
|
||||
]
|
||||
},
|
||||
"Range": {
|
||||
"title": "Range",
|
||||
"description": "A range in a file. 0-indexed.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"start": {
|
||||
"$ref": "#/definitions/Position"
|
||||
},
|
||||
"end": {
|
||||
"$ref": "#/definitions/Position"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"start",
|
||||
"end"
|
||||
]
|
||||
},
|
||||
"continuedev__models__filesystem__RangeInFileWithContents": {
|
||||
"title": "RangeInFileWithContents",
|
||||
"description": "A range in a file with the contents of the range.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filepath": {
|
||||
"title": "Filepath",
|
||||
"type": "string"
|
||||
},
|
||||
"range": {
|
||||
"$ref": "#/definitions/Range"
|
||||
},
|
||||
"contents": {
|
||||
"title": "Contents",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"filepath",
|
||||
"range",
|
||||
"contents"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -111,6 +111,11 @@ class ContinueConfig(BaseModel):
|
|||
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def schema(cls, *args, **kwargs):
|
||||
kwargs.setdefault("exclude", {"ide"})
|
||||
return super().schema(*args, **kwargs)
|
||||
|
||||
@validator("temperature", pre=True)
|
||||
def temperature_validator(cls, v):
|
||||
return max(0.0, min(1.0, v))
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import asyncio
|
||||
import time
|
||||
from abc import abstractmethod
|
||||
from typing import Awaitable, Callable, Dict, List, Optional
|
||||
from typing import Any, Awaitable, Callable, Dict, List, Optional
|
||||
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
|
||||
|
||||
from meilisearch_python_async import Client
|
||||
from pydantic import BaseModel, Field
|
||||
|
|
@ -48,9 +49,8 @@ class ContextProvider(BaseModel):
|
|||
...,
|
||||
description="The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.",
|
||||
)
|
||||
sdk: ContinueSDK = Field(
|
||||
None, description="The ContinueSDK instance accessible by the ContextProvider"
|
||||
)
|
||||
ide: Any = None
|
||||
|
||||
delete_documents: Callable[[List[str]], Awaitable] = Field(
|
||||
None, description="Function to delete documents"
|
||||
)
|
||||
|
|
@ -78,6 +78,10 @@ class ContextProvider(BaseModel):
|
|||
[], description="List of selected items in the ContextProvider"
|
||||
)
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
exclude = {"ide", "delete_documents", "update_documents"}
|
||||
|
||||
def get_description(self) -> ContextProviderDescription:
|
||||
return ContextProviderDescription(
|
||||
title=self.title,
|
||||
|
|
@ -89,18 +93,20 @@ class ContextProvider(BaseModel):
|
|||
|
||||
def dict(self, *args, **kwargs):
|
||||
original_dict = super().dict(*args, **kwargs)
|
||||
original_dict.pop("sdk", None)
|
||||
original_dict.pop("ide", None)
|
||||
original_dict.pop("delete_documents", None)
|
||||
original_dict.pop("update_documents", None)
|
||||
return original_dict
|
||||
|
||||
async def start(self, sdk: ContinueSDK, delete_documents, update_documents):
|
||||
async def start(
|
||||
self, ide: AbstractIdeProtocolServer, delete_documents, update_documents
|
||||
):
|
||||
"""
|
||||
Starts the context provider.
|
||||
|
||||
Default implementation sets the sdk.
|
||||
"""
|
||||
self.sdk = sdk
|
||||
self.ide = ide
|
||||
self.delete_documents = delete_documents
|
||||
self.update_documents = update_documents
|
||||
|
||||
|
|
@ -159,20 +165,6 @@ class ContextProvider(BaseModel):
|
|||
|
||||
return None
|
||||
|
||||
async def delete_context_with_ids(self, ids: List[ContextItemId]):
|
||||
"""
|
||||
Deletes the ContextItems with the given IDs, lets ContextProviders recalculate.
|
||||
|
||||
Default implementation simply deletes those with the given ids.
|
||||
"""
|
||||
id_strings = {id.to_string() for id in ids}
|
||||
self.selected_items = list(
|
||||
filter(
|
||||
lambda item: item.description.id.to_string() not in id_strings,
|
||||
self.selected_items,
|
||||
)
|
||||
)
|
||||
|
||||
async def clear_context(self):
|
||||
"""
|
||||
Clears all context.
|
||||
|
|
@ -198,13 +190,6 @@ class ContextProvider(BaseModel):
|
|||
if new_item := await self.get_item(id, query):
|
||||
self.selected_items.append(new_item)
|
||||
|
||||
async def manually_add_context_item(self, context_item: ContextItem):
|
||||
for item in self.selected_items:
|
||||
if item.description.id.item_id == context_item.description.id.item_id:
|
||||
return
|
||||
|
||||
self.selected_items.append(context_item)
|
||||
|
||||
async def preview_contents(self, id: ContextItemId):
|
||||
"""
|
||||
Open a virtual file or otherwise preview the contents of the context provider in the IDE
|
||||
|
|
@ -212,7 +197,7 @@ class ContextProvider(BaseModel):
|
|||
if item := next(
|
||||
filter(lambda x: x.description.id == id, self.selected_items), None
|
||||
):
|
||||
await self.sdk.ide.showVirtualFile(item.description.name, item.content)
|
||||
await self.ide.showVirtualFile(item.description.name, item.content)
|
||||
|
||||
|
||||
class ContextManager:
|
||||
|
|
@ -226,34 +211,6 @@ class ContextManager:
|
|||
It is responsible for compiling all of this information into a single prompt without exceeding the token limit.
|
||||
"""
|
||||
|
||||
def get_provider_descriptions(self) -> List[ContextProviderDescription]:
|
||||
"""
|
||||
Returns a list of ContextProviderDescriptions for each context provider.
|
||||
"""
|
||||
return [
|
||||
ContextProviderDescription(
|
||||
title=provider.title,
|
||||
display_title=provider.display_title,
|
||||
description=provider.description,
|
||||
dynamic=provider.dynamic,
|
||||
requires_query=provider.requires_query,
|
||||
)
|
||||
for provider in self.context_providers.values()
|
||||
if provider.title != "code"
|
||||
]
|
||||
|
||||
async def get_selected_items(self) -> List[ContextItem]:
|
||||
"""
|
||||
Returns all of the selected ContextItems.
|
||||
"""
|
||||
return sum(
|
||||
[
|
||||
await provider.get_selected_items()
|
||||
for provider in self.context_providers.values()
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
async def get_chat_messages(self) -> List[ChatMessage]:
|
||||
"""
|
||||
Returns chat messages from each provider.
|
||||
|
|
@ -273,7 +230,7 @@ class ContextManager:
|
|||
async def start(
|
||||
self,
|
||||
context_providers: List[ContextProvider],
|
||||
sdk: ContinueSDK,
|
||||
ide: AbstractIdeProtocolServer,
|
||||
only_reloading: bool = False,
|
||||
):
|
||||
"""
|
||||
|
|
@ -292,7 +249,7 @@ class ContextManager:
|
|||
|
||||
for provider in context_providers:
|
||||
await provider.start(
|
||||
sdk,
|
||||
ide,
|
||||
ContextManager.delete_documents,
|
||||
ContextManager.update_documents,
|
||||
)
|
||||
|
|
@ -315,7 +272,7 @@ class ContextManager:
|
|||
|
||||
ti = time.time()
|
||||
await self.load_index(
|
||||
sdk.ide.workspace_directory, providers_to_load=providers_to_load
|
||||
ide.workspace_directory, providers_to_load=providers_to_load
|
||||
)
|
||||
logger.info(f"Loaded Meilisearch index in {time.time() - ti:.3f} seconds")
|
||||
|
||||
|
|
@ -455,9 +412,9 @@ class ContextManager:
|
|||
)
|
||||
await self.load_index(workspace_dir, False)
|
||||
|
||||
async def select_context_item(self, id: str, query: str):
|
||||
async def get_context_item(self, id: str, query: str) -> ContextItem:
|
||||
"""
|
||||
Selects the ContextItem with the given id.
|
||||
Returns the ContextItem with the given id.
|
||||
"""
|
||||
id: ContextItemId = ContextItemId.from_string(id)
|
||||
if id.provider_title not in self.provider_titles:
|
||||
|
|
@ -481,55 +438,9 @@ class ContextManager:
|
|||
"query": query,
|
||||
},
|
||||
)
|
||||
await self.context_providers[id.provider_title].add_context_item(id, query)
|
||||
|
||||
async def get_context_item(self, id: str, query: str) -> ContextItem:
|
||||
"""
|
||||
Returns the ContextItem with the given id.
|
||||
"""
|
||||
id: ContextItemId = ContextItemId.from_string(id)
|
||||
if id.provider_title not in self.provider_titles:
|
||||
raise ValueError(
|
||||
f"Context provider with title {id.provider_title} not found"
|
||||
)
|
||||
|
||||
return await self.context_providers[id.provider_title].get_item(id, query)
|
||||
|
||||
async def delete_context_with_ids(self, ids: List[str]):
|
||||
"""
|
||||
Deletes the ContextItems with the given IDs, lets ContextProviders recalculate.
|
||||
"""
|
||||
|
||||
# Group by provider title
|
||||
provider_title_to_ids: Dict[str, List[ContextItemId]] = {}
|
||||
for id in ids:
|
||||
id: ContextItemId = ContextItemId.from_string(id)
|
||||
if id.provider_title not in provider_title_to_ids:
|
||||
provider_title_to_ids[id.provider_title] = []
|
||||
provider_title_to_ids[id.provider_title].append(id)
|
||||
|
||||
# Recalculate context for each updated provider
|
||||
for provider_title, ids in provider_title_to_ids.items():
|
||||
await self.context_providers[provider_title].delete_context_with_ids(ids)
|
||||
|
||||
async def clear_context(self):
|
||||
"""
|
||||
Clears all context.
|
||||
"""
|
||||
for provider in self.context_providers.values():
|
||||
await self.context_providers[provider.title].clear_context()
|
||||
|
||||
async def manually_add_context_item(self, item: ContextItem):
|
||||
"""
|
||||
Adds the given ContextItem to the list of ContextItems.
|
||||
"""
|
||||
if item.description.id.provider_title not in self.provider_titles:
|
||||
return
|
||||
|
||||
await self.context_providers[
|
||||
item.description.id.provider_title
|
||||
].manually_add_context_item(item)
|
||||
|
||||
async def preview_context_item(self, id: str):
|
||||
"""
|
||||
Opens a virtual file or otherwise previews the contents of the context provider in the IDE.
|
||||
|
|
|
|||
|
|
@ -193,12 +193,7 @@ class ContinueSDK:
|
|||
return [c.rif for c in context]
|
||||
|
||||
async def add_context_item(self, item: ContextItem):
|
||||
await self.__autopilot.context_manager.manually_add_context_item(item)
|
||||
|
||||
async def delete_context_item(self, id: ContextItemId):
|
||||
await self.__autopilot.delete_context_with_ids(
|
||||
[f"{id.provider_title}-{id.item_id}"]
|
||||
)
|
||||
await self.gui.add_context_item(item)
|
||||
|
||||
def set_loading_message(self, message: str):
|
||||
# self.__autopilot.set_loading_message(message)
|
||||
|
|
|
|||
|
|
@ -14,14 +14,14 @@ from ..core.main import (
|
|||
)
|
||||
from ..core.models import Models
|
||||
from ..libs.llm.base import LLM
|
||||
from .filesystem import FileEdit, RangeInFile
|
||||
from .filesystem import FileEdit, RangeInFile, RangeInFileWithContents
|
||||
from .filesystem_edit import FileEditWithFullContents
|
||||
from .main import Position, Range, Traceback, TracebackFrame
|
||||
from ..server.sessions import PersistedSessionInfo
|
||||
|
||||
MODELS_TO_GENERATE = (
|
||||
[Position, Range, Traceback, TracebackFrame]
|
||||
+ [RangeInFile, FileEdit]
|
||||
+ [RangeInFile, FileEdit, RangeInFileWithContents]
|
||||
+ [FileEditWithFullContents]
|
||||
+ [
|
||||
SessionInfo,
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ import asyncio
|
|||
import os
|
||||
from typing import List, Optional
|
||||
|
||||
from ...server.protocols.ide_protocol import AbstractIdeProtocolServer
|
||||
|
||||
from ...core.context import ContextProvider
|
||||
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
|
||||
from ...core.sdk import ContinueSDK
|
||||
from ...libs.util.filter_files import DEFAULT_IGNORE_PATTERNS
|
||||
from ...libs.util.logging import logger
|
||||
from .util import remove_meilisearch_disallowed_chars
|
||||
|
|
@ -12,9 +13,9 @@ from .util import remove_meilisearch_disallowed_chars
|
|||
MAX_SIZE_IN_CHARS = 50_000
|
||||
|
||||
|
||||
async def get_file_contents(filepath: str, sdk: ContinueSDK) -> str:
|
||||
async def get_file_contents(filepath: str, ide: AbstractIdeProtocolServer) -> str:
|
||||
try:
|
||||
return (await sdk.ide.readFile(filepath))[:MAX_SIZE_IN_CHARS]
|
||||
return (await ide.readFile(filepath))[:MAX_SIZE_IN_CHARS]
|
||||
except Exception as _:
|
||||
return None
|
||||
|
||||
|
|
@ -38,7 +39,7 @@ class FileContextProvider(ContextProvider):
|
|||
item = await self.get_context_item_for_filepath(filepath)
|
||||
if item is None:
|
||||
return
|
||||
await self.update_documents([item], self.sdk.ide.workspace_directory)
|
||||
await self.update_documents([item], self.ide.workspace_directory)
|
||||
|
||||
async def on_files_created(filepaths: List[str]):
|
||||
items = await asyncio.gather(
|
||||
|
|
@ -48,7 +49,7 @@ class FileContextProvider(ContextProvider):
|
|||
]
|
||||
)
|
||||
items = [item for item in items if item is not None]
|
||||
await self.update_documents(items, self.sdk.ide.workspace_directory)
|
||||
await self.update_documents(items, self.ide.workspace_directory)
|
||||
|
||||
async def on_files_deleted(filepaths: List[str]):
|
||||
ids = [self.get_id_for_filepath(filepath) for filepath in filepaths]
|
||||
|
|
@ -56,7 +57,7 @@ class FileContextProvider(ContextProvider):
|
|||
await self.delete_documents(ids)
|
||||
|
||||
async def on_files_renamed(old_filepaths: List[str], new_filepaths: List[str]):
|
||||
if self.sdk.ide.workspace_directory is None:
|
||||
if self.ide.workspace_directory is None:
|
||||
return
|
||||
|
||||
old_ids = [self.get_id_for_filepath(filepath) for filepath in old_filepaths]
|
||||
|
|
@ -69,12 +70,12 @@ class FileContextProvider(ContextProvider):
|
|||
new_docs = [doc for doc in new_docs if doc is not None]
|
||||
|
||||
await self.delete_documents(old_ids)
|
||||
await self.update_documents(new_docs, self.sdk.ide.workspace_directory)
|
||||
await self.update_documents(new_docs, self.ide.workspace_directory)
|
||||
|
||||
self.sdk.ide.subscribeToFileSaved(on_file_saved)
|
||||
self.sdk.ide.subscribeToFilesCreated(on_files_created)
|
||||
self.sdk.ide.subscribeToFilesDeleted(on_files_deleted)
|
||||
self.sdk.ide.subscribeToFilesRenamed(on_files_renamed)
|
||||
self.ide.subscribeToFileSaved(on_file_saved)
|
||||
self.ide.subscribeToFilesCreated(on_files_created)
|
||||
self.ide.subscribeToFilesDeleted(on_files_deleted)
|
||||
self.ide.subscribeToFilesRenamed(on_files_renamed)
|
||||
|
||||
def get_id_for_filepath(self, absolute_filepath: str) -> str:
|
||||
return remove_meilisearch_disallowed_chars(absolute_filepath)
|
||||
|
|
@ -82,11 +83,11 @@ class FileContextProvider(ContextProvider):
|
|||
async def get_context_item_for_filepath(
|
||||
self, absolute_filepath: str
|
||||
) -> Optional[ContextItem]:
|
||||
content = await get_file_contents(absolute_filepath, self.sdk)
|
||||
content = await get_file_contents(absolute_filepath, self.ide)
|
||||
if content is None:
|
||||
return None
|
||||
|
||||
workspace_dir = self.sdk.ide.workspace_directory
|
||||
workspace_dir = self.ide.workspace_directory
|
||||
if (
|
||||
os.path.splitdrive(workspace_dir)[0]
|
||||
!= os.path.splitdrive(absolute_filepath)[0]
|
||||
|
|
@ -117,7 +118,7 @@ class FileContextProvider(ContextProvider):
|
|||
)
|
||||
|
||||
async def provide_context_items(self, workspace_dir: str) -> List[ContextItem]:
|
||||
contents = await self.sdk.ide.listDirectoryContents(workspace_dir, True)
|
||||
contents = await self.ide.listDirectoryContents(workspace_dir, True)
|
||||
if contents is None:
|
||||
return []
|
||||
|
||||
|
|
@ -147,9 +148,9 @@ class FileContextProvider(ContextProvider):
|
|||
if item := next(
|
||||
filter(lambda x: x.description.id == id, self.selected_items), None
|
||||
):
|
||||
await self.sdk.ide.setFileOpen(
|
||||
await self.ide.setFileOpen(
|
||||
os.path.join(
|
||||
self.sdk.ide.workspace_directory, item.description.description
|
||||
self.ide.workspace_directory, item.description.description
|
||||
),
|
||||
True,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ class FileTreeContextProvider(ContextProvider):
|
|||
workspace_dir: str = Field(None, description="The workspace directory to display")
|
||||
|
||||
async def _get_file_tree(self, directory: str) -> str:
|
||||
contents = await self.sdk.ide.listDirectoryContents(directory, recursive=True)
|
||||
contents = await self.ide.listDirectoryContents(directory, recursive=True)
|
||||
|
||||
tree = Directory(
|
||||
name=split_path(self.workspace_dir)[-1], files=[], directories=[]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import asyncio
|
||||
import os
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Dict, List, Optional
|
||||
from ...server.protocols.ide_protocol import AbstractIdeProtocolServer
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
|
@ -33,7 +34,10 @@ class HighlightedCodeContextProvider(ContextProvider):
|
|||
description = "Highlight code"
|
||||
dynamic = True
|
||||
|
||||
ide: Any # IdeProtocolServer
|
||||
ide: AbstractIdeProtocolServer
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
highlighted_ranges: List[HighlightedRangeContextItem] = []
|
||||
adding_highlighted_code: bool = True
|
||||
|
|
@ -80,7 +84,7 @@ class HighlightedCodeContextProvider(ContextProvider):
|
|||
ranges = [fallback_item]
|
||||
|
||||
fresh_contents_tasks = [
|
||||
self.sdk.ide.readRangeInFile(r.rif.to_range_in_file()) for r in ranges
|
||||
self.ide.readRangeInFile(r.rif.to_range_in_file()) for r in ranges
|
||||
]
|
||||
fresh_contents = await asyncio.gather(*fresh_contents_tasks)
|
||||
for i in range(len(ranges)):
|
||||
|
|
@ -140,24 +144,6 @@ class HighlightedCodeContextProvider(ContextProvider):
|
|||
self.should_get_fallback_context_item = True
|
||||
self.last_added_fallback = False
|
||||
|
||||
async def delete_context_with_ids(
|
||||
self, ids: List[ContextItemId]
|
||||
) -> List[ContextItem]:
|
||||
ids_to_delete = [id.item_id for id in ids]
|
||||
|
||||
kept_ranges = []
|
||||
for hr in self.highlighted_ranges:
|
||||
if hr.item.description.id.item_id not in ids_to_delete:
|
||||
kept_ranges.append(hr)
|
||||
self.highlighted_ranges = kept_ranges
|
||||
|
||||
self._make_sure_is_editing_range()
|
||||
|
||||
if len(self.highlighted_ranges) == 0 and self.last_added_fallback:
|
||||
self.should_get_fallback_context_item = False
|
||||
|
||||
return [hr.item for hr in self.highlighted_ranges]
|
||||
|
||||
def _rif_to_name(
|
||||
self,
|
||||
rif: RangeInFileWithContents,
|
||||
|
|
@ -282,38 +268,20 @@ class HighlightedCodeContextProvider(ContextProvider):
|
|||
) -> List[ContextItem]:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def manually_add_context_item(self, context_item: ContextItem):
|
||||
full_file_content = await self.ide.readFile(
|
||||
context_item.description.description
|
||||
)
|
||||
self.highlighted_ranges.append(
|
||||
HighlightedRangeContextItem(
|
||||
rif=RangeInFileWithContents(
|
||||
filepath=context_item.description.description,
|
||||
range=Range.from_lines_snippet_in_file(
|
||||
content=full_file_content,
|
||||
snippet=context_item.content,
|
||||
),
|
||||
contents=context_item.content,
|
||||
),
|
||||
item=context_item,
|
||||
)
|
||||
)
|
||||
|
||||
async def preview_contents(self, id: ContextItemId):
|
||||
if item := next(
|
||||
filter(lambda x: x.item.description.id == id, self.highlighted_ranges), None
|
||||
):
|
||||
filepath = os.path.join(
|
||||
self.sdk.ide.workspace_directory, item.item.description.description
|
||||
self.ide.workspace_directory, item.item.description.description
|
||||
)
|
||||
await self.sdk.ide.setFileOpen(
|
||||
await self.ide.setFileOpen(
|
||||
filepath,
|
||||
True,
|
||||
)
|
||||
line_nums_string = item.item.description.name.split(" ")[-1]
|
||||
line_nums = line_nums_string[1:-1].split("-")
|
||||
await self.sdk.ide.highlightCode(
|
||||
await self.ide.highlightCode(
|
||||
RangeInFile(
|
||||
filepath=filepath,
|
||||
range=Range.from_shorthand(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from typing import List
|
||||
from typing import Any, List
|
||||
|
||||
from pydantic import Field
|
||||
from ripgrepy import Ripgrepy
|
||||
|
|
|
|||
|
|
@ -41,9 +41,7 @@ class TerminalContextProvider(ContextProvider):
|
|||
if not id.provider_title == self.title:
|
||||
raise Exception("Invalid provider title for item")
|
||||
|
||||
terminal_contents = await self.sdk.ide.getTerminalContents(
|
||||
self.get_last_n_commands
|
||||
)
|
||||
terminal_contents = await self.ide.getTerminalContents(self.get_last_n_commands)
|
||||
terminal_contents = terminal_contents[-5000:]
|
||||
|
||||
return self._terminal_context_item(terminal_contents)
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ async def ensure_meilisearch_installed() -> bool:
|
|||
if meilisearchPath in existing_paths:
|
||||
try:
|
||||
os.remove(meilisearchPath)
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
existing_paths.remove(meilisearchPath)
|
||||
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ class GUIProtocolServer:
|
|||
messenger: SocketIOMessenger
|
||||
|
||||
get_autopilot: Callable[[SessionState], Autopilot]
|
||||
get_context_item: Callable[[str, str], ContextItem]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
|
@ -43,10 +44,12 @@ class GUIProtocolServer:
|
|||
sio: socketio.AsyncServer,
|
||||
sid: str,
|
||||
get_autopilot: Callable[[SessionState], Autopilot],
|
||||
get_context_item: Callable[[str, str], ContextItem],
|
||||
):
|
||||
self.window_id = window_id
|
||||
self.messenger = SocketIOMessenger(sio, sid)
|
||||
self.get_autopilot = get_autopilot
|
||||
self.get_context_item = get_context_item
|
||||
|
||||
def on_error(self, e: Exception):
|
||||
# TODO
|
||||
|
|
@ -58,6 +61,8 @@ class GUIProtocolServer:
|
|||
await self.run_from_state(SessionState.parse_obj(data["state"]))
|
||||
elif msg.message_type == "stop_session":
|
||||
await self.stop_session()
|
||||
elif msg.message_type == "get_context_item":
|
||||
await self.get_context_item(data["id"], data["query"])
|
||||
|
||||
elif msg.message_type == "set_current_session_title":
|
||||
self.set_current_session_title(data["title"])
|
||||
|
|
@ -328,4 +333,11 @@ class GUIProtocolServer:
|
|||
async def send_session_update(self, session_update: SessionUpdate):
|
||||
await self.messenger.send("session_update", session_update.dict())
|
||||
|
||||
async def add_context_item(self, item: ContextItem):
|
||||
await self.messenger.send("add_context_item", item.dict())
|
||||
|
||||
async def get_context_item(self, id: str, query: str):
|
||||
context_item = await self.get_context_item(id, query)
|
||||
await self.messenger.send("get_context_item", context_item.dict())
|
||||
|
||||
# endregion
|
||||
|
|
|
|||
|
|
@ -137,15 +137,17 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
|
|||
messenger: SocketIOMessenger
|
||||
window_info: WindowInfo
|
||||
|
||||
@property
|
||||
def workspace_directory(self) -> str:
|
||||
return self.window_info.workspace_directory
|
||||
|
||||
def __init__(self, window_info: WindowInfo, sio: socketio.AsyncServer, sid: str):
|
||||
self.messenger = SocketIOMessenger(sio, sid)
|
||||
self.window_info = window_info
|
||||
|
||||
async def handle_json(self, msg: WebsocketsMessage):
|
||||
data = msg.data
|
||||
if msg.message_type == "getSessionId":
|
||||
await self.getSessionId()
|
||||
elif msg.message_type == "setFileOpen":
|
||||
if msg.message_type == "setFileOpen":
|
||||
await self.setFileOpen(data["filepath"], data["open"])
|
||||
elif msg.message_type == "setSuggestionsLocked":
|
||||
await self.setSuggestionsLocked(data["filepath"], data["locked"])
|
||||
|
|
@ -313,13 +315,12 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
|
|||
range_in_files: List[RangeInFileWithContents],
|
||||
edit: Optional[bool] = False,
|
||||
):
|
||||
if autopilot := self.__get_autopilot():
|
||||
create_async_task(
|
||||
autopilot.handle_highlighted_code(range_in_files, edit), self.on_error
|
||||
)
|
||||
for callback in self._highlighted_code_callbacks:
|
||||
self.call_callback(callback, range_in_files, edit)
|
||||
|
||||
## Subscriptions ##
|
||||
|
||||
_highlighted_code_callbacks = []
|
||||
_files_created_callbacks = []
|
||||
_files_deleted_callbacks = []
|
||||
_files_renamed_callbacks = []
|
||||
|
|
@ -331,6 +332,11 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
|
|||
else:
|
||||
callback(*args, **kwargs)
|
||||
|
||||
def subscribeToHighlightedCode(
|
||||
self, callback: Callable[[List[RangeInFileWithContents], bool], None]
|
||||
):
|
||||
self._highlighted_code_callbacks.append(callback)
|
||||
|
||||
def subscribeToFilesCreated(self, callback: Callable[[List[str]], None]):
|
||||
self._files_created_callbacks.append(callback)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import traceback
|
||||
from typing import Dict, Optional
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from ..models.filesystem import RangeInFileWithContents
|
||||
|
||||
from ..core.context import ContextManager
|
||||
|
||||
from ..plugins.context_providers.highlighted_code import HighlightedCodeContextProvider
|
||||
|
||||
from ..plugins.context_providers.file import FileContextProvider
|
||||
|
||||
from ..core.main import SessionState
|
||||
from ..core.autopilot import Autopilot
|
||||
|
|
@ -24,6 +32,7 @@ class Window:
|
|||
ide: Optional[IdeProtocolServer] = None
|
||||
gui: Optional[GUIProtocolServer] = None
|
||||
config: Optional[ContinueConfig] = None
|
||||
context_manager: ContextManager = ContextManager()
|
||||
|
||||
def get_autopilot(self, session_state: SessionState) -> Autopilot:
|
||||
return Autopilot(
|
||||
|
|
@ -83,15 +92,25 @@ class Window:
|
|||
dev_data_logger.setup(self.config.user_token, self.config.data_server_url)
|
||||
|
||||
# Load documents into the search index
|
||||
# await self.context_manager.start(
|
||||
# self.sdk.config.context_providers
|
||||
# + [
|
||||
# HighlightedCodeContextProvider(ide=self.sdk.ide),
|
||||
# FileContextProvider(workspace_dir=self.sdk.ide.workspace_directory),
|
||||
# ],
|
||||
# self.sdk,
|
||||
# only_reloading=only_reloading,
|
||||
# )
|
||||
await self.context_manager.start(
|
||||
self.config.context_providers
|
||||
+ [
|
||||
HighlightedCodeContextProvider(ide=self.ide),
|
||||
FileContextProvider(workspace_dir=self.ide.workspace_directory),
|
||||
],
|
||||
self.ide,
|
||||
only_reloading=only_reloading,
|
||||
)
|
||||
|
||||
# # Subscribe to highlighted code, pass to the context manager
|
||||
# def onHighlightedCodeCallback(
|
||||
# range_in_files: List[RangeInFileWithContents], edit: bool
|
||||
# ):
|
||||
# if "file" in self.context_manager.context_providers:
|
||||
# self.context_manager.context_providers["file"].get_context_item
|
||||
# await self.gui.add_context_item(item)
|
||||
|
||||
# self.ide.subscribeToHighlightedCode(onHighlightedCodeCallback)
|
||||
|
||||
# Load saved context groups
|
||||
# context_groups_file = getSavedContextGroupsPath()
|
||||
|
|
@ -160,6 +179,7 @@ class WindowManager:
|
|||
sio=sio,
|
||||
sid=sid,
|
||||
get_autopilot=self.windows[window_id].get_autopilot,
|
||||
get_context_item=self.windows[window_id].context_manager.get_context_item,
|
||||
)
|
||||
self.windows[window_id].gui = gui
|
||||
self.guis[sid] = gui
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue