diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index db8d99131..7aa7f7c66 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -1,8 +1,6 @@ -import fs from "node:fs"; -import path from "node:path"; - import MockLLM from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/fixtures"; +import { joinPathsToUri } from "../../../util/uri"; import { CompletionProvider } from "../../CompletionProvider"; import { AutocompleteInput } from "../../util/types"; @@ -39,8 +37,8 @@ export async function testAutocompleteFiltering( // Create a real file const [workspaceDir] = await ide.getWorkspaceDirs(); - const filepath = path.join(workspaceDir, test.filename); - fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); + const fileUri = joinPathsToUri(workspaceDir, test.filename); + await ide.writeFile(fileUri, test.input.replace(FIM_DELIMITER, "")); // Prepare completion input and provider const completionProvider = new CompletionProvider( @@ -55,7 +53,7 @@ export async function testAutocompleteFiltering( const character = prefix.split("\n")[line].length; const autocompleteInput: AutocompleteInput = { completionId: "test-completion-id", - filepath, + filepath: fileUri, pos: { line, character, diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 8c9ae1d30..1ada0d55c 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -15,7 +15,7 @@ export interface AutocompleteTemplate { compilePrefixSuffix?: ( prefix: string, suffix: string, - directoryUri: string, + filepath: string, reponame: string, snippets: AutocompleteSnippet[], ) => [string, string]; @@ -24,7 +24,7 @@ export interface AutocompleteTemplate { | (( prefix: string, suffix: string, - directoryUri: string, + filepath: string, reponame: string, language: string, snippets: AutocompleteSnippet[], @@ -85,7 +85,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { return [ - `+++++ ${getLastNUriRelativePathParts(filepath, 2)}\n${prefix}`, + `+++++ ${getLastNUriRelativePathParts(workspaceDirs, filepath, 2)}\n${prefix}`, suffix, ]; } diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 7e920f524..2e0569cb2 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,7 +1,6 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; -import { getBasename } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { HelperVars } from "../util/HelperVars"; @@ -13,6 +12,7 @@ import { getStopTokens } from "./getStopTokens"; import { SnippetPayload } from "../snippets"; import { formatSnippets } from "./formatting"; import { getSnippets } from "./filtering"; +import { getUriPathBasename } from "../../util/uri"; function getTemplate(helper: HelperVars): AutocompleteTemplate { if (helper.options.template) { @@ -33,7 +33,7 @@ function renderStringTemplate( filepath: string, reponame: string, ) { - const filename = getBasename(filepath); + const filename = getUriPathBasename(filepath); const compiledTemplate = Handlebars.compile(template); return compiledTemplate({ @@ -63,7 +63,7 @@ export function renderPrompt({ let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix; let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix; - const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + const reponame = getUriPathBasename(workspaceDirs[0] ?? "myproject"); const { template, compilePrefixSuffix, completionOptions } = getTemplate(helper); diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index b9a39aa0b..f481058aa 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -1,15 +1,18 @@ -import * as fs from "fs/promises"; -import * as path from "path"; - import ignore from "ignore"; -import { IDE, SlashCommand } from "../.."; +import { FileType, IDE, SlashCommand } from "../.."; import { defaultIgnoreDir, defaultIgnoreFile, + getGlobalContinueIgArray, gitIgArrayFromFile, } from "../../indexing/ignore"; import { renderChatMessage } from "../../util/messageContent"; +import { + getRelativePath, + getUriPathBasename, + joinPathsToUri, +} from "../../util/uri"; const LANGUAGE_DEP_MGMT_FILENAMES = [ "package.json", // JavaScript (Node.js) @@ -55,27 +58,32 @@ const OnboardSlashCommand: SlashCommand = { }; async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { - const entries = await fs.readdir(dir, { withFileTypes: true }); + const ig = ignore() + .add(defaultIgnoreDir) + .add(defaultIgnoreFile) + .add(getGlobalContinueIgArray()); + const entries = await ide.listDir(dir); - let ig = ignore().add(defaultIgnoreDir).add(defaultIgnoreFile); + const ignoreUri = joinPathsToUri(dir, ".gitignore"); + const fileExists = await ide.fileExists(ignoreUri); - const gitIgnorePath = path.join(dir, ".gitignore"); - - const hasIgnoreFile = await fs - .access(gitIgnorePath) - .then(() => true) - .catch(() => false); - - if (hasIgnoreFile) { - const gitIgnore = await ide.readFile(gitIgnorePath); + if (fileExists) { + const gitIgnore = await ide.readFile(ignoreUri); const igPatterns = gitIgArrayFromFile(gitIgnore); - ig = ig.add(igPatterns); + ig.add(igPatterns); } - const filteredEntries = entries.filter((entry) => !ig.ignores(entry.name)); + const workspaceDirs = await ide.getWorkspaceDirs(); - return filteredEntries; + const withRelativePaths = entries.map((entry) => ({ + uri: entry[0], + type: entry[1], + basename: getUriPathBasename(entry[0]), + relativePath: getRelativePath(entry[0], workspaceDirs), + })); + + return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath)); } async function gatherProjectContext( @@ -83,7 +91,6 @@ async function gatherProjectContext( ide: IDE, ): Promise { let context = ""; - async function exploreDirectory(dir: string, currentDepth: number = 0) { if (currentDepth > MAX_EXPLORE_DEPTH) { return; @@ -92,19 +99,16 @@ async function gatherProjectContext( const entries = await getEntriesFilteredByIgnore(dir, ide); for (const entry of entries) { - const fullPath = path.join(dir, entry.name); - const relativePath = path.relative(workspaceDir, fullPath); - - if (entry.isDirectory()) { - context += `\nFolder: ${relativePath}\n`; - await exploreDirectory(fullPath, currentDepth + 1); + if (entry.type === FileType.Directory) { + context += `\nFolder: ${entry.relativePath}\n`; + await exploreDirectory(entry.uri, currentDepth + 1); } else { - if (entry.name.toLowerCase() === "readme.md") { - const content = await fs.readFile(fullPath, "utf-8"); - context += `README for ${relativePath}:\n${content}\n\n`; - } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.name)) { - const content = await fs.readFile(fullPath, "utf-8"); - context += `${entry.name} for ${relativePath}:\n${content}\n\n`; + if (entry.basename.toLowerCase() === "readme.md") { + const content = await ide.readFile(entry.uri); + context += `README for ${entry.relativePath}:\n${content}\n\n`; + } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) { + const content = await ide.readFile(entry.uri); + context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`; } } } diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index 4b69f4c62..f60638582 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -1,10 +1,9 @@ -import * as fs from "node:fs"; import { homedir } from "node:os"; -import path from "path"; import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; +import { getContinueGlobalPath } from "../../util/paths.js"; // If useful elsewhere, helper funcs should move to core/util/index.ts or similar function getOffsetDatetime(date: Date): Date { @@ -62,10 +61,7 @@ const ShareSlashCommand: SlashCommand = { }\n\n${msgText}`; } - let outputDir: string = params?.outputDir; - if (!outputDir) { - outputDir = await ide.getContinueDir(); - } + let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); if (outputDir.startsWith("~")) { outputDir = outputDir.replace(/^~/, homedir); diff --git a/core/commands/util.ts b/core/commands/util.ts index 95fedadf7..e1e9cd60e 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -59,3 +59,7 @@ export function ctxItemToRifWithContents( return rif; } + +// export function codeContextItemToMarkdownSource( +// item: ContextItemWithId, +// ): string {} diff --git a/core/config/types.ts b/core/config/types.ts index 71c16c605..93ca6acca 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -446,7 +446,6 @@ declare global { fileExists(filepath: string): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; - getContinueDir(): Promise; openFile(path: string): Promise; runCommand(command: string): Promise; saveFile(filepath: string): Promise; diff --git a/core/context/providers/PromptFilesContextProvider.ts b/core/context/providers/PromptFilesContextProvider.ts index 9ea603f3f..bc9239f1d 100644 --- a/core/context/providers/PromptFilesContextProvider.ts +++ b/core/context/providers/PromptFilesContextProvider.ts @@ -6,6 +6,7 @@ import { ContextSubmenuItem, LoadSubmenuItemsArgs, } from "../../"; +import { getAllPromptFilesV2 } from "../../promptFiles/v2/getPromptFiles"; import { parsePreamble } from "../../promptFiles/v2/parse"; import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile"; @@ -37,7 +38,7 @@ class PromptFilesContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { - const promptFiles = await getAllPromptFiles( + const promptFiles = await getAllPromptFilesV2( args.ide, args.config.experimental?.promptPath, ); diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 17e76af43..5aaabead7 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -71,6 +71,7 @@ This is the question that you should select relevant files for: "${input}"`; return []; } + const subDirPrefix = filterDirectory ? filterDirectory + pathSep : ""; const files = content .split("")[1] diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 564656d23..ff550c0fe 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -1,5 +1,3 @@ -import path from "path"; - import { distance } from "fastest-levenshtein"; import Parser from "web-tree-sitter"; @@ -9,6 +7,10 @@ import { myersDiff } from "../../diff/myers"; import { getParserForFile } from "../../util/treeSitter"; import { findInAst } from "./findInAst"; +import { + getFileExtensionFromBasename, + getUriFileExtension, +} from "../../util/uri"; type AstReplacements = Array<{ nodeToReplace: Parser.SyntaxNode; @@ -125,8 +127,8 @@ export async function deterministicApplyLazyEdit( ); if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) { // If so, we tack lazy blocks to start and end, and run the usual algorithm - const ext = path.extname(filename).slice(1); - const language = LANGUAGES[ext]; + const extension = getFileExtensionFromBasename(filename); + const language = LANGUAGES[extension]; if (language) { newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`; newTree = parser.parse(newLazyFile); diff --git a/core/index.d.ts b/core/index.d.ts index d1f2b28fd..db8e62648 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -617,8 +617,6 @@ export interface IDE { showVirtualFile(title: string, contents: string): Promise; - getContinueDir(): Promise; - openFile(path: string): Promise; openUrl(url: string): Promise; diff --git a/core/promptFiles/v2/parse.ts b/core/promptFiles/v2/parse.ts index 3de31a6d6..334733d79 100644 --- a/core/promptFiles/v2/parse.ts +++ b/core/promptFiles/v2/parse.ts @@ -1,7 +1,8 @@ import * as YAML from "yaml"; +import { getLastNPathParts } from "../../util"; export function extractName(preamble: { name?: string }, path: string): string { - return preamble.name ?? getBasename(path).split(".prompt")[0]; + return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; } export function getPreambleAndBody(content: string): [string, string] { diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index efe5f6885..dd0edeb54 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -26,7 +26,6 @@ export type ToIdeFromWebviewOrCoreProtocol = { listFolders: [undefined, string[]]; writeFile: [{ path: string; contents: string }, void]; showVirtualFile: [{ name: string; content: string }, void]; - getContinueDir: [undefined, string]; openFile: [{ path: string }, void]; openUrl: [string, void]; runCommand: [{ command: string }, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index d19012d6e..df25c8379 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -138,17 +138,6 @@ export class MessageIde implements IDE { return await this.request("listFolders", undefined); } - _continueDir: string | null = null; - - async getContinueDir(): Promise { - if (this._continueDir) { - return this._continueDir; - } - const dir = await this.request("getContinueDir", undefined); - this._continueDir = dir; - return dir; - } - async writeFile(fileUri: string, contents: string): Promise { await this.request("writeFile", { path: fileUri, contents }); } diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index a180bb227..3894a3697 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -126,10 +126,6 @@ export class ReverseMessageIde { return undefined; }); - this.on("getContinueDir", () => { - return this.ide.getContinueDir(); - }); - this.on("writeFile", (data) => { return this.ide.writeFile(data.path, data.contents); }); diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 5a159b04a..ccb79f290 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -2,6 +2,7 @@ import childProcess from "node:child_process"; import util from "node:util"; import { ToolImpl } from "."; +import { fileURLToPath } from "node:url"; const asyncExec = util.promisify(childProcess.exec); @@ -11,7 +12,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { try { const output = await asyncExec(args.command, { - cwd: (await extras.ide.getWorkspaceDirs())[0], + cwd: fileURLToPath((await extras.ide.getWorkspaceDirs())[0]), }); return [ { diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index e11cf37ec..a44aa1add 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -186,10 +186,6 @@ class FileSystemIde implements IDE { return Promise.resolve(); } - getContinueDir(): Promise { - return Promise.resolve(getContinueGlobalPath()); - } - openFile(path: string): Promise { return Promise.resolve(); } diff --git a/core/util/index.ts b/core/util/index.ts index b40d264e0..d310b3fde 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -119,52 +119,6 @@ export function getLastNPathParts(filepath: string, n: number): string { // return getLastNPathParts(item, n); // } -// export function shortestRelativePaths(paths: string[]): string[] { -// if (paths.length === 0) { -// return []; -// } - -// const partsLengths = paths.map((x) => x.split(SEP_REGEX).length); -// const currentRelativePaths = paths.map(getB); -// const currentNumParts = paths.map(() => 1); -// const isDuplicated = currentRelativePaths.map( -// (x, i) => -// currentRelativePaths.filter((y, j) => y === x && paths[i] !== paths[j]) -// .length > 1, -// ); - -// while (isDuplicated.some(Boolean)) { -// const firstDuplicatedPath = currentRelativePaths.find( -// (x, i) => isDuplicated[i], -// ); -// if (!firstDuplicatedPath) { -// break; -// } - -// currentRelativePaths.forEach((x, i) => { -// if (x === firstDuplicatedPath) { -// currentNumParts[i] += 1; -// currentRelativePaths[i] = getLastNUriRelativePathParts( -// paths[i], -// currentNumParts[i], -// ); -// } -// }); - -// isDuplicated.forEach((x, i) => { -// if (x) { -// isDuplicated[i] = -// // Once we've used up all the parts, we can't make it longer -// currentNumParts[i] < partsLengths[i] && -// currentRelativePaths.filter((y) => y === currentRelativePaths[i]) -// .length > 1; -// } -// }); -// } - -// return currentRelativePaths; -// } - // export function splitPath(path: string, withRoot?: string): string[] { // let parts = path.includes("/") ? path.split("/") : path.split("\\"); // if (withRoot !== undefined) { diff --git a/core/util/paths.ts b/core/util/paths.ts index d6d2d3365..8f451c40a 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -321,6 +321,15 @@ export function getLogsDirPath(): string { return logsPath; } +export function getLogFilePath(): string { + const logFilePath = path.join(getContinueGlobalPath(), "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFilePath)) { + fs.writeFileSync(logFilePath, ""); + } + return logFilePath; +} + export function getCoreLogsPath(): string { return path.join(getLogsDirPath(), "core.log"); } @@ -379,3 +388,13 @@ export function setupInitialDotContinueDirectory() { } }); } + +export function getDiffsDirectoryPath(): string { + const diffsPath = path.join(getContinueGlobalPath(), ".diffs"); // .replace(/^C:/, "c:"); ?? + if (!fs.existsSync(diffsPath)) { + fs.mkdirSync(diffsPath, { + recursive: true, + }); + } + return diffsPath; +} diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index cfae9f7e1..2efb03114 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -1,4 +1,5 @@ -// import fs from "node:fs"; +import fs from "node:fs"; +import path from "path"; import Parser, { Language } from "web-tree-sitter"; import { FileSymbolMap, IDE, SymbolWithRange } from ".."; diff --git a/core/util/uri.ts b/core/util/uri.ts index f7e4b9fb4..57af61235 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -89,6 +89,10 @@ export function getUriPathBasename(uri: string): string { return getPath(); } +export function getFileExtensionFromBasename(filename: string) { + return filename.split(".").pop() ?? ""; +} + export function joinPathsToUri(uri: string, ...pathSegments: string[]) { const components = URI.parse(uri); const segments = pathSegments.map((segment) => pathToUriPathSegment(segment)); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index de0c061b2..426de1d50 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -19,7 +19,6 @@ class MessageTypes { "getWorkspaceDirs", "showLines", "listFolders", - "getContinueDir", "writeFile", "fileExists", "showVirtualFile", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 90ef1a850..e8e90519a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -560,10 +560,6 @@ class IdeProtocolClient( respond(file.exists()) } - "getContinueDir" -> { - respond(getContinueGlobalPath()) - } - "openFile" -> { setFileOpen((data as Map)["path"] as String) respond(null) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 4111ecf51..c519f6bf8 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -373,10 +373,6 @@ class VsCodeIde implements IDE { return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString()); } - async getContinueDir(): Promise { - return getContinueGlobalPath(); - } - async writeFile(fileUri: string, contents: string): Promise { await vscode.workspace.fs.writeFile( vscode.Uri.parse(fileUri), @@ -441,7 +437,7 @@ class VsCodeIde implements IDE { vscode.workspace.notebookDocuments.find((doc) => URI.equal(doc.uri.toString(), uri.toString()), ) ?? - (uri.fsPath.endsWith("ipynb") + (uri.path.endsWith("ipynb") ? await vscode.workspace.openNotebookDocument(uri) : undefined); if (notebook) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 9d443f3c3..c5fee0ec9 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import * as fs from "node:fs"; import * as os from "node:os"; -import * as path from "node:path"; import { ContextMenuConfig, RangeInFileWithContents } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; @@ -12,7 +10,11 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; import { walkDirAsync } from "core/indexing/walkDir"; import { GlobalContext } from "core/util/GlobalContext"; -import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths"; +import { + getConfigJsonPath, + getDevDataFilePath, + getLogFilePath, +} from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import readLastLines from "read-last-lines"; import * as vscode from "vscode"; @@ -160,17 +162,17 @@ async function addHighlightedCodeToContext( } async function addEntireFileToContext( - filepath: vscode.Uri, + uri: vscode.Uri, webviewProtocol: VsCodeWebviewProtocol | undefined, ) { // If a directory, add all files in the directory - const stat = await vscode.workspace.fs.stat(filepath); + const stat = await vscode.workspace.fs.stat(uri); if (stat.type === vscode.FileType.Directory) { - const files = await vscode.workspace.fs.readDirectory(filepath); + const files = await vscode.workspace.fs.readDirectory(uri); for (const [filename, type] of files) { if (type === vscode.FileType.File) { addEntireFileToContext( - vscode.Uri.joinPath(filepath, filename), + vscode.Uri.joinPath(uri, filename), webviewProtocol, ); } @@ -179,9 +181,9 @@ async function addEntireFileToContext( } // Get the contents of the file - const contents = (await vscode.workspace.fs.readFile(filepath)).toString(); + const contents = (await vscode.workspace.fs.readFile(uri)).toString(); const rangeInFileWithContents = { - filepath: filepath.toString(), + filepath: uri.toString(), contents: contents, range: { start: { @@ -230,12 +232,12 @@ async function processDiff( diffManager: DiffManager, ide: VsCodeIde, verticalDiffManager: VerticalDiffManager, - newFileUri?: vscode.Uri, + newFileUri?: string, streamId?: string, ) { captureCommandTelemetry(`${action}Diff`); - let newOrCurrentUri = newFileUri?.toString(); + let newOrCurrentUri = newFileUri; if (!newOrCurrentUri) { const currentFile = await ide.getCurrentFile(); newOrCurrentUri = currentFile?.path; @@ -343,24 +345,18 @@ const getCommandsMap: ( ); } return { - "continue.acceptDiff": async ( - newFilepath?: string | vscode.Uri, - streamId?: string, - ) => + "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => processDiff( "accept", sidebar, diffManager, ide, verticalDiffManager, - newFilepath, + newFileUri, streamId, ), - "continue.rejectDiff": async ( - newFilepath?: string | vscode.Uri, - streamId?: string, - ) => + "continue.rejectDiff": async (newFilepath?: string, streamId?: string) => processDiff( "reject", sidebar, @@ -626,17 +622,8 @@ const getCommandsMap: ( }, "continue.viewLogs": async () => { captureCommandTelemetry("viewLogs"); - - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } - - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); + const logFilePath = getLogFilePath(); + await vscode.window.showTextDocument(vscode.Uri.file(logFilePath)); }, "continue.debugTerminal": async () => { captureCommandTelemetry("debugTerminal"); @@ -783,9 +770,9 @@ const getCommandsMap: ( .stat(uri) ?.then((stat) => stat.type === vscode.FileType.Directory); if (isDirectory) { - for await (const filepath of walkDirAsync(uri.toString(), ide)) { + for await (const fileUri of walkDirAsync(uri.toString(), ide)) { addEntireFileToContext( - vscode.Uri.parse(filepath), + vscode.Uri.parse(fileUri), sidebar.webviewProtocol, ); } @@ -917,7 +904,7 @@ const getCommandsMap: ( } else if ( selectedOption === "$(gear) Configure autocomplete options" ) { - ide.openFile(getConfigJsonPath()); + ide.openFile(vscode.Uri.file(getConfigJsonPath()).toString()); } else if ( autocompleteModels.some((model) => model.title === selectedOption) ) { diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index 42be5903f..dc85a5683 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -1,7 +1,3 @@ -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; - import { devDataPath } from "core/util/paths"; import * as vscode from "vscode"; @@ -17,47 +13,34 @@ interface DiffInfo { range: vscode.Range; } -async function readFile(uri: vscode.Uri): Promise { +async function readFile(fileUri: string): Promise { return await vscode.workspace.fs - .readFile(uri) + .readFile(vscode.Uri.parse(fileUri)) .then((bytes) => new TextDecoder().decode(bytes)); } -async function writeFile(uri: vscode.Uri, contents: string) { - await vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(contents)); +async function writeFile(fileUri: string, contents: string) { + await vscode.workspace.fs.writeFile( + vscode.Uri.parse(fileUri), + new TextEncoder().encode(contents), + ); } -// THIS IS LOCAL -export const DIFF_DIRECTORY = path - .join(os.homedir(), ".continue", ".diffs") - .replace(/^C:/, "c:"); - export class DiffManager { // Create a temporary file in the global .continue directory which displays the updated version // Doing this because virtual files are read-only private diffs: Map = new Map(); - diffAtNewFilepath(newFilepath: string): DiffInfo | undefined { - return this.diffs.get(newFilepath); - } - - private async setupDirectory() { - // Make sure the diff directory exists - if (!fs.existsSync(DIFF_DIRECTORY)) { - fs.mkdirSync(DIFF_DIRECTORY, { - recursive: true, - }); - } + diffAtNewFilepath(newFileUri: string): DiffInfo | undefined { + return this.diffs.get(newFileUri); } webviewProtocol: VsCodeWebviewProtocol | undefined; constructor(private readonly extensionContext: vscode.ExtensionContext) { - this.setupDirectory(); - // Listen for file closes, and if it's a diff file, clean up vscode.workspace.onDidCloseTextDocument((document) => { - const newFilepath = document.uri.fsPath; + const newFilepath = document.uri.toString(); const diffInfo = this.diffs.get(newFilepath); if (diffInfo) { this.cleanUpDiff(diffInfo, false); @@ -73,15 +56,15 @@ export class DiffManager { } private remoteTmpDir = "/tmp/continue"; - private getNewFilepath(originalFilepath: string): string { + private getNewFileUri(originalFileUri: string): vscode.Uri { if (vscode.env.remoteName) { // If we're in a remote, use the remote's temp directory // Doing this because there's no easy way to find the home directory, // and there aren't write permissions to the root directory // and writing these to local causes separate issues // because the vscode.diff command will always try to read from remote - vscode.workspace.fs.createDirectory(uriFromFilePath(this.remoteTmpDir)); - return path.join( + vscode.workspace.fs.createDirectory(vscode.Uri.file(this.remoteTmpDir)); + return vscode.Uri.j.join( this.remoteTmpDir, this.escapeFilepath(originalFilepath), ); @@ -160,8 +143,6 @@ export class DiffManager { newContent: string, step_index: number, ): Promise { - await this.setupDirectory(); - // Create or update existing diff const newFilepath = this.getNewFilepath(originalFilepath); await writeFile(uriFromFilePath(newFilepath), newContent); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index de4a36d02..806e602a7 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -159,7 +159,7 @@ export class VsCodeExtension { const { verticalDiffCodeLens } = registerAllCodeLensProviders( context, this.diffManager, - this.verticalDiffManager.filepathToCodeLens, + this.verticalDiffManager.fileUriToCodeLens, config, ); @@ -182,7 +182,7 @@ export class VsCodeExtension { registerAllCodeLensProviders( context, this.diffManager, - this.verticalDiffManager.filepathToCodeLens, + this.verticalDiffManager.fileUriToCodeLens, newConfig, ); } @@ -264,8 +264,8 @@ export class VsCodeExtension { vscode.workspace.onDidSaveTextDocument(async (event) => { this.core.invoke("files/changed", { - uris: [event.uri.toString()] - }) + uris: [event.uri.toString()], + }); }); vscode.workspace.onDidDeleteFiles(async (event) => { @@ -317,7 +317,7 @@ export class VsCodeExtension { // Refresh index when branch is changed this.ide.getWorkspaceDirs().then((dirs) => dirs.forEach(async (dir) => { - const repo = await this.ide.getRepo(vscode.Uri.file(dir)); + const repo = await this.ide.getRepo(dir); if (repo) { repo.state.onDidChange(() => { // args passed to this callback are always undefined, so keep track of previous branch diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 244777fa8..a7494e4df 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,5 +1,4 @@ import * as fs from "node:fs"; -import * as path from "node:path"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; @@ -30,6 +29,7 @@ import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; import { getUriPathBasename } from "core/util/uri"; +import { showTutorial } from "../util/tutorial"; /** * A shared messenger class between Core and Webview @@ -86,22 +86,16 @@ export class VsCodeMessenger { ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { - const fullPath = getFullyQualifiedPath(this.ide, msg.data.filepath); - - if (fullPath) { - this.ide.openFile(fullPath); - } + this.ide.openFile(msg.data.filepath); }); this.onWebview("vscode/openMoveRightMarkdown", (msg) => { vscode.commands.executeCommand( "markdown.showPreview", - vscode.Uri.file( - path.join( - getExtensionUri().fsPath, - "media", - "move-chat-panel-right.md", - ), + vscode.Uri.joinPath( + getExtensionUri(), + "media", + "move-chat-panel-right.md", ), ); }); @@ -175,25 +169,14 @@ export class VsCodeMessenger { fileContent: data.text, }); - let filepath = data.filepath; - - // If there is a filepath, verify it exists and then open the file - if (filepath) { - const fullPath = getFullyQualifiedPath(ide, filepath); - - if (!fullPath) { - return; - } - - const fileExists = await this.ide.fileExists(fullPath); - - // If there is no existing file at the path, create it + if (data.filepath) { + const fileExists = await this.ide.fileExists(data.filepath); if (!fileExists) { - await this.ide.writeFile(fullPath, ""); - await this.ide.openFile(fullPath); + await this.ide.writeFile(data.filepath, ""); + await this.ide.openFile(data.filepath); } - await this.ide.openFile(fullPath); + await this.ide.openFile(data.filepath); } // Get active text editor @@ -282,25 +265,7 @@ export class VsCodeMessenger { }); this.onWebview("showTutorial", async (msg) => { - const tutorialPath = path.join( - getExtensionUri().fsPath, - "continue_tutorial.py", - ); - // Ensure keyboard shortcuts match OS - if (process.platform !== "darwin") { - let tutorialContent = fs.readFileSync(tutorialPath, "utf8"); - tutorialContent = tutorialContent - .replace("⌘", "^") - .replace("Cmd", "Ctrl"); - fs.writeFileSync(tutorialPath, tutorialContent); - } - - const doc = await vscode.workspace.openTextDocument( - vscode.Uri.file(tutorialPath), - ); - await vscode.window.showTextDocument(doc, { - preview: false, - }); + await showTutorial(this.ide); }); this.onWebview("openUrl", (msg) => { @@ -466,9 +431,6 @@ export class VsCodeMessenger { this.onWebviewOrCore("showVirtualFile", async (msg) => { return ide.showVirtualFile(msg.data.name, msg.data.content); }); - this.onWebviewOrCore("getContinueDir", async (msg) => { - return ide.getContinueDir(); - }); this.onWebviewOrCore("openFile", async (msg) => { return ide.openFile(msg.data.path); }); diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts index dba240912..32fbe97f1 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts @@ -2,8 +2,9 @@ import path from "path"; import * as vscode from "vscode"; -import { DiffManager, DIFF_DIRECTORY } from "../../../diff/horizontal"; +import { DiffManager } from "../../../diff/horizontal"; import { getMetaKeyLabel } from "../../../util/util"; +import { getDiffsDirectoryPath } from "core/util/paths"; export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { constructor(private diffManager: DiffManager) {} @@ -12,7 +13,7 @@ export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { document: vscode.TextDocument, _: vscode.CancellationToken, ): vscode.CodeLens[] | Thenable { - if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) { + if (path.dirname(document.uri.fsPath) === getDiffsDirectoryPath()) { const codeLenses: vscode.CodeLens[] = []; let range = new vscode.Range(0, 0, 1, 0); const diffInfo = this.diffManager.diffAtNewFilepath( diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts index b4c30350b..18ed64dda 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -7,11 +7,7 @@ import { CONTINUE_WORKSPACE_KEY, getContinueWorkspaceConfig, } from "../../../util/workspaceConfig"; - -const TUTORIAL_FILE_NAME = "continue_tutorial.py"; -function isTutorialFile(uri: vscode.Uri) { - return uri.fsPath.endsWith(TUTORIAL_FILE_NAME); -} +import { isTutorialFile } from "../../../util/tutorial"; export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions"; diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index ce4a1b645..aefc7408f 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -248,7 +248,7 @@ export class QuickEdit { private setActiveEditorAndPrevInput(editor: vscode.TextEditor) { const existingHandler = this.verticalDiffManager.getHandlerForFile( - editor.document.uri.fsPath ?? "", + editor.document.uri.toString(), ); this.editorWhenOpened = editor; @@ -447,8 +447,8 @@ export class QuickEdit { if (searchResults.length > 0) { quickPick.items = searchResults - .map(({ filename }) => ({ - label: filename, + .map(({ relativePath }) => ({ + label: relativePath, alwaysShow: true, })) .slice(0, QuickEdit.maxFileSearchResults); diff --git a/extensions/vscode/src/util/tutorial.ts b/extensions/vscode/src/util/tutorial.ts new file mode 100644 index 000000000..45a86a675 --- /dev/null +++ b/extensions/vscode/src/util/tutorial.ts @@ -0,0 +1,27 @@ +import { IDE } from "core"; +import { getExtensionUri } from "./vscode"; +import * as vscode from "vscode"; + +const TUTORIAL_FILE_NAME = "continue_tutorial.py"; +export function getTutorialUri(): vscode.Uri { + return vscode.Uri.joinPath(getExtensionUri(), TUTORIAL_FILE_NAME); +} + +export function isTutorialFile(uri: vscode.Uri) { + return uri.path.endsWith(TUTORIAL_FILE_NAME); +} + +export async function showTutorial(ide: IDE) { + const tutorialUri = getTutorialUri(); + // Ensure keyboard shortcuts match OS + if (process.platform !== "darwin") { + let tutorialContent = await ide.readFile(tutorialUri.toString()); + tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl"); + await ide.writeFile(tutorialUri.toString(), tutorialContent); + } + + const doc = await vscode.workspace.openTextDocument(tutorialUri); + await vscode.window.showTextDocument(doc, { + preview: false, + }); +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 1fc383fae..dcb07fb5a 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,6 +1,3 @@ -import fs from "node:fs"; -import path from "path"; - import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; import { WebviewMessengerResult } from "core/protocol/util"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; @@ -12,25 +9,6 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; import { showFreeTrialLoginMessage } from "./util/messages"; -import { getExtensionUri } from "./util/vscode"; - -export async function showTutorial() { - const tutorialPath = path.join( - getExtensionUri().fsPath, - "continue_tutorial.py", - ); - // Ensure keyboard shortcuts match OS - if (process.platform !== "darwin") { - let tutorialContent = fs.readFileSync(tutorialPath, "utf8"); - tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl"); - fs.writeFileSync(tutorialPath, tutorialContent); - } - - const doc = await vscode.workspace.openTextDocument( - vscode.Uri.file(tutorialPath), - ); - await vscode.window.showTextDocument(doc, { preview: false }); -} export class VsCodeWebviewProtocol implements IMessenger diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx index f6e4420f4..f91300e74 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx @@ -4,12 +4,13 @@ import { ChevronRightIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { useState } from "react"; +import { useMemo, useState } from "react"; import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; import { getMarkdownLanguageTagForFile } from "core/util"; import styled from "styled-components"; import { CodeToEdit } from "core"; -import { getLastNPathParts } from "core/util/uri"; +import { rifWithContentsToContextItem } from "core/commands/util"; +import { getUriPathBasename } from "core/util/uri"; export interface CodeToEditListItemProps { code: CodeToEdit; @@ -36,7 +37,15 @@ export default function CodeToEditListItem({ }: CodeToEditListItemProps) { const [showCodeSnippet, setShowCodeSnippet] = useState(false); - const filepath = code.filepath.split("/").pop() || code.filepath; + const context = useMemo(() => { + return rifWithContentsToContextItem({ + contents: code.contents, + range: { + start: {}, + }, + }); + }, []); + const basename = getUriPathBasename(code.filepath); const fileSubpath = getLastNPathParts(code.filepath, 2); let isInsertion = false; diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 1e3997930..226d87a6d 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -29,10 +29,14 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const isUrl = contextItem.uri?.type === "url"; function openContextItem() { - const { uri, name, description, content } = contextItem; + const { uri, name, content } = contextItem; if (isUrl) { - ideMessenger.post("openUrl", uri.value); + if (uri?.value) { + ideMessenger.post("openUrl", uri.value); + } else { + console.error("Couldn't open url", uri); + } } else if (uri) { const isRangeInFile = name.includes(" (") && name.endsWith(")"); @@ -44,7 +48,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { rif.range.end.line, ); } else { - ideMessenger.ide.openFile(description); + ideMessenger.ide.openFile(uri.value); } } else { ideMessenger.ide.showVirtualFile(name, content); diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 6bdfdf353..2a1fe556a 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -5,7 +5,7 @@ import { } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { dedent, getMarkdownLanguageTagForFile } from "core/util"; -import React, { useContext } from "react"; +import React, { useContext, useMemo } from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscEditorBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -13,6 +13,7 @@ import { getFontSize } from "../../util"; import FileIcon from "../FileIcon"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import StyledMarkdownPreview from "./StyledMarkdownPreview"; +import { ctxItemToRifWithContents } from "core/commands/util"; const PreviewMarkdownDiv = styled.div<{ borderColor?: string; @@ -49,7 +50,6 @@ interface CodeSnippetPreviewProps { const MAX_PREVIEW_HEIGHT = 300; -// Pre-compile the regular expression outside of the function const backticksRegex = /`{3,}/gm; function CodeSnippetPreview(props: CodeSnippetPreviewProps) { @@ -58,12 +58,14 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { const [collapsed, setCollapsed] = React.useState(true); const [hovered, setHovered] = React.useState(false); - const content = dedent`${props.item.content}`; + const content = useMemo(() => { + return dedent`${props.item.content}`; + }, [props.item.content]); - const fence = React.useMemo(() => { + const fence = useMemo(() => { const backticks = content.match(backticksRegex); return backticks ? backticks.sort().at(-1) + "`" : "```"; - }, [props.item.content]); + }, [content]); const codeBlockRef = React.useRef(null); @@ -79,19 +81,19 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { { - if (props.item.id.providerTitle === "file") { + if ( + props.item.id.providerTitle === "file" && + props.item.uri?.value + ) { ideMessenger.post("showFile", { - filepath: props.item.description, + filepath: props.item.uri.value, }); } else if (props.item.id.providerTitle === "code") { - const lines = props.item.name - .split("(")[1] - .split(")")[0] - .split("-"); + const rif = ctxItemToRifWithContents(props.item); ideMessenger.ide.showLines( - props.item.description.split(" ")[0], - parseInt(lines[0]) - 1, - parseInt(lines[1]) - 1, + rif.filepath, + rif.range.start.line, + rif.range.end.line, ); } else { ideMessenger.post("showVirtualFile", { @@ -124,9 +126,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { ref={codeBlockRef} >