🚧 slash commands and history
This commit is contained in:
parent
4ce9df38c1
commit
5168eaf4a4
19 changed files with 625 additions and 61 deletions
38
core/commands/cmd.ts
Normal file
38
core/commands/cmd.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { SlashCommand } from ".";
|
||||
import { removeQuotesAndEscapes } from "../util";
|
||||
|
||||
`
|
||||
cmd = await sdk.models.default.complete(
|
||||
dedent(
|
||||
f"""\
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
cmd = remove_quotes_and_escapes(cmd.strip()).replace("\n", "").replace("\r", "")
|
||||
|
||||
await sdk.ide.runCommand(cmd)
|
||||
|
||||
yield SetStep(description=f"Generated shell command: {cmd}")
|
||||
|
||||
`;
|
||||
|
||||
const GenerateTerminalCommand: SlashCommand = {
|
||||
name: "cmd",
|
||||
description: "Generate a shell command",
|
||||
run: async function* ({ ide, llm, input }) {
|
||||
let cmd =
|
||||
await llm.complete(`The user has made a request to run a shell command. Their description of what it should do is:
|
||||
|
||||
"${input}"
|
||||
|
||||
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested.`);
|
||||
cmd = removeQuotesAndEscapes(cmd.trim())
|
||||
.replace("\n", "")
|
||||
.replace("\r", "");
|
||||
await ide.runCommand(cmd);
|
||||
yield `Generated shell command: ${cmd}`;
|
||||
},
|
||||
};
|
||||
|
||||
export default GenerateTerminalCommand;
|
||||
56
core/commands/draftIssue.ts
Normal file
56
core/commands/draftIssue.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { ContinueSDK, SlashCommand } from ".";
|
||||
import { ChatMessage } from "../llm/types";
|
||||
import { removeQuotesAndEscapes } from "../util";
|
||||
|
||||
const PROMPT = (
|
||||
input: string,
|
||||
title: string
|
||||
) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules:
|
||||
- Be descriptive but do not make up details
|
||||
- If the the user request includes any code snippets that are relevant, reference them in code blocks
|
||||
- Describe step by step how to reproduce the problem
|
||||
- Describe the ideal solution to the problem
|
||||
- Describe the expected behavior after the issue has been resolved
|
||||
- This issue will be read by a team member
|
||||
- Use markdown formatting, but you do not need to surround the entire body with triple backticks
|
||||
{additional_instructions}
|
||||
|
||||
Here is the user request: '${input}'
|
||||
|
||||
Title: ${title}
|
||||
|
||||
Body:\n\n`;
|
||||
|
||||
const DraftIssueCommand: SlashCommand = {
|
||||
name: "issue",
|
||||
description: "Draft a GitHub issue",
|
||||
run: async function* ({ input, llm, history, options }) {
|
||||
if (options?.repositoryUrl === undefined) {
|
||||
yield "This command requires a repository URL to be set in the config file.";
|
||||
return;
|
||||
}
|
||||
const title = await llm.complete(
|
||||
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
|
||||
{ maxTokens: 20 }
|
||||
);
|
||||
|
||||
yield removeQuotesAndEscapes(title) + "\n\n";
|
||||
|
||||
let body = "";
|
||||
const messages: ChatMessage[] = [
|
||||
...history,
|
||||
{ role: "user", content: PROMPT(input, title) },
|
||||
];
|
||||
|
||||
for await (const chunk of llm.streamChat(messages)) {
|
||||
body += chunk.content;
|
||||
yield chunk.content;
|
||||
}
|
||||
|
||||
// const url = f"{self.repository_url}/issues/new?title={quote(title)}&body={quote(body)}"
|
||||
const url = `${options.repositoryUrl}/issues/new?title={encodeURIComponent(title)}&body={encodeURIComponent(body)}`;
|
||||
yield `\n\n[Link to draft of issue](${url})`;
|
||||
},
|
||||
};
|
||||
|
||||
export default DraftIssueCommand;
|
||||
46
core/commands/index.ts
Normal file
46
core/commands/index.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { CustomCommand } from "../config";
|
||||
import { IDE } from "../ide/types";
|
||||
import { LLM } from "../llm";
|
||||
import { ChatMessage, ContextItem } from "../llm/types";
|
||||
|
||||
export interface ContinueSDK {
|
||||
ide: IDE;
|
||||
llm: LLM;
|
||||
addContextItem: (item: ContextItem) => void;
|
||||
history: ChatMessage[];
|
||||
input: string;
|
||||
options?: any;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
name: string;
|
||||
description: string;
|
||||
run: (sdk: ContinueSDK) => AsyncGenerator<string>;
|
||||
}
|
||||
|
||||
export function slashFromCustomCommand(
|
||||
customCommand: CustomCommand
|
||||
): SlashCommand {
|
||||
return {
|
||||
name: customCommand.name,
|
||||
description: customCommand.description,
|
||||
run: async function* ({ input, llm, history }) {
|
||||
const promptUserInput = `Task: ${customCommand.prompt}. Additional info: ${input}`;
|
||||
const messages = [...history];
|
||||
// Find the last chat message with this slash command and replace it with the user input
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (
|
||||
messages[i].role === "user" &&
|
||||
messages[i].content.startsWith(`/${customCommand.name}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: promptUserInput };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of llm.streamChat(messages)) {
|
||||
yield chunk.content;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
24
core/commands/share.ts
Normal file
24
core/commands/share.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { SlashCommand } from ".";
|
||||
|
||||
const ShareSlashCommand: SlashCommand = {
|
||||
name: "share",
|
||||
description: "Download and share this session",
|
||||
run: async function* ({ ide, history }) {
|
||||
let content = `This is a session transcript from [Continue](https://continue.dev) on ${new Date().toLocaleString()}.`;
|
||||
|
||||
for (const msg of history) {
|
||||
content += `\n\n## ${msg.role === "user" ? "User" : "Continue"}\n\n${
|
||||
msg.content
|
||||
}`;
|
||||
}
|
||||
|
||||
const continueDir = await ide.getContinueDir();
|
||||
const path = `${continueDir}/session.md`;
|
||||
await ide.writeFile(path, content);
|
||||
await ide.openFile(path);
|
||||
|
||||
yield `The session transcript has been saved to a markdown file at \`${path}\`.`;
|
||||
},
|
||||
};
|
||||
|
||||
export default ShareSlashCommand;
|
||||
116
core/commands/stackOverflow.ts
Normal file
116
core/commands/stackOverflow.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import { SlashCommand } from ".";
|
||||
import { pruneStringFromBottom } from "../llm/countTokens";
|
||||
import { ChatMessageRole } from "../llm/types";
|
||||
|
||||
const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app";
|
||||
const PROMPT = (
|
||||
input: string
|
||||
) => `The above sources are excerpts from related StackOverflow questions. Use them to help answer the below question from our user. Provide links to the sources in markdown whenever possible:
|
||||
|
||||
${input}
|
||||
`;
|
||||
|
||||
async function getResults(q: string): Promise<any> {
|
||||
const payload = JSON.stringify({
|
||||
q: `${q} site:stackoverflow.com`,
|
||||
});
|
||||
|
||||
const resp = await fetch(`${SERVER_URL}/search`, {
|
||||
method: "POST",
|
||||
body: payload,
|
||||
});
|
||||
return await resp.json();
|
||||
}
|
||||
|
||||
async function fetchData(url: string): Promise<string | undefined> {
|
||||
const response = await fetch(url);
|
||||
const htmlString = await response.text();
|
||||
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(htmlString, "text/html");
|
||||
|
||||
const h1 = doc.querySelector("h1.fs-headline1");
|
||||
const title = h1?.textContent?.trim() || "No Title";
|
||||
|
||||
const bodies = doc.querySelectorAll("div.js-post-body");
|
||||
if (bodies.length < 2) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const question = bodies[0].textContent || "";
|
||||
const answer = bodies[1].textContent || "";
|
||||
|
||||
return `
|
||||
# Question: [${title}](${url})
|
||||
|
||||
${question}
|
||||
|
||||
# Best Answer
|
||||
|
||||
${answer}
|
||||
`;
|
||||
}
|
||||
|
||||
const StackOverflowSlashCommand: SlashCommand = {
|
||||
name: "so",
|
||||
description: "Search Stack Overflow",
|
||||
run: async function* ({ llm, input, addContextItem, history }) {
|
||||
const contextLength = llm.contextLength;
|
||||
|
||||
const sources: string[] = [];
|
||||
const results = await getResults(input);
|
||||
const links = results.organic.map((result: any) => result.link);
|
||||
let totalTokens = llm.countTokens(input) + 200;
|
||||
|
||||
for (const link of links) {
|
||||
const contents = await fetchData(link);
|
||||
if (!contents) {
|
||||
continue;
|
||||
}
|
||||
sources.push(contents);
|
||||
const newTokens = llm.countTokens(contents);
|
||||
totalTokens += newTokens;
|
||||
|
||||
let shouldBreak = false;
|
||||
if (totalTokens > contextLength) {
|
||||
sources[sources.length - 1] = pruneStringFromBottom(
|
||||
llm.model,
|
||||
contextLength - (totalTokens - newTokens),
|
||||
sources[sources.length - 1]
|
||||
);
|
||||
shouldBreak = true;
|
||||
}
|
||||
|
||||
if (sources.length >= 3) {
|
||||
shouldBreak = true;
|
||||
}
|
||||
|
||||
addContextItem({
|
||||
content: sources[sources.length - 1],
|
||||
description: "StackOverflow Answer",
|
||||
name: `StackOverflow ${sources.length}`,
|
||||
id: {
|
||||
providerTitle: "so",
|
||||
itemId: links[sources.length - 1],
|
||||
},
|
||||
});
|
||||
|
||||
if (shouldBreak) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of llm.streamChat([
|
||||
...history,
|
||||
...sources.map((source) => ({
|
||||
role: "user" as ChatMessageRole,
|
||||
content: source,
|
||||
})),
|
||||
{ role: "user", content: PROMPT(input) },
|
||||
])) {
|
||||
yield chunk.content;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default StackOverflowSlashCommand;
|
||||
|
|
@ -1,29 +1,53 @@
|
|||
import { ideRequest } from "./messaging";
|
||||
import { IDE } from "./types";
|
||||
|
||||
async function r(messageType: string, options: any = {}) {
|
||||
return await ideRequest(messageType, options);
|
||||
}
|
||||
export class ExtensionIde implements IDE {
|
||||
async getSerializedConfig() {
|
||||
const resp = await ideRequest("getSerializedConfig", {});
|
||||
return resp.config;
|
||||
return await r("getSerializedConfig");
|
||||
}
|
||||
|
||||
async getDiff() {
|
||||
const resp = await ideRequest("getDiff", {});
|
||||
return resp.diff;
|
||||
return await r("getDiff");
|
||||
}
|
||||
|
||||
async getTerminalContents() {
|
||||
const resp = await ideRequest("getTerminalContents", {});
|
||||
return resp.terminalContents;
|
||||
return await r("getTerminalContents");
|
||||
}
|
||||
|
||||
async listWorkspaceContents(): Promise<string[]> {
|
||||
const resp = await ideRequest("listWorkspaceContents", {});
|
||||
return resp.workspaceContents;
|
||||
return await r("listWorkspaceContents");
|
||||
}
|
||||
|
||||
async getWorkspaceDir(): Promise<string> {
|
||||
const resp = await ideRequest("getWorkspaceDir", {});
|
||||
return resp.workspaceDir;
|
||||
return await r("getWorkspaceDir");
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await r("getContinueDir");
|
||||
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", { title, contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await r("openFile", { path });
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await r("runCommand", { command });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import "vscode-webview";
|
||||
// import "vscode-webview";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
interface vscode {
|
||||
postMessage(message: any): vscode;
|
||||
}
|
||||
|
||||
declare const vscode: any;
|
||||
|
||||
|
|
@ -42,16 +47,19 @@ export function postToIde(type: string, data: any, attempt: number = 0) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function ideRequest(type: string, data: any): Promise<any> {
|
||||
// TODO: Use UUID
|
||||
export async function ideRequest(type: string, message: any): Promise<any> {
|
||||
// message, messageId, and type are passed back and forth
|
||||
const messageId = uuidv4();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const handler = (event: any) => {
|
||||
if (event.data.type === type) {
|
||||
if (event.data.messageId === messageId) {
|
||||
window.removeEventListener("message", handler);
|
||||
resolve(event.data);
|
||||
resolve(event.data.message);
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
postToIde(type, data);
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
});
|
||||
}
|
||||
|
|
|
|||
5
core/ide/types.d.ts
vendored
5
core/ide/types.d.ts
vendored
|
|
@ -6,6 +6,11 @@ interface IDE {
|
|||
getTerminalContents(): Promise<string>;
|
||||
listWorkspaceContents(): Promise<string[]>;
|
||||
getWorkspaceDir(): Promise<string>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
openFile(path: string): Promise<void>;
|
||||
runCommand(command: string): Promise<void>;
|
||||
}
|
||||
|
||||
export { IDE };
|
||||
|
|
|
|||
|
|
@ -40,6 +40,27 @@ function countChatMessageTokens(
|
|||
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
|
||||
}
|
||||
|
||||
function pruneStringFromBottom(
|
||||
modelName: string,
|
||||
maxTokens: number,
|
||||
prompt: string
|
||||
): string {
|
||||
// TODO: Tiktoken
|
||||
// const encoding = encodingForModel(modelName);
|
||||
|
||||
// if (encoding === null) {
|
||||
const desiredLengthInChars = maxTokens * 2;
|
||||
return prompt.slice(0, desiredLengthInChars);
|
||||
// }
|
||||
|
||||
// const tokens = encoding.encode(prompt, { disallowedSpecial: [] });
|
||||
// if (tokens.length <= maxTokens) {
|
||||
// return prompt;
|
||||
// }
|
||||
|
||||
// return encoding.decode(tokens.slice(-maxTokens));
|
||||
}
|
||||
|
||||
function pruneStringFromTop(
|
||||
modelName: string,
|
||||
maxTokens: number,
|
||||
|
|
@ -236,4 +257,9 @@ function compileChatMessages(
|
|||
return flattenedHistory;
|
||||
}
|
||||
|
||||
export { compileChatMessages, pruneRawPromptFromTop, countTokens };
|
||||
export {
|
||||
compileChatMessages,
|
||||
pruneRawPromptFromTop,
|
||||
countTokens,
|
||||
pruneStringFromBottom,
|
||||
};
|
||||
|
|
|
|||
22
core/package-lock.json
generated
22
core/package-lock.json
generated
|
|
@ -12,10 +12,12 @@
|
|||
"@anthropic-ai/sdk": "^0.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"openai": "^4.20.1",
|
||||
"replicate": "^0.23.0"
|
||||
"replicate": "^0.23.0",
|
||||
"uuid": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.11",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.1.1"
|
||||
}
|
||||
|
|
@ -1219,6 +1221,12 @@
|
|||
"integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/uuid": {
|
||||
"version": "9.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.7.tgz",
|
||||
"integrity": "sha512-WUtIVRUZ9i5dYXefDEAI7sh9/O7jGvHg7Df/5O/gtH3Yabe5odI3UWopVR1qbPXQtvOxWu3mM4XxlYeZtMWF4g==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/yargs": {
|
||||
"version": "17.0.32",
|
||||
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz",
|
||||
|
|
@ -4060,6 +4068,18 @@
|
|||
"browserslist": ">= 4.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "9.0.1",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
|
||||
"integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-compile-cache-lib": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.11",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.1.1"
|
||||
},
|
||||
|
|
@ -17,6 +18,7 @@
|
|||
"@anthropic-ai/sdk": "^0.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"openai": "^4.20.1",
|
||||
"replicate": "^0.23.0"
|
||||
"replicate": "^0.23.0",
|
||||
"uuid": "^9.0.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
24
core/util/index.ts
Normal file
24
core/util/index.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
export function removeQuotesAndEscapes(output: string): string {
|
||||
output = output.trim();
|
||||
|
||||
// Replace smart quotes
|
||||
output = output.replace("“", '"');
|
||||
output = output.replace("”", '"');
|
||||
output = output.replace("‘", "'");
|
||||
output = output.replace("’", "'");
|
||||
|
||||
// Remove escapes
|
||||
output = output.replace('\\"', '"');
|
||||
output = output.replace("\\'", "'");
|
||||
output = output.replace("\\n", "\n");
|
||||
output = output.replace("\\t", "\t");
|
||||
output = output.replace("\\\\", "\\");
|
||||
if (
|
||||
(output.startsWith('"') && output.endsWith('"')) ||
|
||||
(output.startsWith("'") && output.endsWith("'"))
|
||||
) {
|
||||
output = output.slice(1, -1);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
|
@ -55,6 +55,22 @@ export function getContinueGlobalPath(): string {
|
|||
return continuePath;
|
||||
}
|
||||
|
||||
export function getSessionsFolderPath(): string {
|
||||
const sessionsPath = path.join(getContinueGlobalPath(), "sessions");
|
||||
if (!fs.existsSync(sessionsPath)) {
|
||||
fs.mkdirSync(sessionsPath);
|
||||
}
|
||||
return sessionsPath;
|
||||
}
|
||||
|
||||
export function getSessionFilePath(sessionId: string): string {
|
||||
return path.join(getSessionsFolderPath(), `${sessionId}.json`);
|
||||
}
|
||||
|
||||
export function getSessionsListPath(): string {
|
||||
return path.join(getSessionsFolderPath(), "sessions.json");
|
||||
}
|
||||
|
||||
export function getConfigJsonPath(): string {
|
||||
// TODO: Create if it doesn't exist
|
||||
return path.join(getContinueGlobalPath(), "config.json");
|
||||
|
|
|
|||
|
|
@ -98,6 +98,14 @@ export function getSidebarContent(
|
|||
}
|
||||
|
||||
panel.webview.onDidReceiveMessage(async (data) => {
|
||||
const ide = new VsCodeIde();
|
||||
const respond = (message: any) => {
|
||||
panel.webview.postMessage({
|
||||
type: data.type,
|
||||
messageId: data.messageId,
|
||||
message: message || {},
|
||||
});
|
||||
};
|
||||
switch (data.type) {
|
||||
case "websocketForwardingOpen": {
|
||||
let url = data.url;
|
||||
|
|
@ -230,48 +238,43 @@ export function getSidebarContent(
|
|||
break;
|
||||
}
|
||||
case "getDiff": {
|
||||
new VsCodeIde().getDiff().then((diff) => {
|
||||
panel.webview.postMessage({
|
||||
type: "getDiff",
|
||||
diff,
|
||||
});
|
||||
});
|
||||
respond(await ide.getDiff());
|
||||
break;
|
||||
}
|
||||
case "getSerializedConfig": {
|
||||
new VsCodeIde().getSerializedConfig().then((config) => {
|
||||
panel.webview.postMessage({
|
||||
type: "getSerializedConfig",
|
||||
config,
|
||||
});
|
||||
});
|
||||
respond(await ide.getSerializedConfig());
|
||||
break;
|
||||
}
|
||||
case "getTerminalContents": {
|
||||
new VsCodeIde().getTerminalContents().then((terminalContents) => {
|
||||
panel.webview.postMessage({
|
||||
type: "getTerminalContents",
|
||||
terminalContents,
|
||||
});
|
||||
});
|
||||
respond(await ide.getTerminalContents());
|
||||
break;
|
||||
}
|
||||
case "listWorkspaceContents": {
|
||||
new VsCodeIde().listWorkspaceContents().then((workspaceContents) => {
|
||||
panel.webview.postMessage({
|
||||
type: "listWorkspaceContents",
|
||||
workspaceContents,
|
||||
});
|
||||
});
|
||||
respond(await ide.listWorkspaceContents());
|
||||
break;
|
||||
}
|
||||
case "getWorkspaceDir": {
|
||||
new VsCodeIde().getWorkspaceDir().then((workspaceDir) => {
|
||||
panel.webview.postMessage({
|
||||
type: "getWorkspaceDir",
|
||||
workspaceDir,
|
||||
});
|
||||
});
|
||||
respond(await ide.getWorkspaceDir());
|
||||
break;
|
||||
}
|
||||
case "writeFile": {
|
||||
respond(await ide.writeFile(data.path, data.contents));
|
||||
break;
|
||||
}
|
||||
case "showVirtualFile": {
|
||||
respond(await ide.showVirtualFile(data.title, data.contents));
|
||||
break;
|
||||
}
|
||||
case "getContinueDir": {
|
||||
respond(await ide.getContinueDir());
|
||||
break;
|
||||
}
|
||||
case "openFile": {
|
||||
respond(await ide.openFile(data.path));
|
||||
break;
|
||||
}
|
||||
case "runCommand": {
|
||||
respond(await ide.runCommand(data.command));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
130
extensions/vscode/src/history.ts
Normal file
130
extensions/vscode/src/history.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import {
|
||||
getContinueGlobalPath,
|
||||
getSessionFilePath,
|
||||
getSessionsListPath,
|
||||
} from "./activation/environmentSetup";
|
||||
import { ChatHistory } from "core/llm/types";
|
||||
import * as fs from "fs";
|
||||
|
||||
export interface PersistedSessionInfo {
|
||||
history: ChatHistory;
|
||||
title: string;
|
||||
workspaceDirectory: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
sessionId: string;
|
||||
title: string;
|
||||
dateCreated: string;
|
||||
workspaceDirectory: string;
|
||||
}
|
||||
|
||||
class HistoryManager {
|
||||
list(): PersistedSessionInfo[] {
|
||||
const filepath = getSessionsListPath();
|
||||
if (!fs.existsSync(filepath)) {
|
||||
return [];
|
||||
}
|
||||
const content = fs.readFileSync(filepath, "utf8");
|
||||
const sessions = JSON.parse(content);
|
||||
return sessions;
|
||||
}
|
||||
|
||||
delete(sessionId: string) {
|
||||
// Delete a session
|
||||
const sessionFile = getSessionFilePath(sessionId);
|
||||
if (!fs.existsSync(sessionFile)) {
|
||||
throw new Error(`Session file ${sessionFile} does not exist`);
|
||||
}
|
||||
fs.unlinkSync(sessionFile);
|
||||
|
||||
// Read and update the sessions list
|
||||
const sessionsListFile = getSessionsListPath();
|
||||
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
|
||||
let sessionsList: SessionInfo[];
|
||||
try {
|
||||
sessionsList = JSON.parse(sessionsListRaw);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFile}). Please fix this before creating a new session.`
|
||||
);
|
||||
}
|
||||
|
||||
sessionsList = sessionsList.filter(
|
||||
(session) => session.sessionId !== sessionId
|
||||
);
|
||||
|
||||
fs.writeFileSync(sessionsListFile, JSON.stringify(sessionsList));
|
||||
}
|
||||
|
||||
load(sessionId: string): PersistedSessionInfo {
|
||||
try {
|
||||
const sessionFile = getSessionFilePath(sessionId);
|
||||
if (!fs.existsSync(sessionFile)) {
|
||||
throw new Error(`Session file ${sessionFile} does not exist`);
|
||||
}
|
||||
const session: PersistedSessionInfo = JSON.parse(
|
||||
fs.readFileSync(sessionFile, "utf8")
|
||||
);
|
||||
session.sessionId = sessionId;
|
||||
return session;
|
||||
} catch (e) {
|
||||
console.log(`Error migrating session: ${e}`);
|
||||
return {
|
||||
history: [],
|
||||
title: "Failed to load session",
|
||||
workspaceDirectory: "",
|
||||
sessionId: sessionId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
save(session: PersistedSessionInfo) {
|
||||
// Save the main session json file
|
||||
fs.writeFileSync(
|
||||
getSessionFilePath(session.sessionId),
|
||||
JSON.stringify(session)
|
||||
);
|
||||
|
||||
// Read and update the sessions list
|
||||
const sessionsListFilePath = getSessionsListPath();
|
||||
try {
|
||||
const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
|
||||
const sessionsList: SessionInfo[] = JSON.parse(rawSessionsList);
|
||||
|
||||
let found = false;
|
||||
for (const sessionInfo of sessionsList) {
|
||||
if (sessionInfo.sessionId === session.sessionId) {
|
||||
sessionInfo.title = session.title;
|
||||
sessionInfo.workspaceDirectory = session.workspaceDirectory;
|
||||
sessionInfo.dateCreated = String(Date.now());
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
const sessionInfo: SessionInfo = {
|
||||
sessionId: session.sessionId,
|
||||
title: session.title,
|
||||
dateCreated: String(Date.now()),
|
||||
workspaceDirectory: session.workspaceDirectory,
|
||||
};
|
||||
sessionsList.push(sessionInfo);
|
||||
}
|
||||
|
||||
fs.writeFileSync(sessionsListFilePath, JSON.stringify(sessionsList));
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) {
|
||||
throw new Error(
|
||||
`It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session.`
|
||||
);
|
||||
} else {
|
||||
throw new Error(
|
||||
`It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,12 @@
|
|||
import { IDE } from "core/ide/types";
|
||||
import * as fs from "fs";
|
||||
import { getConfigJsonPath } from "./activation/environmentSetup";
|
||||
import {
|
||||
getConfigJsonPath,
|
||||
getContinueGlobalPath,
|
||||
} from "./activation/environmentSetup";
|
||||
import { ideProtocolClient } from "./activation/activate";
|
||||
import { SerializedContinueConfig } from "core/config/index";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
class VsCodeIde implements IDE {
|
||||
async getSerializedConfig(): Promise<SerializedContinueConfig> {
|
||||
|
|
@ -29,6 +33,29 @@ class VsCodeIde implements IDE {
|
|||
async getWorkspaceDir(): Promise<string> {
|
||||
return ideProtocolClient.getWorkspaceDirectory();
|
||||
}
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
return getContinueGlobalPath();
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await vscode.workspace.fs.writeFile(
|
||||
vscode.Uri.file(path),
|
||||
Buffer.from(contents)
|
||||
);
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
ideProtocolClient.showVirtualFile(title, contents);
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
ideProtocolClient.openFile(path);
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await ideProtocolClient.runCommand(command);
|
||||
}
|
||||
}
|
||||
|
||||
export default VsCodeIde;
|
||||
|
|
|
|||
|
|
@ -11,11 +11,11 @@ import CustomPostHogProvider from "./hooks/CustomPostHogProvider";
|
|||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<Provider store={store}>
|
||||
<PersistGate loading={null} persistor={persistor}>
|
||||
<CustomPostHogProvider>
|
||||
<App />
|
||||
</CustomPostHogProvider>
|
||||
</PersistGate>
|
||||
{/* <PersistGate loading={null} persistor={persistor}> */}
|
||||
<CustomPostHogProvider>
|
||||
<App />
|
||||
</CustomPostHogProvider>
|
||||
{/* </PersistGate> */}
|
||||
</Provider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -87,14 +87,15 @@ const persistConfig = {
|
|||
// ],
|
||||
};
|
||||
|
||||
const persistedReducer = persistReducer(persistConfig, rootReducer);
|
||||
// const persistedReducer = persistReducer(persistConfig, rootReducer);
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: persistedReducer,
|
||||
// reducer: persistedReducer,
|
||||
reducer: rootReducer,
|
||||
middleware: (getDefaultMiddleware) =>
|
||||
getDefaultMiddleware({
|
||||
serializableCheck: false,
|
||||
}),
|
||||
});
|
||||
|
||||
export const persistor = persistStore(store);
|
||||
// export const persistor = persistStore(store);
|
||||
|
|
|
|||
|
|
@ -27,13 +27,11 @@ STEP_NAMES = [
|
|||
"ClearHistoryStep",
|
||||
"StackOverflowStep",
|
||||
"OpenConfigStep",
|
||||
"GenerateShellCommandStep",
|
||||
"DraftIssueStep",
|
||||
]
|
||||
|
||||
StepName = Literal[
|
||||
"AnswerQuestionChroma",
|
||||
"GenerateShellCommandStep",
|
||||
"EditHighlightedCodeStep",
|
||||
"ShareSessionStep",
|
||||
"CommentCodeStep",
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue