🚧 IpcIde in fewer lines of code

This commit is contained in:
Nate Sesti 2024-02-14 23:54:15 -08:00
parent 756cb7fead
commit 6113e802d5
7 changed files with 244 additions and 335 deletions

118
core/util/messageIde.ts Normal file
View file

@ -0,0 +1,118 @@
import { ContinueRcJson, IDE, Problem, Range } from "..";
export class MessageIde implements IDE {
constructor(
private readonly request: (messageType: string, data: any) => Promise<any>
) {}
readRangeInFile(filepath: string, range: Range): Promise<string> {
return this.request("readRangeInFile", { filepath, range });
}
getStats(directory: string): Promise<{ [path: string]: number }> {
throw new Error("Method not implemented.");
}
isTelemetryEnabled(): Promise<boolean> {
return this.request("isTelemetryEnabled", undefined);
}
getUniqueId(): Promise<string> {
return this.request("getUniqueId", undefined);
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return this.request("getWorkspaceConfigs", undefined);
}
async getDiff() {
return await this.request("getDiff", undefined);
}
async getTerminalContents() {
return await this.request("getTerminalContents", undefined);
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
return await this.request("listWorkspaceContents", undefined);
}
async getWorkspaceDirs(): Promise<string[]> {
return await this.request("getWorkspaceDirs", undefined);
}
async showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
return await this.request("showLines", { filepath, startLine, endLine });
}
async listFolders(): Promise<string[]> {
return await this.request("listFolders", undefined);
}
_continueDir: string | null = null;
async getContinueDir(): Promise<string> {
if (this._continueDir) {
return this._continueDir;
}
const dir = await this.request("getContinueDir", undefined);
this._continueDir = dir;
return dir;
}
async writeFile(path: string, contents: string): Promise<void> {
await this.request("writeFile", { path, contents });
}
async showVirtualFile(title: string, contents: string): Promise<void> {
await this.request("showVirtualFile", { name: title, content: contents });
}
async openFile(path: string): Promise<void> {
await this.request("openFile", { path });
}
async runCommand(command: string): Promise<void> {
await this.request("runCommand", { command });
}
async saveFile(filepath: string): Promise<void> {
await this.request("saveFile", { filepath });
}
async readFile(filepath: string): Promise<string> {
return await this.request("readFile", { filepath });
}
async showDiff(
filepath: string,
newContents: string,
stepIndex: number
): Promise<void> {
await this.request("showDiff", { filepath, newContents, stepIndex });
}
getOpenFiles(): Promise<string[]> {
return this.request("getOpenFiles", undefined);
}
getPinnedFiles(): Promise<string[]> {
return this.request("getPinnedFiles", undefined);
}
getSearchResults(query: string): Promise<string> {
return this.request("getSearchResults", { query });
}
getProblems(filepath?: string | undefined): Promise<Problem[]> {
return this.request("getProblems", { filepath });
}
subprocess(command: string): Promise<[string, string]> {
return this.request("subprocess", { command });
}
async getBranch(dir: string): Promise<string> {
return this.request("getBranch", { dir });
}
}

View file

@ -1,4 +1,4 @@
import { ContinueRcJson, IDE, Problem, Range } from "core";
import { MessageIde } from "core/util/messageIde";
import { WebviewProtocol } from "core/web/webviewProtocol";
import { ideRequest } from "./ide";
function r<T extends keyof WebviewProtocol>(
@ -7,115 +7,9 @@ function r<T extends keyof WebviewProtocol>(
): Promise<WebviewProtocol[T][1]> {
return ideRequest(messageType, data);
}
export class WebviewIde implements IDE {
readRangeInFile(filepath: string, range: Range): Promise<string> {
return r("readRangeInFile", { filepath, range });
}
getStats(directory: string): Promise<{ [path: string]: number }> {
throw new Error("Method not implemented.");
}
isTelemetryEnabled(): Promise<boolean> {
return r("isTelemetryEnabled", undefined);
}
getUniqueId(): Promise<string> {
return r("getUniqueId", undefined);
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return r("getWorkspaceConfigs", undefined);
}
async getDiff() {
return await r("getDiff", undefined);
}
async getTerminalContents() {
return await r("getTerminalContents", undefined);
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
return await r("listWorkspaceContents", undefined);
}
async getWorkspaceDirs(): Promise<string[]> {
return await r("getWorkspaceDirs", undefined);
}
async showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
return await r("showLines", { filepath, startLine, endLine });
}
async listFolders(): Promise<string[]> {
return await r("listFolders", undefined);
}
_continueDir: string | null = null;
async getContinueDir(): Promise<string> {
if (this._continueDir) {
return this._continueDir;
}
const dir = await r("getContinueDir", undefined);
this._continueDir = dir;
return dir;
}
async writeFile(path: string, contents: string): Promise<void> {
await r("writeFile", { path, contents });
}
async showVirtualFile(title: string, contents: string): Promise<void> {
await r("showVirtualFile", { name: title, content: contents });
}
async openFile(path: string): Promise<void> {
await r("openFile", { path });
}
async runCommand(command: string): Promise<void> {
await r("runCommand", { command });
}
async saveFile(filepath: string): Promise<void> {
await r("saveFile", { filepath });
}
async readFile(filepath: string): Promise<string> {
return await r("readFile", { filepath });
}
async showDiff(
filepath: string,
newContents: string,
stepIndex: number
): Promise<void> {
await r("showDiff", { filepath, newContents, stepIndex });
}
getOpenFiles(): Promise<string[]> {
return r("getOpenFiles", undefined);
}
getPinnedFiles(): Promise<string[]> {
return r("getPinnedFiles", undefined);
}
getSearchResults(query: string): Promise<string> {
return r("getSearchResults", { query });
}
getProblems(filepath?: string | undefined): Promise<Problem[]> {
return r("getProblems", { filepath });
}
subprocess(command: string): Promise<[string, string]> {
return r("subprocess", { command });
}
async getBranch(dir: string): Promise<string> {
return r("getBranch", { dir });
export class WebviewIde extends MessageIde {
constructor() {
super(r);
}
}

View file

@ -10,7 +10,9 @@
],
"assets": [
"../core/node_modules/sqlite3/**/*",
"node_modules/@lancedb/**/*"
"node_modules/@lancedb/**/*",
"out/tree-sitter.wasm",
"out/tree-sitter-wasms/*"
],
"targets": [
"node18-darwin-arm64"

View file

@ -1,114 +1,8 @@
import { Chunk, ContinueRcJson, IDE, Problem, Range } from "../../core";
import { MessageIde } from "core/util/messageIde";
import { IpcMessenger } from "./messenger";
export class IpcIde implements IDE {
private messenger: IpcMessenger;
export class IpcIde extends MessageIde {
constructor(messenger: IpcMessenger) {
this.messenger = messenger;
}
readRangeInFile(filepath: string, range: Range): Promise<string> {
throw new Error("Method not implemented.");
}
getStats(directory: string): Promise<{ [path: string]: number }> {
throw new Error("Method not implemented.");
}
isTelemetryEnabled(): Promise<boolean> {
throw new Error("Method not implemented.");
}
getUniqueId(): Promise<string> {
throw new Error("Method not implemented.");
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
throw new Error("Method not implemented.");
}
getDiff(): Promise<string> {
throw new Error("Method not implemented.");
}
getTerminalContents(): Promise<string> {
throw new Error("Method not implemented.");
}
listWorkspaceContents(directory?: string | undefined): Promise<string[]> {
throw new Error("Method not implemented.");
}
listFolders(): Promise<string[]> {
throw new Error("Method not implemented.");
}
getWorkspaceDirs(): Promise<string[]> {
throw new Error("Method not implemented.");
}
writeFile(path: string, contents: string): Promise<void> {
throw new Error("Method not implemented.");
}
showVirtualFile(title: string, contents: string): Promise<void> {
throw new Error("Method not implemented.");
}
getContinueDir(): Promise<string> {
throw new Error("Method not implemented.");
}
openFile(path: string): Promise<void> {
throw new Error("Method not implemented.");
}
runCommand(command: string): Promise<void> {
throw new Error("Method not implemented.");
}
saveFile(filepath: string): Promise<void> {
throw new Error("Method not implemented.");
}
readFile(filepath: string): Promise<string> {
throw new Error("Method not implemented.");
}
showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
throw new Error("Method not implemented.");
}
showDiff(
filepath: string,
newContents: string,
stepIndex: number
): Promise<void> {
throw new Error("Method not implemented.");
}
getOpenFiles(): Promise<string[]> {
throw new Error("Method not implemented.");
}
getPinnedFiles(): Promise<string[]> {
throw new Error("Method not implemented.");
}
getSearchResults(query: string): Promise<string> {
throw new Error("Method not implemented.");
}
subprocess(command: string): Promise<[string, string]> {
throw new Error("Method not implemented.");
}
getProblems(filepath?: string | undefined): Promise<Problem[]> {
throw new Error("Method not implemented.");
}
getBranch(dir: string): Promise<string> {
throw new Error("Method not implemented.");
}
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
throw new Error("Method not implemented.");
}
sendEmbeddingForChunk(
chunk: Chunk,
embedding: number[],
tags: string[]
): void {
throw new Error("Method not implemented.");
}
retrieveChunks(
text: string,
n: number,
directory: string | undefined
): Promise<Chunk[]> {
throw new Error("Method not implemented.");
super(messenger.request);
}
}

View file

@ -7,10 +7,11 @@ import { CodebaseIndexer } from "core/indexing/indexCodebase";
import { logDevData } from "core/util/devdata";
import historyManager from "core/util/history";
import { v4 as uuidv4 } from "uuid";
import { Messenger, Protocol } from "./messenger";
import { IpcMessenger } from "./messenger";
import { Protocol } from "./protocol";
export class Core {
private messenger: Messenger;
private messenger: IpcMessenger;
private readonly ide: IDE;
private readonly configHandler: ConfigHandler;
private readonly codebaseIndexer: CodebaseIndexer;
@ -25,13 +26,13 @@ export class Core {
return await this.configHandler.llmFromTitle(this.selectedModelTitle);
}
constructor(messenger: Messenger, ide: IDE) {
constructor(messenger: IpcMessenger, ide: IDE) {
this.messenger = messenger;
this.ide = ide;
this.configHandler = new ConfigHandler(this.ide);
this.codebaseIndexer = new CodebaseIndexer(this.configHandler, this.ide);
const on = this.messenger.on;
const on = this.messenger.on.bind(this.messenger);
// New
on("update/modelChange", (msg) => {

View file

@ -1,114 +1,13 @@
import { v4 as uuidv4 } from "uuid";
import {
ChatMessage,
CompletionOptions,
ContextItem,
ContextSubmenuItem,
PersistedSessionInfo,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
} from "../../core";
import { Message } from "../../core/util/messenger";
import { Protocol } from "./protocol";
export abstract class Messenger {
abstract send(messageType: string, message: any, messageId?: string): string;
abstract on<T extends keyof Protocol>(
messageType: T,
handler: (message: Message<Protocol[T][0]>) => Protocol[T][1]
): void;
abstract invoke<T extends keyof Protocol>(
messageType: T,
data: Protocol[T][0]
): Protocol[T][1];
}
export type Protocol = {
// New
"update/modelChange": [string, void];
// Special
abort: [undefined, void];
// History
"history/list": [undefined, SessionInfo[]];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, PersistedSessionInfo];
"history/save": [PersistedSessionInfo, void];
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
{ model: SerializedContinueConfig["models"][number] },
void,
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, void];
"context/getContextItems": [
{
name: string;
query: string;
fullInput: string;
selectedCode: RangeInFile[];
},
Promise<ContextItem[]>,
];
"context/loadSubmenuItems": [
{ title: string },
Promise<ContextSubmenuItem[]>,
];
"context/addDocs": [{ title: string; url: string }, void];
"autocomplete/complete": [
{ filepath: string; line: number; column: number },
string[],
];
"command/run": [
{
input: string;
history: ChatMessage[];
modelTitle: string;
slashCommandName: string;
contextItems: ContextItem[];
params: any;
historyIndex: number;
},
AsyncGenerator<string>,
];
"llm/complete": [
{
prompt: string;
completionOptions: CompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
"llm/streamComplete": [
{
prompt: string;
completionOptions: CompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
"llm/streamChat": [
{
messages: ChatMessage[];
completionOptions: CompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
};
type ProtocolKeys = keyof Protocol;
type ProtocolCallbacks = {
[K in ProtocolKeys]: (msg: Protocol[K][0]) => Protocol[K][1];
};
export class IpcMessenger extends Messenger {
listeners = new Map<keyof Protocol, ((message: Message) => any)[]>();
export class IpcMessenger {
typeListeners = new Map<keyof Protocol, ((message: Message) => any)[]>();
idListeners = new Map<string, (message: Message) => any>();
constructor() {
super();
console.log = console.error;
process.stdin.on("data", (data) => {
@ -123,10 +22,14 @@ export class IpcMessenger extends Messenger {
throw new Error("Invalid message sent: " + JSON.stringify(msg));
}
this.listeners.get(msg.messageType)?.forEach(async (handler) => {
// Call handler and respond with return value
this.typeListeners.get(msg.messageType)?.forEach(async (handler) => {
const response = await handler(msg);
this.send(msg.messageType, response, msg.messageId);
});
// Call handler which is waiting for the response, nothing to return
this.idListeners.get(msg.messageId)?.(msg);
} catch (e) {
console.error("Invalid JSON:", d);
return;
@ -150,20 +53,32 @@ export class IpcMessenger extends Messenger {
messageType: T,
handler: (message: Message<Protocol[T][0]>) => Protocol[T][1]
): void {
if (!this.listeners.has(messageType)) {
this.listeners.set(messageType, []);
if (!this.typeListeners.has(messageType)) {
this.typeListeners.set(messageType, []);
}
this.listeners.get(messageType)?.push(handler);
this.typeListeners.get(messageType)?.push(handler);
}
invoke<T extends keyof Protocol>(
messageType: T,
data: Protocol[T][0]
): Protocol[T][1] {
return this.listeners.get(messageType)?.[0]?.({
return this.typeListeners.get(messageType)?.[0]?.({
messageId: uuidv4(),
messageType,
data,
});
}
request(messageType: string, data: any): Promise<any> {
const messageId = uuidv4();
return new Promise((resolve) => {
const handler = (msg: Message) => {
resolve(msg.data);
this.idListeners.delete(messageId);
};
this.idListeners.set(messageId, handler);
this.send(messageType, data, messageId);
});
}
}

85
pkg/src/protocol.ts Normal file
View file

@ -0,0 +1,85 @@
import {
ChatMessage,
CompletionOptions,
ContextItem,
ContextSubmenuItem,
PersistedSessionInfo,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
} from "../../core";
export type Protocol = {
// New
"update/modelChange": [string, void];
// Special
abort: [undefined, void];
// History
"history/list": [undefined, SessionInfo[]];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, PersistedSessionInfo];
"history/save": [PersistedSessionInfo, void];
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
{ model: SerializedContinueConfig["models"][number] },
void,
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, void];
"context/getContextItems": [
{
name: string;
query: string;
fullInput: string;
selectedCode: RangeInFile[];
},
Promise<ContextItem[]>,
];
"context/loadSubmenuItems": [
{ title: string },
Promise<ContextSubmenuItem[]>,
];
"context/addDocs": [{ title: string; url: string }, void];
"autocomplete/complete": [
{ filepath: string; line: number; column: number },
string[],
];
"command/run": [
{
input: string;
history: ChatMessage[];
modelTitle: string;
slashCommandName: string;
contextItems: ContextItem[];
params: any;
historyIndex: number;
},
AsyncGenerator<string>,
];
"llm/complete": [
{
prompt: string;
completionOptions: CompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
"llm/streamComplete": [
{
prompt: string;
completionOptions: CompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
"llm/streamChat": [
{
messages: ChatMessage[];
completionOptions: CompletionOptions;
title: string;
},
AsyncGenerator<string>,
];
};