fix: filepath replacements in prompt files (#1939)

* fix: filepath replacements in prompt files

* remove file extensions
This commit is contained in:
Patrick Erichsen 2024-08-06 11:31:10 -07:00 • committed by GitHub
parent 7050d76828
commit c0923a0dd7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 668 additions and 311 deletions

View file

@ -1,11 +1,7 @@
import {
CustomCommand,
SlashCommand,
SlashCommandDescription,
} from "../index.js";
import { stripImages } from "../llm/images.js";
import { renderTemplatedString } from "../llm/llms/index.js";
import SlashCommands from "./slash/index.js";
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,

View file

@ -4,8 +4,8 @@ import * as YAML from "yaml";
import type { IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../llm/llms/index";
import { getBasename } from "../util/index";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
@ -15,6 +15,7 @@ export async function getPromptFiles(
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
@ -89,6 +90,32 @@ export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand {
const { name, description, systemMessage, prompt } = parsePromptFile(
path,
content,
);
return {
name,
description,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPrompt(prompt, context, userInput);
const messages = updateChatHistory(
context.history,
name,
renderedPrompt,
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
}
function parsePromptFile(path: string, content: string) {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;
@ -105,115 +132,122 @@ export function slashCommandFromPromptFile(
prompt = prompt.split("</system>")[1].trim();
}
return {
name,
description,
run: async function* ({
input,
llm,
history,
ide,
config,
fetch,
selectedCode,
addContextItem,
}) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${name}`)) {
userInput = userInput
.slice(name.length + 1, userInput.length)
.trimStart();
}
return { name, description, systemMessage, prompt };
}
// Render prompt template
const helpers: [string, Handlebars.HelperDelegate][] | undefined =
config.contextProviders?.map((provider) => {
return [
provider.description.title,
async (context: any) => {
const items = await provider.getContextItems(context, {
config,
embeddingsProvider: config.embeddingsProvider,
fetch,
fullInput: userInput,
ide,
llm,
reranker: config.reranker,
selectedCode,
});
items.forEach((item) =>
addContextItem({
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
}),
);
return items.map((item) => item.content).join("\n\n");
},
];
});
function extractUserInput(input: string, commandName: string): string {
if (input.startsWith(`/${commandName}`)) {
return input.slice(commandName.length + 1).trimStart();
}
return input;
}
// A few context providers that don't need to be in config.json to work in .prompt files
const diff = await ide.getDiff();
const currentFilePath = await ide.getCurrentFile();
const promptUserInput = await renderTemplatedString(
prompt,
ide.readFile.bind(ide),
{
input: userInput,
diff,
currentFile: currentFilePath
? await ide.readFile(currentFilePath)
: undefined,
},
helpers,
async function renderPrompt(prompt: string, context: any, userInput: string) {
const helpers = getContextProviderHelpers(context);
// A few context providers that don't need to be in config.json to work in .prompt files
const diff = await context.ide.getDiff();
const currentFilePath = await context.ide.getCurrentFile();
const currentFile = currentFilePath
? await context.ide.readFile(currentFilePath)
: undefined;
return renderTemplatedString(
prompt,
context.ide.readFile.bind(context.ide),
{ diff, currentFile, input: userInput },
helpers,
);
}
function getContextProviderHelpers(
context: any,
): Array<[string, Handlebars.HelperDelegate]> | undefined {
return context.config.contextProviders?.map((provider: any) => [
provider.description.title,
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.embeddingsProvider,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.reranker,
selectedCode: context.selectedCode,
});
items.forEach((item: any) =>
context.addContextItem(createContextItem(item, provider)),
);
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--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
return items.map((item: any) => item.content).join("\n\n");
},
]);
}
if (
Array.isArray(content) &&
content.some((part) => part.text?.startsWith(`/${name}`))
) {
messages[i] = {
...messages[i],
content: content.map((part) => {
return part.text?.startsWith(`/${name}`)
? { ...part, text: promptUserInput }
: part;
}),
};
break;
} else if (
typeof content === "string" &&
content.startsWith(`/${name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
break;
}
}
// System message
if (systemMessage) {
if (messages[0]?.role === "system") {
messages[0].content = systemMessage;
} else {
messages.unshift({ role: "system", content: systemMessage });
}
}
for await (const chunk of llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
function createContextItem(item: any, provider: any) {
return {
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
};
}
function updateChatHistory(
history: any[],
commandName: string,
renderedPrompt: string,
systemMessage?: string,
) {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (Array.isArray(content)) {
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
messages[i] = updateArrayContent(
messages[i],
commandName,
renderedPrompt,
);
break;
}
} else if (
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
break;
}
}
if (systemMessage) {
messages[0]?.role === "system"
? (messages[0].content = systemMessage)
: messages.unshift({ role: "system", content: systemMessage });
}
return messages;
}
function updateArrayContent(
message: any,
commandName: string,
renderedPrompt: string,
) {
return {
...message,
content: message.content.map((part: any) =>
part.text?.startsWith(`/${commandName}`)
? { ...part, text: renderedPrompt }
: part,
),
};
}

View file

@ -1,105 +1,39 @@
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
import {
BaseCompletionOptions,
IdeSettings,
ILLM,
LLMOptions,
ModelDescription,
} from "../../index.js";
import { DEFAULT_MAX_TOKENS } from "../constants.js";
import { BaseLLM } from "../index.js";
import Anthropic from "./Anthropic.js";
import Bedrock from "./Bedrock.js";
import Cloudflare from "./Cloudflare.js";
import Cohere from "./Cohere.js";
import DeepInfra from "./DeepInfra.js";
import Deepseek from "./Deepseek.js";
import Fireworks from "./Fireworks.js";
import Flowise from "./Flowise.js";
import FreeTrial from "./FreeTrial.js";
import Gemini from "./Gemini.js";
import Groq from "./Groq.js";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI.js";
import HuggingFaceTGI from "./HuggingFaceTGI.js";
import LMStudio from "./LMStudio.js";
import LlamaCpp from "./LlamaCpp.js";
import Llamafile from "./Llamafile.js";
import Mistral from "./Mistral.js";
import Msty from "./Msty.js";
import Azure from "./Azure.js";
import Ollama from "./Ollama.js";
import OpenAI from "./OpenAI.js";
import Replicate from "./Replicate.js";
import TextGenWebUI from "./TextGenWebUI.js";
import Together from "./Together.js";
import ContinueProxy from "./stubs/ContinueProxy.js";
import WatsonX from "./WatsonX.js";
function convertToLetter(num: number): string {
let result = "";
while (num > 0) {
const remainder = (num - 1) % 26;
result = String.fromCharCode(97 + remainder) + result;
num = Math.floor((num - 1) / 26);
}
return result;
}
const getHandlebarsVars = (
value: string,
): [string, { [key: string]: string }] => {
const ast = Handlebars.parse(value);
const keysToFilepath: { [key: string]: string } = {};
let keyIndex = 1;
for (const i in ast.body) {
if (ast.body[i].type === "MustacheStatement") {
const letter = convertToLetter(keyIndex);
keysToFilepath[letter] = (ast.body[i] as any).path.original;
value = value.replace(
new RegExp(`{{\\s*${(ast.body[i] as any).path.original}\\s*}}`),
`{{${letter}}}`,
);
keyIndex++;
}
}
return [value, keysToFilepath];
};
export async function renderTemplatedString(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
helpers?: [string, Handlebars.HelperDelegate][],
): Promise<string> {
const promises: { [key: string]: Promise<string> } = {};
if (helpers) {
for (const [name, helper] of helpers) {
Handlebars.registerHelper(name, (...args) => {
const id = uuidv4();
promises[id] = helper(...args);
return `__${id}__`;
});
}
}
const [newTemplate, vars] = getHandlebarsVars(template);
const data: any = { ...inputData };
for (const key in vars) {
const fileContents = await readFile(vars[key]);
data[key] = fileContents || (inputData[vars[key]] ?? vars[key]);
}
const templateFn = Handlebars.compile(newTemplate);
let final = templateFn(data);
await Promise.all(Object.values(promises));
for (const id in promises) {
final = final.replace(`__${id}__`, await promises[id]);
}
return final;
}
} from "../..";
import { DEFAULT_MAX_TOKENS } from "../constants";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Bedrock from "./Bedrock";
import Cloudflare from "./Cloudflare";
import Cohere from "./Cohere";
import DeepInfra from "./DeepInfra";
import Deepseek from "./Deepseek";
import Fireworks from "./Fireworks";
import Flowise from "./Flowise";
import FreeTrial from "./FreeTrial";
import Gemini from "./Gemini";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTGI from "./HuggingFaceTGI";
import LMStudio from "./LMStudio";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import Mistral from "./Mistral";
import Msty from "./Msty";
import Azure from "./Azure";
import Ollama from "./Ollama";
import OpenAI from "./OpenAI";
import Replicate from "./Replicate";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import ContinueProxy from "./stubs/ContinueProxy";
import WatsonX from "./WatsonX";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
const LLMs = [
Anthropic,
@ -127,7 +61,7 @@ const LLMs = [
Deepseek,
Msty,
Azure,
WatsonX
WatsonX,
];
export async function llmFromDescription(

View file

@ -0,0 +1,57 @@
import path from "path";
import { IDE } from "..";
import { DEFAULT_PROMPTS_FOLDER } from "./";
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue
# Continue will automatically create a slash command for each prompt in the .prompts folder
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
temperature: 0.0
---
{{{ diff }}}
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
- If you found any problems, an h3 like "❌ <filename>"
- If you didn't find any problems, an h3 like "✅ <filename>"
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
- If you didn't find any problems, you don't need to add anything else
Here is an example. The example is surrounded in backticks, but your response should not be:
\`\`\`
### ✅ <Filename1>
### ❌ <Filename2>
<Description>
\`\`\`
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
- console.logs that have been left after debugging
- repeated code
- algorithmic errors that could fail under edge cases
- something that could be refactored
Make sure to review ALL files that were changed, do not skip any.
`;
export async function createNewPromptFile(
ide: IDE,
promptPath: string | undefined,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const promptFilePath = path.join(
workspaceDirs[0],
promptPath ?? DEFAULT_PROMPTS_FOLDER,
"new-prompt-file.prompt",
);
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
await ide.openFile(promptFilePath);
}

View file

@ -0,0 +1,37 @@
import Handlebars from "handlebars";
export function getContextProviderHelpers(
context: any,
): Array<[string, Handlebars.HelperDelegate]> | undefined {
return context.config.contextProviders?.map((provider: any) => [
provider.description.title,
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.embeddingsProvider,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.reranker,
selectedCode: context.selectedCode,
});
items.forEach((item: any) =>
context.addContextItem(createContextItem(item, provider)),
);
return items.map((item: any) => item.content).join("\n\n");
},
]);
}
function createContextItem(item: any, provider: any) {
return {
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
};
}

View file

@ -0,0 +1,25 @@
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
export async function getPromptFiles(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
const results = paths.map(async (path) => {
const content = await ide.readFile(path); // make a try catch
return { path, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}

View file

@ -0,0 +1,114 @@
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
export function convertToLetter(num: number): string {
let result = "";
while (num > 0) {
const remainder = (num - 1) % 26;
result = String.fromCharCode(97 + remainder) + result;
num = Math.floor((num - 1) / 26);
}
return result;
}
/**
* We replace filepaths with alphabetic characters to handle
* escaping issues.
*/
export const replaceFilepaths = (
value: string,
ctxProviderNames: string[],
): [string, { [key: string]: string }] => {
const ast = Handlebars.parse(value);
const keysToFilepath: { [key: string]: string } = {};
let keyIndex = 1;
for (const i in ast.body) {
const node = ast.body[i] as any;
if (node.type === "MustacheStatement") {
const originalNodeVal = node.path.original;
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
if (isFilepath) {
const letter = convertToLetter(keyIndex);
keysToFilepath[letter] = originalNodeVal;
value = value.replace(
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
`{{${letter}}}`,
);
keyIndex++;
}
}
}
return [value, keysToFilepath];
};
export function registerHelpers(
helpers: Array<[string, Handlebars.HelperDelegate]>,
): {
[key: string]: Promise<string>;
} {
const promises: { [key: string]: Promise<string> } = {};
for (const [name, helper] of helpers) {
Handlebars.registerHelper(name, (...args) => {
const id = uuidv4();
promises[id] = helper(...args);
return `__${id}__`;
});
}
return promises;
}
export async function prepareTemplateAndData(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
ctxProviderNames: string[],
): Promise<[string, any]> {
const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
const data: any = { ...inputData };
for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
data[replacedName] =
inputData[originalCtxProviderName] ?? originalCtxProviderName;
// If it's not a context provider, assume it's a filepath.
if (!ctxProviderNames.includes(originalCtxProviderName)) {
const fileContents = await readFile(vars[replacedName]);
if (fileContents) {
data[replacedName] = fileContents;
}
}
}
return [newTemplate, data];
}
export function compileAndRenderTemplate(template: string, data: any): string {
const templateFn = Handlebars.compile(template);
return templateFn(data);
}
export async function resolveHelperPromises(
renderedString: string,
promises: { [key: string]: Promise<string> },
): Promise<string> {
await Promise.all(Object.values(promises));
for (const id in promises) {
renderedString = renderedString.replace(`__${id}__`, await promises[id]);
}
return renderedString;
}

View file

@ -0,0 +1,8 @@
import { IDE } from "..";
import { getPromptFiles } from "./getPromptFiles";
import { createNewPromptFile } from "./createNewPromptFile";
import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
export { getPromptFiles, createNewPromptFile, slashCommandFromPromptFile };

View file

@ -0,0 +1,30 @@
import {
compileAndRenderTemplate,
prepareTemplateAndData,
registerHelpers,
resolveHelperPromises,
} from "./handlebarUtils";
export async function renderTemplatedString(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
): Promise<string> {
const helperPromises = availableHelpers
? registerHelpers(availableHelpers)
: {};
const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
const [newTemplate, data] = await prepareTemplateAndData(
template,
readFile,
inputData,
ctxProviderNames,
);
let renderedString = compileAndRenderTemplate(newTemplate, data);
return resolveHelperPromises(renderedString, helperPromises);
}

View file

@ -0,0 +1,93 @@
import { SlashCommand } from "..";
import { stripImages } from "../llm/images";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
import { updateChatHistory } from "./updateChatHistory";
import * as YAML from "yaml";
import { getBasename } from "../util/index";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getBasename(path).split(".prompt")[0];
}
export function parsePromptFile(path: string, content: string) {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;
preambleRaw = "";
}
const preamble = YAML.parse(preambleRaw) ?? {};
const name = extractName(preamble, path);
const description = preamble.description ?? name;
let systemMessage: string | undefined = undefined;
if (prompt.includes("<system>")) {
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
prompt = prompt.split("</system>")[1].trim();
}
return { name, description, systemMessage, prompt };
}
export function extractUserInput(input: string, commandName: string): string {
if (input.startsWith(`/${commandName}`)) {
return input.slice(commandName.length + 1).trimStart();
}
return input;
}
export async function getDefaultVariables(context: any, userInput: string) {
const currentFilePath = await context.ide.getCurrentFile();
const currentFile = currentFilePath
? await context.ide.readFile(currentFilePath)
: undefined;
return { currentFile, input: userInput };
}
export async function renderPrompt(
prompt: string,
context: any,
userInput: string,
) {
const helpers = getContextProviderHelpers(context);
const inputData = await getDefaultVariables(context, userInput);
return renderTemplatedString(
prompt,
context.ide.readFile.bind(context.ide),
inputData,
helpers,
);
}
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand {
const { name, description, systemMessage, prompt } = parsePromptFile(
path,
content,
);
return {
name,
description,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPrompt(prompt, context, userInput);
const messages = updateChatHistory(
context.history,
name,
renderedPrompt,
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
}

View file

@ -0,0 +1,55 @@
export function updateChatHistory(
history: any[],
commandName: string,
renderedPrompt: string,
systemMessage?: string,
) {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (Array.isArray(content)) {
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
messages[i] = updateArrayContent(
messages[i],
commandName,
renderedPrompt,
);
break;
}
} else if (
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
break;
}
}
if (systemMessage) {
messages[0]?.role === "system"
? (messages[0].content = systemMessage)
: messages.unshift({ role: "system", content: systemMessage });
}
return messages;
}
function updateArrayContent(
message: any,
commandName: string,
renderedPrompt: string,
) {
return {
...message,
content: message.content.map((part: any) =>
part.text?.startsWith(`/${commandName}`)
? { ...part, text: renderedPrompt }
: part,
),
};
}

View file

@ -69,8 +69,8 @@ To add a system message, start the body with `<system></system>` tags like in th
The body also supports templating with [Handlebars syntax](https://handlebarsjs.com/guide/). The following variables are currently available:
- `input`: The full text from the input box in the sidebar that is sent along with the slash command
- `currentFile`: The currently open file in your IDE
- `{{{ input }}}`: The full text from the input box in the sidebar that is sent along with the slash command
- `{{{ currentFile }}}`: The currently open file in your IDE
#### Context providers

View file

@ -320,8 +320,6 @@ const commandsMap: (
// Handle closing the GUI only if we are focused on the input
if (fullScreenTab) {
fullScreenPanel?.dispose();
} else {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
}
} else {
// Handle opening the GUI otherwise
@ -480,11 +478,6 @@ const commandsMap: (
//Full screen not open - open it
captureCommandTelemetry("openFullScreen");
// Close the sidebar.webviews
// vscode.commands.executeCommand("workbench.action.closeSidebar");
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
// vscode.commands.executeCommand("workbench.action.toggleZenMode");
//create the full screen panel
let panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
@ -601,8 +594,8 @@ const commandsMap: (
currentStatus === StatusBarStatus.Paused
? StatusBarStatus.Enabled
: currentStatus === StatusBarStatus.Disabled
? StatusBarStatus.Paused
: StatusBarStatus.Disabled;
? StatusBarStatus.Paused
: StatusBarStatus.Disabled;
} else {
// Toggle between Disabled and Enabled
targetStatus =

View file

@ -95,38 +95,29 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider {
return [quickEdit];
}
getSymbolsFrom(symbol: vscode.DocumentSymbol): vscode.DocumentSymbol[] {
if (symbol.children.length === 0) {
return [symbol];
}
const symbols: vscode.DocumentSymbol[] = [];
symbols.push(symbol);
for (const children of symbol.children) {
if (children.children.length === 0) {
symbols.push(children);
} else {
symbols.push(...this.getSymbolsFrom(children));
}
}
return symbols;
}
async getAllSymbols(uri: vscode.Uri) {
const docSymbols = await vscode.commands.executeCommand<
/**
* Get all top-level symbols and their immediate children.
* We do not recurse through all children to avoid noise.
*/
async getTopLevelAndChildrenSymbols(uri: vscode.Uri) {
const topLevelSymbols = await vscode.commands.executeCommand<
Array<vscode.DocumentSymbol> | undefined
>("vscode.executeDocumentSymbolProvider", uri);
if (!docSymbols) {
if (!topLevelSymbols) {
return [];
}
const symbols = docSymbols.flatMap((symbol) => this.getSymbolsFrom(symbol));
const childrenSymbols = topLevelSymbols.flatMap(
(symbol) => symbol.children,
);
const filteredSmybols = symbols?.filter((def) =>
this.quickActionSymbolKinds.includes(def.kind),
const symbols = [...topLevelSymbols, ...childrenSymbols];
const filteredSmybols = symbols?.filter(
(symbol) =>
this.quickActionSymbolKinds.includes(symbol.kind) &&
!symbol.range.isSingleLine,
);
return filteredSmybols;
@ -147,7 +138,7 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider {
return [];
}
const symbols = await this.getAllSymbols(document.uri);
const symbols = await this.getTopLevelAndChildrenSymbols(document.uri);
return symbols.flatMap(({ range }) => {
const commands: vscode.Command[] = !!this.customQuickActionsConfig

View file

@ -135,22 +135,6 @@ export class VsCodeIdeUtils {
);
}
showMultiFileEdit(edits: FileEdit[]) {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
const panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
"Continue",
vscode.ViewColumn.One,
);
// panel.webview.html = this.sidebar.getSidebarContent(
// extensionContext,
// panel,
// this.ide,
// "/monaco",
// edits
// );
}
openFile(filepath: string, range?: vscode.Range) {
// vscode has a builtin open/get open files
return openEditorAndRevealRange(filepath, range, vscode.ViewColumn.One);
@ -380,7 +364,9 @@ export class VsCodeIdeUtils {
const lastLine = lines.pop()?.trim();
if (lastLine) {
let i = lines.length - 1;
while (i >= 0 && !lines[i].trim().startsWith(lastLine)) i--;
while (i >= 0 && !lines[i].trim().startsWith(lastLine)) {
i--;
}
terminalContents = lines.slice(Math.max(i, 0)).join("\n");
}
@ -400,7 +386,9 @@ export class VsCodeIdeUtils {
async getAvailableThreads(): Promise<Thread[]> {
const session = vscode.debug.activeDebugSession;
if (!session) return [];
if (!session) {
return [];
}
const threadsResponse = await this._getThreads(session);
return threadsResponse.threads;
@ -449,7 +437,9 @@ export class VsCodeIdeUtils {
stackDepth = 3,
): Promise<string[]> {
const session = vscode.debug.activeDebugSession;
if (!session) return [];
if (!session) {
return [];
}
const sourcesPromises = await session
.customRequest("stackTrace", {
@ -476,7 +466,9 @@ export class VsCodeIdeUtils {
}
private async retrieveSource(sourceContainer: any): Promise<string> {
if (!sourceContainer.source) return "";
if (!sourceContainer.source) {
return "";
}
const sourceRef = sourceContainer.source.sourceReference;
if (sourceRef && sourceRef > 0) {
@ -498,7 +490,7 @@ export class VsCodeIdeUtils {
sourceContainer.endColumn,
),
);
} else if (sourceContainer.line)
} else if (sourceContainer.line) {
// fall back to 5 line of context
return await this.readRangeInFile(
sourceContainer.source.path,
@ -509,7 +501,9 @@ export class VsCodeIdeUtils {
0,
),
);
else return "unavailable";
} else {
return "unavailable";
}
}
private async _getRepo(
@ -557,7 +551,9 @@ export class VsCodeIdeUtils {
let i = 0;
while (!repo?.state?.HEAD?.name) {
if (this._repoWasNone) return undefined;
if (this._repoWasNone) {
return undefined;
}
await new Promise((resolve) => setTimeout(resolve, 1000));
i++;

View file

@ -2,12 +2,9 @@ import {
ArrowRightIcon,
ArrowUpOnSquareIcon,
AtSymbolIcon,
BeakerIcon,
BookOpenIcon,
CodeBracketIcon,
Cog6ToothIcon,
CommandLineIcon,
CubeIcon,
ExclamationCircleIcon,
ExclamationTriangleIcon,
FolderIcon,
@ -15,10 +12,11 @@ import {
GlobeAltIcon,
HashtagIcon,
MagnifyingGlassIcon,
PaintBrushIcon,
PencilIcon,
PlusIcon,
SparklesIcon,
TrashIcon,
BoltIcon,
} from "@heroicons/react/24/outline";
import { Editor } from "@tiptap/react";
import {
@ -62,16 +60,11 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
docs: BookOpenIcon,
issue: ExclamationCircleIcon,
trash: TrashIcon,
"/edit": PaintBrushIcon,
"/edit": PencilIcon,
"/clear": TrashIcon,
"/test": BeakerIcon,
"/config": Cog6ToothIcon,
"/comment": HashtagIcon,
"/share": ArrowUpOnSquareIcon,
"/cmd": CommandLineIcon,
"/codebase": SparklesIcon,
"/so": GlobeAltIcon,
"/issue": ExclamationCircleIcon,
};
function DropdownIcon(props: { className?: string; item: ComboBoxItem }) {
@ -81,41 +74,41 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) {
);
}
const provider =
props.item.type === "contextProvider"
? props.item.id
: props.item.type === "slashCommand"
? props.item.id
: props.item.type;
const provider = (() => {
switch (props.item.type) {
case "contextProvider":
case "slashCommand":
return props.item.id;
default:
return props.item.type;
}
})();
const iconClass = `${props.className} flex-shrink-0`;
const IconComponent =
ICONS_FOR_DROPDOWN[provider] ??
(props.item.type === "contextProvider" ? AtSymbolIcon : BoltIcon);
let fallbackIcon;
const Icon = ICONS_FOR_DROPDOWN[provider];
if (!Icon) {
fallbackIcon =
props.item.type === "contextProvider" ? (
<AtSymbolIcon className={iconClass} height="1.2em" width="1.2em" />
) : (
<CubeIcon className={iconClass} height="1.2em" width="1.2em" />
);
} else {
fallbackIcon = <Icon className={iconClass} height="1.2em" width="1.2em" />;
const fallbackIcon = (
<IconComponent
className={`${props.className} flex-shrink-0`}
height="1.2em"
width="1.2em"
/>
);
if (!props.item.icon) {
return fallbackIcon;
}
if (props.item.icon) {
return (
<SafeImg
className="flex-shrink-0 pr-2"
src={props.item.icon}
height="18em"
width="18em"
fallback={fallbackIcon}
/>
);
}
return fallbackIcon;
return (
<SafeImg
className="flex-shrink-0 pr-2"
src={props.item.icon}
height="18em"
width="18em"
fallback={fallbackIcon}
/>
);
}
const ItemsDiv = styled.div`
@ -212,6 +205,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
description: "Add a new documentation source",
});
}
setAllItems(items);
}, [subMenuTitle, props.items, props.editor]);