♻️ use message IDs

This commit is contained in:
Nate Sesti 2023-10-26 11:47:00 -07:00
parent ec21f9f981
commit a7f87e25c3
20 changed files with 467 additions and 80691 deletions

View file

@ -25,9 +25,14 @@ import kotlinx.coroutines.*
import okhttp3.*
import java.io.File
import java.net.NetworkInterface
import java.util.UUID
fun uuid(): String {
return UUID.randomUUID().toString()
}
data class WebSocketMessage<T>(val messageType: String, val data: T)
data class WebSocketMessage<T>(val messageType: String, val messageId: String, val data: T)
data class WorkspaceDirectory(val workspaceDirectory: String)
data class UniqueId(val uniqueId: String)
data class ReadFile(val contents: String)
@ -133,6 +138,12 @@ class IdeProtocolClient(
object : TypeToken<Map<String, Any>>() {}.type
)
val messageType = parsedMessage["messageType"] as? String
val messageId = parsedMessage["messageId"] as? String
if (messageId == null) {
println("Received message without messageId: $text")
return@launch
}
val data = parsedMessage["data"] as Map<*, *>
try {
@ -142,6 +153,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"workspaceDirectory",
messageId,
WorkspaceDirectory(workspaceDirectory())
)
)
@ -152,6 +164,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"uniqueId",
messageId,
UniqueId(uniqueId())
)
)
@ -172,6 +185,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"ide",
messageId,
IdeInfo(
ideName, ideVersion, remoteName
)
@ -195,6 +209,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"readFile",
messageId,
msg
)
)
@ -206,6 +221,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"listDirectoryContents",
messageId,
ListDirectoryContents(listDirectoryContents())
)
)
@ -217,6 +233,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"getTerminalContents",
messageId,
GetTerminalContents("Terminal cannot be accessed in JetBrains IDE")
)
)
@ -229,6 +246,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"visibleFiles",
messageId,
msg
)
)
@ -270,6 +288,7 @@ class IdeProtocolClient(
Gson().toJson(
WebSocketMessage(
"highlightedCode",
messageId,
HighlightedCode(rifs)
)
)
@ -431,31 +450,31 @@ class IdeProtocolClient(
return result
}
private fun<T> sendWebSocketMessage(messageType: String, data: T) {
private fun<T> sendWebSocketMessage(messageType: String, messageId: String, data: T) {
webSocket?.send(Gson().toJson(
WebSocketMessage(messageType, data)
WebSocketMessage(messageType, messageId, data)
))
}
fun sendHighlightedCode(edit: Boolean = false) {
val rif = getHighlightedCode() ?: return
sendWebSocketMessage("highlightedCodePush", HighlightedCodeUpdate(
sendWebSocketMessage("highlightedCodePush", uuid(), HighlightedCodeUpdate(
listOf(rif),
edit
))
}
fun sendMainUserInput(input: String) {
sendWebSocketMessage("mainUserInput", MainUserInput(input))
sendWebSocketMessage("mainUserInput", uuid(), MainUserInput(input))
}
fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) {
sendWebSocketMessage("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex))
sendWebSocketMessage("acceptRejectDiff", uuid(), AcceptRejectDiff(accepted, stepIndex))
}
fun deleteAtIndex(index: Int) {
sendWebSocketMessage("deleteAtIndex", DeleteAtIndex(index))
sendWebSocketMessage("deleteAtIndex", uuid(), DeleteAtIndex(index))
}
private val DEFAULT_IGNORE_DIRS = listOf(

File diff suppressed because one or more lines are too long

View file

@ -1,3 +1,3 @@
function mergeSortAlgorithm() {
// TODO: implement
}
// TODO: implement
}

View file

@ -24,6 +24,7 @@
"request": "^2.88.2",
"strip-ansi": "^7.1.0",
"tailwindcss": "^3.3.2",
"uuidv4": "^6.2.13",
"vscode-languageclient": "^8.0.2",
"ws": "^8.13.0"
},
@ -2529,6 +2530,11 @@
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
},
"node_modules/@types/uuid": {
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.4.tgz",
"integrity": "sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw=="
},
"node_modules/@types/vscode": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.67.0.tgz",
@ -11346,11 +11352,19 @@
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"dev": true,
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/uuidv4": {
"version": "6.2.13",
"resolved": "https://registry.npmjs.org/uuidv4/-/uuidv4-6.2.13.tgz",
"integrity": "sha512-AXyzMjazYB3ovL3q051VLH06Ixj//Knx7QnUSi1T//Ie3io6CpsPu9nVMOx5MoLWh6xV0B9J0hIaxungxXUbPQ==",
"dependencies": {
"@types/uuid": "8.3.4",
"uuid": "8.3.2"
}
},
"node_modules/uvu": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.6.tgz",
@ -13734,6 +13748,11 @@
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
},
"@types/uuid": {
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.4.tgz",
"integrity": "sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw=="
},
"@types/vscode": {
"version": "1.67.0",
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.67.0.tgz",
@ -20120,8 +20139,16 @@
"uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"dev": true
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
},
"uuidv4": {
"version": "6.2.13",
"resolved": "https://registry.npmjs.org/uuidv4/-/uuidv4-6.2.13.tgz",
"integrity": "sha512-AXyzMjazYB3ovL3q051VLH06Ixj//Knx7QnUSi1T//Ie3io6CpsPu9nVMOx5MoLWh6xV0B9J0hIaxungxXUbPQ==",
"requires": {
"@types/uuid": "8.3.4",
"uuid": "8.3.2"
}
},
"uvu": {
"version": "0.5.6",

View file

@ -267,6 +267,7 @@
"request": "^2.88.2",
"strip-ansi": "^7.1.0",
"tailwindcss": "^3.3.2",
"uuidv4": "^6.2.13",
"vscode-languageclient": "^8.0.2",
"ws": "^8.13.0"
},

View file

@ -20,6 +20,7 @@ import { WebsocketMessenger } from "./util/messenger";
import { diffManager } from "./diffs";
const os = require("os");
const path = require("path");
import { uuid } from "uuidv4";
const continueVirtualDocumentScheme = "continue";
@ -68,21 +69,23 @@ class IdeProtocolClient {
messenger.onError(() => {
reconnect();
});
messenger.onMessage((messageType, data, messenger) => {
this.handleMessage(messageType, data, messenger).catch((err) => {
console.log("Error handling message: ", err);
vscode.window
.showErrorMessage(
`Error handling message (${messageType}) from Continue server: ` +
err,
"View Logs"
)
.then((selection) => {
if (selection === "View Logs") {
vscode.commands.executeCommand("continue.viewLogs");
}
});
});
messenger.onMessage((messageType, data, messageId, messenger) => {
this.handleMessage(messageType, data, messageId, messenger).catch(
(err) => {
console.log("Error handling message: ", err);
vscode.window
.showErrorMessage(
`Error handling message (${messageType}) from Continue server: ` +
err,
"View Logs"
)
.then((selection) => {
if (selection === "View Logs") {
vscode.commands.executeCommand("continue.viewLogs");
}
});
}
);
});
}
@ -124,20 +127,20 @@ class IdeProtocolClient {
// Listen for new file creation
vscode.workspace.onDidCreateFiles((event) => {
const filepaths = event.files.map((file) => file.fsPath);
this.messenger?.send("filesCreated", { filepaths });
this.messenger?.send("filesCreated", uuid(), { filepaths });
});
// Listen for file deletion
vscode.workspace.onDidDeleteFiles((event) => {
const filepaths = event.files.map((file) => file.fsPath);
this.messenger?.send("filesDeleted", { filepaths });
this.messenger?.send("filesDeleted", uuid(), { filepaths });
});
// Listen for file renaming
vscode.workspace.onDidRenameFiles((event) => {
const oldFilepaths = event.files.map((file) => file.oldUri.fsPath);
const newFilepaths = event.files.map((file) => file.newUri.fsPath);
this.messenger?.send("filesRenamed", {
this.messenger?.send("filesRenamed", uuid(), {
old_filepaths: oldFilepaths,
new_filepaths: newFilepaths,
});
@ -147,7 +150,7 @@ class IdeProtocolClient {
vscode.workspace.onDidSaveTextDocument((event) => {
const filepath = event.uri.fsPath;
const contents = event.getText();
this.messenger?.send("fileSaved", { filepath, contents });
this.messenger?.send("fileSaved", uuid(), { filepath, contents });
});
// Setup listeners for any selection changes in open editors
@ -234,58 +237,59 @@ class IdeProtocolClient {
async handleMessage(
messageType: string,
data: any,
messageId: string,
messenger: WebsocketMessenger
) {
switch (messageType) {
case "highlightedCode":
messenger.send("highlightedCode", {
messenger.send("highlightedCode", messageId, {
highlightedCode: this.getHighlightedCode(),
});
break;
case "workspaceDirectory":
messenger.send("workspaceDirectory", {
messenger.send("workspaceDirectory", messageId, {
workspaceDirectory: this.getWorkspaceDirectory(),
});
break;
case "uniqueId":
messenger.send("uniqueId", {
messenger.send("uniqueId", messageId, {
uniqueId: this.getUniqueId(),
});
break;
case "ide":
messenger.send("ide", {
messenger.send("ide", messageId, {
name: "vscode",
version: vscode.version,
remoteName: vscode.env.remoteName,
});
break;
case "fileExists":
messenger.send("fileExists", {
messenger.send("fileExists", messageId, {
exists: await this.fileExists(data.filepath),
});
break;
case "getUserSecret":
messenger.send("getUserSecret", {
messenger.send("getUserSecret", messageId, {
value: await this.getUserSecret(data.key),
});
break;
case "openFiles":
messenger.send("openFiles", {
messenger.send("openFiles", messageId, {
openFiles: this.getOpenFiles(),
});
break;
case "visibleFiles":
messenger.send("visibleFiles", {
messenger.send("visibleFiles", messageId, {
visibleFiles: this.getVisibleFiles(),
});
break;
case "readFile":
messenger.send("readFile", {
messenger.send("readFile", messageId, {
contents: await this.readFile(data.filepath),
});
break;
case "getTerminalContents":
messenger.send("getTerminalContents", {
messenger.send("getTerminalContents", messageId, {
contents: await this.getTerminalContents(data.commands),
});
break;
@ -300,13 +304,13 @@ class IdeProtocolClient {
console.log("Error listing directory contents: ", e);
contents = [];
}
messenger.send("listDirectoryContents", {
messenger.send("listDirectoryContents", messageId, {
contents,
});
break;
case "editFile":
const fileEdit = await this.editFile(data.edit);
messenger.send("editFile", {
messenger.send("editFile", messageId, {
fileEdit,
});
break;
@ -314,7 +318,7 @@ class IdeProtocolClient {
this.highlightCode(data.rangeInFile, data.color);
break;
case "runCommand":
messenger.send("runCommand", {
messenger.send("runCommand", messageId, {
output: await this.runCommand(data.command),
});
break;
@ -429,7 +433,7 @@ class IdeProtocolClient {
}
async setTelemetryEnabled(enabled: boolean) {
this.messenger?.send("setTelemetryEnabled", { enabled });
this.messenger?.send("setTelemetryEnabled", uuid(), { enabled });
}
async showDiff(filepath: string, replacement: string, step_index: number) {
@ -509,7 +513,11 @@ class IdeProtocolClient {
}, 1000);
});
console.log("Getting session ID");
const resp = await this.messenger?.sendAndReceive("getSessionId", {});
const resp = await this.messenger?.sendAndReceive(
"getSessionId",
uuid(),
{}
);
console.log("New Continue session with ID: ", resp.sessionId);
this.sessionId = resp.sessionId;
return resp.sessionId;
@ -729,35 +737,38 @@ class IdeProtocolClient {
}
sendCommandOutput(output: string) {
this.messenger?.send("commandOutput", { output });
this.messenger?.send("commandOutput", uuid(), { output });
}
sendHighlightedCode(
highlightedCode: (RangeInFile & { contents: string })[],
edit?: boolean
) {
this.messenger?.send("highlightedCodePush", { highlightedCode, edit });
this.messenger?.send("highlightedCodePush", uuid(), {
highlightedCode,
edit,
});
}
sendAcceptRejectSuggestion(accepted: boolean) {
this.messenger?.send("acceptRejectSuggestion", { accepted });
this.messenger?.send("acceptRejectSuggestion", uuid(), { accepted });
}
sendAcceptRejectDiff(accepted: boolean, stepIndex: number) {
this.messenger?.send("acceptRejectDiff", { accepted, stepIndex });
this.messenger?.send("acceptRejectDiff", uuid(), { accepted, stepIndex });
}
sendMainUserInput(input: string) {
this.messenger?.send("mainUserInput", { input });
this.messenger?.send("mainUserInput", uuid(), { input });
}
async debugTerminal() {
const contents = await this.getTerminalContents();
this.messenger?.send("debugTerminal", { contents });
this.messenger?.send("debugTerminal", uuid(), { contents });
}
deleteAtIndex(index: number) {
this.messenger?.send("deleteAtIndex", { index });
this.messenger?.send("deleteAtIndex", uuid(), { index });
}
}

View file

@ -1,14 +1,16 @@
const WebSocket = require("ws");
export abstract class Messenger {
abstract send(messageType: string, data: object): void;
abstract send(messageType: string, messageId: string, data: object): void;
abstract onMessageType(
messageType: string,
callback: (data: object) => void
): void;
abstract onMessage(callback: (messageType: string, data: any) => void): void;
abstract onMessage(
callback: (messageType: string, messageId: string, data: any) => void
): void;
abstract onOpen(callback: () => void): void;
@ -16,7 +18,11 @@ export abstract class Messenger {
abstract onError(callback: () => void): void;
abstract sendAndReceive(messageType: string, data: any): Promise<any>;
abstract sendAndReceive(
messageType: string,
messageId: string,
data: any
): Promise<any>;
abstract close(): void;
}
@ -55,14 +61,16 @@ export class WebsocketMessenger extends Messenger {
}
}
newWebsocket.addEventListener("open", () => console.log("Websocket connection opened"));
newWebsocket.addEventListener("open", () =>
console.log("Websocket connection opened")
);
newWebsocket.addEventListener("error", (error: any) => {
console.error("Websocket error occurred: ", error);
});
newWebsocket.addEventListener("close", (error: any) => {
console.log("Websocket connection closed: ", error);
});
return newWebsocket;
}
@ -111,8 +119,8 @@ export class WebsocketMessenger extends Messenger {
// }, 1000);
}
send(messageType: string, data: object) {
const payload = JSON.stringify({ messageType, data });
send(messageType: string, messageId: string, data: object) {
const payload = JSON.stringify({ messageType, data, messageId });
if (this.websocket.readyState === this.websocket.OPEN) {
this.websocket.send(payload);
} else {
@ -125,7 +133,11 @@ export class WebsocketMessenger extends Messenger {
}
}
sendAndReceive(messageType: string, data: any): Promise<any> {
sendAndReceive(
messageType: string,
messageId: string,
data: any
): Promise<any> {
return new Promise((resolve, reject) => {
const eventListener = (data: any) => {
// THIS ISN"T GETTING CALLED
@ -133,7 +145,7 @@ export class WebsocketMessenger extends Messenger {
this.websocket.removeEventListener("message", eventListener);
};
this.onMessageType(messageType, eventListener);
this.send(messageType, data);
this.send(messageType, messageId, data);
});
}
@ -150,12 +162,13 @@ export class WebsocketMessenger extends Messenger {
callback: (
messageType: string,
data: any,
messageId: string,
messenger: WebsocketMessenger
) => void
): void {
this.websocket.addEventListener("message", (event) => {
const msg = JSON.parse(event.data);
callback(msg.messageType, msg.data, this);
callback(msg.messageType, msg.data, msg.messageId, this);
});
}

View file

@ -108,7 +108,6 @@ class Autopilot(ContinueBaseModel):
self.policy = override_policy
# Load documents into the search index
logger.debug("Starting context manager")
await self.context_manager.start(
self.continue_sdk.config.context_providers
+ [

View file

@ -304,11 +304,11 @@ class ContextManager:
)
return
logger.debug("Loading Meilisearch index...")
ti = time.time()
await self.load_index(
sdk.ide.workspace_directory, providers_to_load=providers_to_load
)
logger.debug("Loaded Meilisearch index")
logger.info(f"Loaded Meilisearch index in {time.time() - ti:.3f} seconds")
providers_to_load = (
new_context_providers if only_reloading else context_providers
@ -420,9 +420,9 @@ class ContextManager:
return
tf = time.time()
logger.debug(
f"Loaded {num_documents} documents into meilisearch in {tf - ti} seconds for context provider {provider.title}"
)
# logger.info(
# f"Loaded {num_documents} documents into meilisearch in {tf - ti} seconds for context provider {provider.title}"
# )
tasks = [
safe_load(provider)

View file

@ -254,8 +254,6 @@ class ContinueSDK(AbstractContinueSDK):
config = ContinueConfig.from_filepath(path)
self._last_valid_config = config
logger.debug("Loaded Continue config file from %s", path)
return config
except ModuleNotFoundError as e:
if not retry:

View file

@ -60,10 +60,6 @@ class LocalIdeProtocol(AbstractIdeProtocolServer):
"""Get a new session ID"""
pass
async def showSuggestionsAndWait(self, suggestions: List[FileEdit]) -> bool:
"""Show suggestions to the user and wait for a response"""
pass
def onAcceptRejectSuggestion(self, accepted: bool):
"""Called when the user accepts or rejects a suggestion"""
pass

View file

@ -34,6 +34,7 @@ console_handler.setLevel(logging.DEBUG)
# Create a formatter
formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s")
formatter.datefmt = "%Y-%m-%d %H:%M:%S"
# Add the formatter to the handlers
file_handler.setFormatter(formatter)
@ -42,6 +43,3 @@ console_handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# Log a test message
logger.debug("------ Begin Logs ------")

View file

@ -3,7 +3,6 @@ from typing import Dict
class AsyncSubscriptionQueue:
# The correct way to do this is probably to keep request IDs
queues: Dict[str, asyncio.Queue] = {}
def post(self, messageType: str, data: any):
@ -15,3 +14,7 @@ class AsyncSubscriptionQueue:
if message_type not in self.queues:
self.queues.update({message_type: asyncio.Queue()})
return await self.queues[message_type].get()
async def delete(self, message_type: str):
if message_type in self.queues:
del self.queues[message_type]

View file

@ -54,19 +54,6 @@ class PostHogLogger:
_found_disconnected: bool = False
def _capture_event(self, event_name: str, event_properties: Any):
# logger.debug(
# f"Logging to PostHog: {event_name} ({self.unique_id}, {self.allow_anonymous_telemetry}): {event_properties}")
telemetry_path = os.path.expanduser("~/.continue/telemetry.log")
# Make sure the telemetry file exists
if not os.path.exists(telemetry_path):
os.makedirs(os.path.dirname(telemetry_path), exist_ok=True)
open(telemetry_path, "w").close()
with open(telemetry_path, "a") as f:
str_to_write = f"{event_name}: {event_properties}\n{self.unique_id}\n{self.allow_anonymous_telemetry}\n\n"
f.write(str_to_write)
if not self.allow_anonymous_telemetry:
return

View file

@ -137,7 +137,7 @@ class FileContextProvider(ContextProvider):
)
i += 100
asyncio.sleep(0.1)
await asyncio.sleep(0.1)
items = list(filter(lambda item: item is not None, items))

View file

@ -2,6 +2,7 @@ import asyncio
import json
import traceback
from typing import Any, List, Optional, Type, TypeVar
import uuid
from ..plugins.steps.setup_model import SetupModelStep
from fastapi import APIRouter, Depends, WebSocket
@ -67,24 +68,36 @@ class GUIProtocolServer:
def __init__(self, session: Session):
self.session = session
async def _send_json(self, message_type: str, data: Any):
async def _send_json(
self, message_type: str, data: Any, message_id: Optional[str] = None
):
if self.websocket.application_state == WebSocketState.DISCONNECTED:
return
await self.websocket.send_json({"messageType": message_type, "data": data})
return message_id
async def _receive_json(self, message_type: str, timeout: int = 20) -> Any:
message_id = message_id or uuid.uuid4().hex
await self.websocket.send_json(
{"messageType": message_type, "data": data, "messageId": message_id}
)
return message_id
async def _receive_json(self, message_id: str, timeout: int = 20) -> Any:
try:
return await asyncio.wait_for(
self.sub_queue.get(message_type), timeout=timeout
resp = await asyncio.wait_for(
self.sub_queue.get(message_id), timeout=timeout
)
except asyncio.TimeoutError:
raise Exception("GUI Protocol _receive_json timed out after 20 seconds")
finally:
await self.sub_queue.delete(message_id)
return resp
async def _send_and_receive_json(
self, data: Any, resp_model: Type[T], message_type: str
) -> T:
await self._send_json(message_type, data)
resp = await self._receive_json(message_type)
message_id = uuid.uuid4().hex
await self._send_json(message_type, data, message_id=message_id)
resp = await self._receive_json(message_id)
return resp_model.parse_obj(resp)
def on_error(self, e: Exception):
@ -463,10 +476,8 @@ async def websocket_endpoint(
websocket: WebSocket, session: Session = Depends(websocket_session)
):
try:
logger.debug(f"Received websocket connection at url: {websocket.url}")
await websocket.accept()
logger.debug("Session started")
session_manager.register_websocket(session.session_id, websocket)
protocol = GUIProtocolServer(session)
protocol.websocket = websocket
@ -476,16 +487,18 @@ async def websocket_endpoint(
while AppStatus.should_exit is False:
message = await websocket.receive_text()
logger.debug(f"Received GUI message {message}")
if isinstance(message, str):
message = json.loads(message)
if "messageType" not in message or "data" not in message:
logger.warning(f"Invalid message received: {message}")
continue # :o
message_type = message["messageType"]
data = message["data"]
logger.debug(f"Received '{message_type}': {data}")
protocol.handle_json(message_type, data)
except WebSocketDisconnect:
logger.debug("GUI websocket disconnected")
except Exception as e:

View file

@ -176,9 +176,7 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
continue # <-- hey that's the name of this repo!
message_type = message["messageType"]
data = message["data"]
logger.debug(f"Received message while initializing {message_type}")
logger.debug(data)
logger.debug(message)
if message_type == "workspaceDirectory":
self.workspace_directory = data["workspaceDirectory"]
elif message_type == "uniqueId":
@ -193,7 +191,9 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
return other_msgs
async def _send_json(self, message_type: str, data: Any):
async def _send_json(
self, message_type: str, data: Any, message_id: Optional[str] = None
) -> Optional[str]:
# TODO: You breakpointed here, set it to disconnected, and then saw
# that even after reloading, it couldn't connect the server.
# Is this because there is an IDE registered without a websocket?
@ -205,20 +205,28 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
)
return
# logger.debug(f"Sending IDE message: {message_type}")
await self.websocket.send_json({"messageType": message_type, "data": data})
message_id = message_id or uuid.uuid4().hex
await self.websocket.send_json(
{"messageType": message_type, "data": data, "messageId": message_id}
)
return message_id
except RuntimeError as e:
logger.warning(f"Error sending IDE message, websocket probably closed: {e}")
return message_id
async def _receive_json(self, message_type: str, message=None) -> Any:
return await self.sub_queue.get(message_type)
async def _receive_json(self, message_id: str, message=None) -> Any:
resp = await self.sub_queue.get(message_id)
await self.sub_queue.delete(message_id)
return resp
async def _send_and_receive_json(
self, data: Any, resp_model: Type[T], message_type: str
) -> T:
async def try_with_timeout(timeout: int):
await self._send_json(message_type, data)
message_id = uuid.uuid4().hex
await self._send_json(message_type, data, message_id=message_id)
resp = await asyncio.wait_for(
self._receive_json(message_type, message=data), timeout=timeout
self._receive_json(message_id, message=data), timeout=timeout
)
return resp_model.parse_obj(resp)
@ -234,7 +242,7 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
message=f"IDE Protocol _receive_json timed out. The message sent was: {message or ''}",
)
async def handle_json(self, message_type: str, data: Any):
async def handle_json(self, message_type: str, data: Any, message_id: str):
if message_type == "getSessionId":
await self.getSessionId()
elif message_type == "setFileOpen":
@ -277,7 +285,7 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
"listDirectoryContents",
"fileExists",
]:
self.sub_queue.post(message_type, data)
self.sub_queue.post(message_id, data)
elif message_type == "workspaceDirectory":
self.workspace_directory = data["workspaceDirectory"]
elif message_type == "uniqueId":
@ -342,7 +350,6 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
self.session_manager.new_session(self, self.session_id), timeout=5
)
session_id = new_session.session_id
logger.debug(f"Sending session id: {session_id}")
await self._send_json("getSessionId", {"sessionId": session_id})
async def highlightCode(self, range_in_file: RangeInFile, color: str = "#00ff0022"):
@ -357,21 +364,6 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
)
).output
async def showSuggestionsAndWait(self, suggestions: List[FileEdit]) -> bool:
ids = [str(uuid.uuid4()) for _ in suggestions]
for i in range(len(suggestions)):
self._send_json(
"showSuggestion", {"suggestion": suggestions[i], "suggestionId": ids[i]}
)
responses = await asyncio.gather(
*[
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 gui)
return any([r.accepted for r in responses])
def on_error(self, e: Exception) -> Coroutine:
err_msg = "\n".join(traceback.format_exception(e))
e_title = e.__str__() or e.__repr__()
@ -632,8 +624,9 @@ async def websocket_endpoint(websocket: WebSocket, session_id: str = None):
try:
# Accept the websocket connection
await websocket.accept()
logger.debug(f"Accepted websocket connection from {websocket.client}")
await websocket.send_json({"messageType": "connected", "data": {}})
await websocket.send_json(
{"messageType": "connected", "data": {}, "messageId": uuid.uuid4().hex}
)
# Message handler
def handle_msg(msg):
@ -643,14 +636,19 @@ async def websocket_endpoint(websocket: WebSocket, session_id: str = None):
logger.critical(f"Error decoding json: {msg}")
return
if "messageType" not in message or "data" not in message:
if (
"messageType" not in message
or "data" not in message
or "messageId" not in message
):
return
message_type = message["messageType"]
message_id = message["messageId"]
data = message["data"]
# logger.debug(f"Received IDE message: {message_type}")
create_async_task(
ideProtocolServer.handle_json(message_type, data),
ideProtocolServer.handle_json(message_type, data, message_id),
ideProtocolServer.on_error,
)
@ -659,13 +657,8 @@ async def websocket_endpoint(websocket: WebSocket, session_id: str = None):
if session_id is not None:
session_manager.registered_ides[session_id] = ideProtocolServer
other_msgs = await ideProtocolServer.initialize(session_id)
logger.debug(other_msgs)
# posthog_logger.capture_event(
# "session_started", {"session_id": ideProtocolServer.session_id}
# )
for other_msg in other_msgs:
logger.debug("processing....:")
handle_msg(other_msg)
# Handle messages

View file

@ -40,10 +40,6 @@ class AbstractIdeProtocolServer(ABC):
async def getSessionId(self):
"""Get a new session ID"""
@abstractmethod
async def showSuggestionsAndWait(self, suggestions: List[FileEdit]) -> bool:
"""Show suggestions to the user and wait for a response"""
@abstractmethod
def onAcceptRejectSuggestion(self, accepted: bool):
"""Called when the user accepts or rejects a suggestion"""

View file

@ -160,7 +160,7 @@ async def start_meilisearch(url: Optional[str] = None):
shell=True,
)
logger.debug("Meilisearch started")
logger.info(f"Meilisearch started at {meilisearch_url}")
def stop_meilisearch():

View file

@ -63,8 +63,6 @@ class SessionManager:
session_id: Optional[str] = None,
config: Optional[ContinueConfig] = None,
) -> Session:
logger.debug(f"New session: {session_id}")
# Load the persisted state (not being used right now)
full_state = None
if session_id is not None and os.path.exists(getSessionFilePath(session_id)):
@ -98,10 +96,17 @@ class SessionManager:
return ide.showMessage(f"Error in Continue server: {err_msg}")
create_async_task(autopilot.run_policy(), on_error)
session_info = {
"session_id": session_id,
"workspace_directory": ide.workspace_directory,
}
logger.info(f"New session: {json.dumps(session_info, indent=2)}")
return session
async def remove_session(self, session_id: str):
logger.debug(f"Removing session: {session_id}")
logger.info(f"Removing session: {session_id}")
if session_id in self.sessions:
if (
session_id in self.registered_ides
@ -111,7 +116,7 @@ class SessionManager:
if (
ws_to_close is not None
and ws_to_close.client_state != WebSocketState.DISCONNECTED
and ws_to_close.application_state != WebSocketState.DISCONNECTED
and ws_to_close.application_state != WebSocketState.DISCONNECTED
):
await self.sessions[session_id].autopilot.ide.websocket.close()
@ -164,7 +169,6 @@ class SessionManager:
def register_websocket(self, session_id: str, ws: WebSocket):
self.sessions[session_id].ws = ws
logger.debug(f"Registered websocket for session {session_id}")
async def send_ws_data(self, session_id: str, message_type: str, data: Any):
if session_id not in self.sessions:
@ -174,9 +178,12 @@ class SessionManager:
return
ws = self.sessions[session_id].ws
if ws.client_state != WebSocketState.DISCONNECTED and ws.application_state != WebSocketState.DISCONNECTED:
if (
ws.client_state != WebSocketState.DISCONNECTED
and ws.application_state != WebSocketState.DISCONNECTED
):
await ws.send_json(
{"messageType": message_type, "data": data}
{"messageType": message_type, "data": data, "messageId": uuid4().hex}
)