add missing vscodemessenger message handlers and fix apply

This commit is contained in:
Dallin Romney 2024-12-13 20:43:54 -08:00
parent f4e7398d70
commit 38b0ede53a
11 changed files with 162 additions and 92 deletions

View file

@ -38,7 +38,6 @@ export async function inferResolvedUriFromRelativePath(
throw new Error("inferResolvedUriFromRelativePath: no dirs provided");
}
const segments = pathToUriPathSegment(path).split("/");
// Generate all possible suffixes from shortest to longest
const suffixes: string[] = [];
for (let i = segments.length - 1; i >= 0; i--) {
@ -51,13 +50,17 @@ export async function inferResolvedUriFromRelativePath(
dir,
partialUri: joinPathsToUri(dir, suffix),
}));
const existenceChecks = await Promise.all(
uris.map(async ({ partialUri, dir }) => ({
console.log("here");
const promises = uris.map(async ({ partialUri, dir }) => {
const exists = await ide.fileExists(partialUri);
return {
dir,
partialUri,
exists: await ide.fileExists(partialUri),
})),
);
exists,
};
});
console.log("INFERRING", suffix, promises);
const existenceChecks = await Promise.all(promises);
const existingUris = existenceChecks.filter(({ exists }) => exists);

View file

@ -9,7 +9,10 @@ export function pathToUriPathSegment(path: string) {
let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes
clean = clean.replace(/^\//, ""); // remove start slash
clean = clean.replace(/\/$/, ""); // remove end slash
return encodeURIComponent(clean);
return clean
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
}
export function findUriInDirs(

View file

@ -39,10 +39,16 @@ class VsCodeIde implements IDE {
}
async fileExists(uri: string): Promise<boolean> {
return vscode.workspace.fs.stat(vscode.Uri.parse(uri)).then(
() => true,
() => false,
);
console.log("VSCODE FILE EXISTS");
try {
await vscode.workspace.fs.stat(vscode.Uri.parse(uri));
return true;
} catch (error) {
if (error instanceof vscode.FileSystemError) {
return false;
}
throw error;
}
}
async gotoDefinition(location: Location): Promise<RangeInFile[]> {

View file

@ -98,18 +98,6 @@ export class VsCodeMessenger {
);
});
this.onWebview("readRangeInFile", async (msg) => {
return await vscode.workspace
.openTextDocument(msg.data.filepath)
.then((document) => {
const start = new vscode.Position(0, 0);
const end = new vscode.Position(5, 0);
const range = new vscode.Range(start, end);
const contents = document.getText(range);
return contents;
});
});
this.onWebview("toggleDevTools", (msg) => {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
vscode.commands.executeCommand("continue.viewLogs");
@ -123,35 +111,22 @@ export class VsCodeMessenger {
this.onWebview("toggleFullScreen", (msg) => {
vscode.commands.executeCommand("continue.toggleFullScreen");
});
// History
this.onWebview("saveFile", async (msg) => {
return await ide.saveFile(msg.data.filepath);
});
this.onWebview("readFile", async (msg) => {
return await ide.readFile(msg.data.filepath);
this.onWebview("acceptDiff", async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(
"continue.acceptDiff",
filepath,
streamId,
);
});
webviewProtocol.on(
"acceptDiff",
async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(
"continue.acceptDiff",
filepath,
streamId,
);
},
);
webviewProtocol.on(
"rejectDiff",
async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(
"continue.rejectDiff",
filepath,
streamId,
);
},
);
this.onWebview("rejectDiff", async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(
"continue.rejectDiff",
filepath,
streamId,
);
});
this.onWebview("applyToFile", async ({ data }) => {
webviewProtocol.request("updateApplyState", {
@ -259,10 +234,6 @@ export class VsCodeMessenger {
await showTutorial(this.ide);
});
this.onWebview("openUrl", (msg) => {
vscode.env.openExternal(vscode.Uri.parse(msg.data));
});
this.onWebview(
"overwriteFile",
async ({ data: { prevFileContent, filepath } }) => {
@ -389,6 +360,19 @@ export class VsCodeMessenger {
// None right now
/** BOTH CORE AND WEBVIEW **/
this.onWebviewOrCore("readRangeInFile", async (msg) => {
return await vscode.workspace
.openTextDocument(msg.data.filepath)
.then((document) => {
const start = new vscode.Position(0, 0);
const end = new vscode.Position(5, 0);
const range = new vscode.Range(start, end);
const contents = document.getText(range);
return contents;
});
});
this.onWebviewOrCore("getIdeSettings", async (msg) => {
return ide.getIdeSettings();
});
@ -471,5 +455,58 @@ export class VsCodeMessenger {
false,
);
});
this.onWebviewOrCore("saveFile", async (msg) => {
return await ide.saveFile(msg.data.filepath);
});
this.onWebviewOrCore("readFile", async (msg) => {
return await ide.readFile(msg.data.filepath);
});
this.onWebviewOrCore("openUrl", (msg) => {
vscode.env.openExternal(vscode.Uri.parse(msg.data));
});
this.onWebviewOrCore("fileExists", async (msg) => {
return await ide.fileExists(msg.data.filepath);
});
this.onWebviewOrCore("gotoDefinition", async (msg) => {
return await ide.gotoDefinition(msg.data.location);
});
this.onWebviewOrCore("getLastModified", async (msg) => {
return await ide.getLastModified(msg.data.files);
});
this.onWebviewOrCore("getGitRootPath", async (msg) => {
return await ide.getGitRootPath(msg.data.dir);
});
this.onWebviewOrCore("listDir", async (msg) => {
return await ide.listDir(msg.data.dir);
});
this.onWebviewOrCore("getRepoName", async (msg) => {
return await ide.getRepoName(msg.data.dir);
});
this.onWebviewOrCore("getTags", async (msg) => {
return await ide.getTags(msg.data);
});
this.onWebviewOrCore("getIdeInfo", async (msg) => {
return await ide.getIdeInfo();
});
this.onWebviewOrCore("isTelemetryEnabled", async (msg) => {
return await ide.isTelemetryEnabled();
});
this.onWebviewOrCore("getWorkspaceConfigs", async (msg) => {
return await ide.getWorkspaceConfigs();
});
this.onWebviewOrCore("getUniqueId", async (msg) => {
return await ide.getUniqueId();
});
}
}

View file

@ -4,12 +4,11 @@ import {
ChevronRightIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { useMemo, useState } from "react";
import { useState } from "react";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { getMarkdownLanguageTagForFile } from "core/util";
import styled from "styled-components";
import { CodeToEdit } from "core";
import { rifWithContentsToContextItem } from "core/commands/util";
import {
getLastNUriRelativePathParts,
getUriPathBasename,

View file

@ -782,13 +782,7 @@ function TipTapEditor(props: TipTapEditorProps) {
editor.commands.focus("end");
}, 20);
},
[
editor,
props.isMainInput,
historyLength,
props.isMainInput,
onEnterRef.current,
],
[editor, props.isMainInput, historyLength, onEnterRef.current],
);
useWebviewListener(

View file

@ -83,7 +83,7 @@ export default function StepContainerPreActionButtons({
const defaultModel = useAppSelector(selectDefaultModel);
function onClickApply() {
if (!defaultModel) {
if (!defaultModel || !streamIdRef.current) {
return;
}
ideMessenger.post("applyToFile", {

View file

@ -1,19 +1,24 @@
import FileIcon from "../../FileIcon";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { getUriPathBasename } from "core/util/uri";
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
export interface FileInfoProps {
filepath: string;
relativeFilepath: string;
range?: string;
}
const FileInfo = ({ filepath, range }: FileInfoProps) => {
const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
const ideMessenger = useContext(IdeMessengerContext);
function onClickFileName() {
async function onClickFileName() {
const fileUri = await inferResolvedUriFromRelativePath(
relativeFilepath,
ideMessenger.ide,
);
ideMessenger.post("showFile", {
filepath,
filepath: fileUri,
});
}
@ -23,9 +28,9 @@ const FileInfo = ({ filepath, range }: FileInfoProps) => {
className="mr-0.5 flex w-full min-w-0 cursor-pointer items-center gap-0.5"
onClick={onClickFileName}
>
<FileIcon height="20px" width="20px" filename={filepath} />
<FileIcon height="20px" width="20px" filename={relativeFilepath} />
<span className="w-full truncate hover:underline">
{getUriPathBasename(filepath)}
{getLastNPathParts(relativeFilepath, 1)}
{range && ` ${range}`}
</span>
</div>

View file

@ -19,6 +19,7 @@ import {
selectApplyStateByStreamId,
selectIsInEditMode,
} from "../../../redux/slices/sessionSlice";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
const TopDiv = styled.div`
outline: 1px solid rgba(153, 153, 152);
@ -44,7 +45,7 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>`
export interface StepContainerPreToolbarProps {
codeBlockContent: string;
language: string;
fileUri: string;
relativeFilepath: string;
isGeneratingCodeBlock: boolean;
codeBlockIndex: number; // To track which codeblock we are applying
range?: string;
@ -84,17 +85,23 @@ export default function StepContainerPreToolbar(
: props.isGeneratingCodeBlock;
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.fileUri);
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath);
const defaultModel = useAppSelector(selectDefaultModel);
function onClickApply() {
async function onClickApply() {
if (!defaultModel) {
return;
}
console.log(props.relativeFilepath);
const fileUri = await inferResolvedUriFromRelativePath(
props.relativeFilepath,
ideMessenger.ide,
);
console.log(fileUri);
ideMessenger.post("applyToFile", {
streamId: streamIdRef.current,
filepath: props.fileUri,
filepath: fileUri,
text: codeBlockContent,
curSelectedModelTitle: defaultModel.title,
});
@ -137,16 +144,24 @@ export default function StepContainerPreToolbar(
wasGeneratingRef.current = isGeneratingCodeBlock;
}, [isGeneratingCodeBlock]);
function onClickAcceptApply() {
async function onClickAcceptApply() {
const fileUri = await inferResolvedUriFromRelativePath(
props.relativeFilepath,
ideMessenger.ide,
);
ideMessenger.post("acceptDiff", {
filepath: props.fileUri,
filepath: fileUri,
streamId: streamIdRef.current,
});
}
function onClickRejectApply() {
async function onClickRejectApply() {
const fileUri = await inferResolvedUriFromRelativePath(
props.relativeFilepath,
ideMessenger.ide,
);
ideMessenger.post("rejectDiff", {
filepath: props.fileUri,
filepath: fileUri,
streamId: streamIdRef.current,
});
}
@ -172,7 +187,10 @@ export default function StepContainerPreToolbar(
}`}
/>
<div className="w-full min-w-0">
<FileInfo filepath={props.fileUri} range={props.range} />
<FileInfo
relativeFilepath={props.relativeFilepath}
range={props.range}
/>
</div>
</div>

View file

@ -201,9 +201,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
if (node.meta) {
let meta = node.meta.split(" ");
node.data.hProperties["data-fileuri"] =
inferResolvedUriFromRelativePath(meta[0], ideMessenger.ide);
node.data.hProperties.range = meta[1]; // E.g
node.data.hProperties["data-relativefilepath"] = meta[0];
node.data.hProperties.range = meta[1];
}
});
},
@ -224,7 +223,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
return (tree) => {
visit(tree, { tagName: "pre" }, (node: any) => {
// Add an index (0, 1, 2, etc...) to each code block.
node.properties = { codeBlockIndex };
node.properties = { "data-codeblockindex": codeBlockIndex };
codeBlockIndex++;
});
};
@ -241,9 +240,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
);
},
pre: ({ node, ...preProps }) => {
const preChildProps = preProps?.children?.[0]?.props;
const { className, range } = preChildProps ?? {};
const fileUri = preChildProps["data-fileuri"];
const codeBlockIndex = preProps["data-codeblockindex"];
const preChildProps = preProps?.children?.[0]?.props ?? {};
const { className, range } = preChildProps;
const relativeFilePath = preChildProps["data-relativefilepath"];
const codeBlockContent = preChildProps["data-codeblockcontent"];
const isGeneratingCodeBlock =
preChildProps["data-isgeneratingcodeblock"];
@ -258,12 +259,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
// that is just action buttons on hover.
// We also use this in JB since we haven't yet implemented
// the logic forfileUri lazy apply.
if (!fileUri || isJetBrains()) {
if (!relativeFilePath || isJetBrains()) {
return (
<StepContainerPreActionButtons
language={language}
codeBlockContent={codeBlockContent}
codeBlockIndex={preProps.codeBlockIndex}
codeBlockIndex={codeBlockIndex}
>
<SyntaxHighlightedPre {...preProps} />
</StepContainerPreActionButtons>
@ -274,9 +275,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
return (
<StepContainerPreToolbar
codeBlockContent={codeBlockContent}
codeBlockIndex={preProps.codeBlockIndex}
codeBlockIndex={codeBlockIndex}
language={language}
fileUri={fileUri}
relativeFilepath={relativeFilePath}
isGeneratingCodeBlock={isGeneratingCodeBlock}
range={range}
>

View file

@ -65,7 +65,11 @@ export class IdeMessenger implements IIdeMessenger {
);
}
private _postToIde(messageType: string, data: any, messageId?: string) {
private _postToIde(
messageType: string,
data: FromWebviewProtocol[T][0],
messageId?: string,
) {
if (typeof vscode === "undefined") {
if (isJetBrains()) {
if (window.postIntellijMessage === undefined) {