feat(jb): impl "apply" button

This commit is contained in:
Test 2024-10-26 17:10:49 -07:00
parent 8d2a3ffc24
commit 802cb43cd6
8 changed files with 199 additions and 101 deletions

View file

@ -60,7 +60,7 @@ export async function* streamDiffLines(
language: string | undefined,
onlyOneInsertion?: boolean,
): AsyncGenerator<DiffLine> {
Telemetry.capture(
void Telemetry.capture(
"inlineEdit",
{
model: llm.model,
@ -94,7 +94,6 @@ export async function* streamDiffLines(
);
const inept = modelIsInept(llm.model);
const options: LLMFullCompletionOptions = {};
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt, { raw: true })

View file

@ -15,7 +15,12 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
},
];
openUrl: [string, void];
applyToCurrentFile: [{ text: string; streamId: string }, void];
// We pass the `curSelectedModel` because we currently cannot access the
// default model title in the GUI from JB
applyToCurrentFile: [
{ text: string; streamId: string; curSelectedModelTitle: string },
void,
];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];

View file

@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Prompt Logs" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="tail -f ./binary/.continue/logs/prompt.log" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="false" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2" />
</configuration>
</component>

View file

@ -3,7 +3,7 @@
<toRun name="Run Extension" type="GradleRunConfiguration" />
<toRun name="Start Dev Server (core)" type="NodeJSConfigurationType" />
<toRun name="Start Dev Server (gui)" type="js.build_tools.npm" />
<toRun name="Tail Dev Logs" type="ShConfigurationType" />
<toRun name="Prompt Logs" type="ShConfigurationType" />
<method v="2" />
</configuration>
</component>

View file

@ -6,8 +6,6 @@ import com.intellij.diff.DiffContentFactory
import com.intellij.diff.DiffManager
import com.intellij.diff.DiffRequestPanel
import com.intellij.diff.contents.DiffContent
import com.intellij.diff.contents.DocumentContent
import com.intellij.diff.requests.DiffRequest
import com.intellij.diff.requests.SimpleDiffRequest
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
@ -18,7 +16,6 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.content.ContentFactory
import java.awt.Toolkit
import java.io.File
import java.nio.file.Paths
@ -51,10 +48,9 @@ interface DiffInfo {
class DiffManager(private val project: Project) : DumbAware {
private val diffContentFactory = DiffContentFactory.getInstance()
// Mapping from file2 to relevant info
private val diffInfoMap: MutableMap<String, DiffInfo> = mutableMapOf()
private var lastFile2: String? = null
fun showDiff(filepath: String, replacement: String, stepIndex: Int) {
val diffDir = getDiffDirectory()
@ -68,7 +64,7 @@ class DiffManager(private val project: Project) : DumbAware {
openDiffWindow(filepath, file.path, stepIndex)
}
fun cleanUpFile(file2: String) {
private fun cleanUpFile(file2: String) {
diffInfoMap[file2]?.dialog?.close(0)
diffInfoMap.remove(file2)
File(file2).delete()
@ -77,7 +73,6 @@ class DiffManager(private val project: Project) : DumbAware {
}
}
private var lastFile2: String? = null
fun acceptDiff(file2: String?) {
val file = (file2 ?: lastFile2) ?: return
@ -128,7 +123,7 @@ class DiffManager(private val project: Project) : DumbAware {
// Create a SimpleDiffRequest and populate it with the DiffContents and titles
val diffRequest = SimpleDiffRequest("Continue Diff", content1, content2, "Old", "New")
// Get a DiffRequestPanel from the DiffManager and set the DiffRequest to it
val diffInfo = diffInfoMap[file2]
@ -176,10 +171,10 @@ class DiffManager(private val project: Project) : DumbAware {
}
override fun createActions(): Array<Action> {
val okAction = getOKAction()
val okAction = okAction
okAction.putValue(Action.NAME, "Accept (${getAltKeyLabel()} ⇧ Y)")
val cancelAction = getCancelAction()
val cancelAction = cancelAction
cancelAction.putValue(Action.NAME, "Reject (${getAltKeyLabel()} ⇧ N)")
return arrayOf(okAction, cancelAction)

View file

@ -5,6 +5,8 @@ import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
@ -16,9 +18,9 @@ import com.intellij.execution.util.ExecUtil
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
@ -34,6 +36,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.psi.PsiDocumentManager
@ -48,6 +51,7 @@ import java.nio.charset.Charset
import java.nio.file.Paths
import java.util.*
fun uuid(): String {
return UUID.randomUUID().toString()
}
@ -550,7 +554,6 @@ class IdeProtocolClient(
}
"openFile" -> {
setFileOpen((data as Map<String, Any>)["path"] as String)
respond(null)
}
@ -619,7 +622,73 @@ class IdeProtocolClient(
}
}
"applyToFile" -> {
"applyToCurrentFile" -> {
val msg = data as Map<String, String>;
val text = msg["text"] as String
val curSelectedModelTitle = msg["curSelectedModelTitle"] as String
val config = readConfigJson()
var llm = getModelByRole(config, "applyCodeBlock")
if (llm == null) {
val models = (config as? Map<*, *>)?.get("models") as? List<Map<*, *>>
llm = models?.find { model -> model["title"] == curSelectedModelTitle } as Map<String, Any>
if (llm == null) {
showToast("error", "Model '$curSelectedModelTitle' not found in config.")
respond(null)
return@launch
}
}
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt =
"The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code."
val editor = FileEditorManager.getInstance(project).selectedTextEditor
if (editor == null) {
showToast("error", "No active editor to apply edits to")
respond(null)
return@launch
}
val rif = getHighlightedCode()
val (prefix, highlighted, suffix) = if (rif == null) {
// If no highlight, use the whole document as highlighted
Triple("", editor.document.text, "")
} else {
val prefix = editor.document.getText(TextRange(0, rif.range.start.character))
val highlighted = rif.contents
val suffix =
editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength))
// Remove the selection after processing
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
Triple(prefix, highlighted, suffix)
}
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
rif?.range?.start?.line ?: 0,
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
{}, {})
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.streamDiffLinesToEditor(
prompt, prefix, highlighted, suffix, llmTitle
)
respond(null)
}
"getGitHubAuthToken" -> {
@ -692,11 +761,11 @@ class IdeProtocolClient(
)
}
fun uniqueId(): String {
private fun uniqueId(): String {
return getMachineUniqueID()
}
suspend fun getBranch(dir: String): String = withContext(Dispatchers.IO) {
private suspend fun getBranch(dir: String): String = withContext(Dispatchers.IO) {
try {
val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
builder.directory(File(dir))
@ -715,7 +784,7 @@ class IdeProtocolClient(
data class IndexTag(val directory: String, val branch: String, val artifactId: String)
suspend fun getTags(artifactId: String): List<IndexTag> {
private suspend fun getTags(artifactId: String): List<IndexTag> {
val workspaceDirs = workspaceDirectories()
// Collect branches concurrently using Kotlin coroutines
@ -731,7 +800,7 @@ class IdeProtocolClient(
}
}
fun readFile(filepath: String): String {
private fun readFile(filepath: String): String {
try {
val content = ApplicationManager.getApplication().runReadAction<String?> {
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
@ -982,4 +1051,19 @@ class IdeProtocolClient(
command.setWorkDirectory(project.basePath)
return ExecUtil.execAndGetOutput(command).stdout ?: ""
}
private fun getModelByRole(
config: Any,
role: Any
): Any? {
val experimental = (config as? Map<*, *>)?.get("experimental") as? Map<*, *>
val roleTitle = (experimental?.get("modelRoles") as? Map<*, *>)?.get(role) as? String ?: return null
val models = (config as? Map<*, *>)?.get("models") as? List<*>
val matchingModel = models?.find { model ->
(model as? Map<*, *>)?.get("title") == roleTitle
}
return matchingModel
}
}

View file

@ -35,6 +35,7 @@ import { VsCodeWebviewProtocol } from "../webviewProtocol";
type TODO = any;
type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
ToWebviewFromCoreProtocol;
export class VsCodeMessenger {
onWebview<T extends keyof FromWebviewProtocol>(
messageType: T,
@ -149,7 +150,7 @@ export class VsCodeMessenger {
await vscode.commands.executeCommand("continue.rejectDiff", filepath);
});
this.onWebview("applyToCurrentFile", async (msg) => {
this.onWebview("applyToCurrentFile", async ({ data }) => {
// Get active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
@ -164,16 +165,11 @@ export class VsCodeMessenger {
let llm = getModelByRole(config, "applyCodeBlock");
if (!llm) {
const defaultModelTitle = await this.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
);
llm = config.models.find((model) => model.title === defaultModelTitle);
llm = config.models.find((model) => model.title === data.curSelectedModelTitle);
if (!llm) {
vscode.window.showErrorMessage(
`Model ${defaultModelTitle} not found in config.`,
`Model ${data.curSelectedModelTitle} not found in config.`,
);
return;
}
@ -184,20 +180,20 @@ export class VsCodeMessenger {
// Generate the diff and pass through diff manager
const [instant, diffLines] = await applyCodeBlock(
editor.document.getText(),
msg.data.text,
data.text,
getBasename(editor.document.fileName),
llm,
fastLlm,
);
const verticalDiffManager = await this.verticalDiffManagerPromise;
if (instant) {
verticalDiffManager.streamDiffLines(
await verticalDiffManager.streamDiffLines(
diffLines,
instant,
msg.data.streamId,
data.streamId,
);
} else {
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`;
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`;
const fullEditorRange = new vscode.Range(
0,
0,
@ -207,10 +203,11 @@ export class VsCodeMessenger {
const rangeToApplyTo = editor.selection.isEmpty
? fullEditorRange
: editor.selection;
verticalDiffManager.streamEdit(
await verticalDiffManager.streamEdit(
prompt,
llm.title,
msg.data.streamId,
data.streamId,
undefined,
undefined,
rangeToApplyTo,

View file

@ -29,6 +29,7 @@ import ButtonWithTooltip from "../ButtonWithTooltip";
import FileIcon from "../FileIcon";
import { CopyButton as CopyButtonHeader } from "./CopyButton";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
const ToolbarDiv = styled.div`
display: flex;
@ -127,6 +128,7 @@ function getTerminalCommand(text: string): string {
function CodeBlockToolBar(props: CodeBlockToolBarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useDispatch();
const defaultModel = useSelector(defaultModelSelector);
const isTerminal = isTerminalCodeBlock(props.language, props.text);
const [isCopied, setIsCopied] = useState(false);
const [isApplying, setIsApplying] = useState(false);
@ -148,6 +150,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
"applyCodeFromChat",
async () => {
await ideMessenger.request("applyToCurrentFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
});
@ -157,24 +160,25 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
!props.isNextCodeBlock,
);
function onClickCopy() {
async function onClickCopy() {
if (isJetBrains()) {
ideMessenger.request("copyText", { text: props.text });
await ideMessenger.request("copyText", { text: props.text });
} else {
navigator.clipboard.writeText(props.text);
await navigator.clipboard.writeText(props.text);
}
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
}
function onClickApply() {
async function onClickApply() {
if (isApplying) return;
if (isTerminal) {
ideMessenger.ide.runCommand(getTerminalCommand(props.text));
await ideMessenger.ide.runCommand(getTerminalCommand(props.text));
} else {
ideMessenger.post("applyToCurrentFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
});
@ -214,7 +218,9 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
);
}
if (!props.filepath) {
// Currently we only use the "old" apply logic in JetBrains. This check can be removed once
// we implement the "new" lazy apply logic.
if (!props.filepath || isJetBrains()) {
return (
<HoverDiv>
<InnerHoverDiv bottom={props.bottom || false}>
@ -284,69 +290,64 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
</div>
</ToolbarButton>
{!isJetBrains() && (
<div className="flex">
{applyState === "closed" ? (
<ToolbarButton
onClick={onClickApply}
<div className="flex">
{applyState === "closed" ? (
<ToolbarButton onClick={onClickApply} style={{ color: lightGray }}>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
<PlayIcon className="h-3 w-3" />
<span className="xs:inline hidden">Apply</span>
</div>
</ToolbarButton>
) : applyState === "done" ? (
<>
<ToolbarButtonWithTooltip
onClick={onClickReject}
tooltipContent={`${getMetaKeyLabel()}⇧⌫`}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Reject</span>
</div>
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
onClick={onClickAccept}
tooltipContent={`${getMetaKeyLabel()}⇧⏎`}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Accept</span>
</div>
</ToolbarButtonWithTooltip>
</>
) : (
<div className="mr-2 flex items-center">
<svg
className="h-4 w-4 animate-spin text-gray-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="2"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
<PlayIcon className="h-3 w-3" />
<span className="xs:inline hidden">Apply</span>
</div>
)}
</div>
)}
</ToolbarButton>
) : applyState === "done" ? (
<>
<ToolbarButtonWithTooltip
onClick={onClickReject}
tooltipContent={`${getMetaKeyLabel()}⇧⌫`}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Reject</span>
</div>
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
onClick={onClickAccept}
tooltipContent={`${getMetaKeyLabel()}⇧⏎`}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Accept</span>
</div>
</ToolbarButtonWithTooltip>
</>
) : (
<div className="mr-2 flex items-center">
<svg
className="h-4 w-4 animate-spin text-gray-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="2"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</div>
)}
</div>
</div>
</ToolbarDiv>
);