Merge branch 'nate/lazy-edit' of https://github.com/continuedev/continue into nate/lazy-edit

This commit is contained in:
Nate 2024-09-17 19:41:50 -07:00
commit 0a80637461
10 changed files with 194 additions and 108 deletions

View file

@ -119,7 +119,7 @@ export class Core {
(resolve) => (continueServerClientResolve = resolve),
);
ideSettingsPromise.then((ideSettings) => {
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
@ -136,7 +136,7 @@ export class Core {
);
// Index on initialization
this.ide.getWorkspaceDirs().then(async (dirs) => {
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
await this.messenger.request("indexProgress", {
@ -147,7 +147,7 @@ export class Core {
return;
}
this.refreshCodebaseIndex(dirs);
void this.refreshCodebaseIndex(dirs);
});
});
@ -172,11 +172,11 @@ export class Core {
this.messenger.onError((err) => {
console.error(err);
Telemetry.capture("core_messenger_error", {
void Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
this.ide.showToast("error", err.message);
void this.ide.showToast("error", err.message);
});
// New
@ -186,7 +186,7 @@ export class Core {
on("update/selectTabAutocompleteModel", async (msg) => {
this.globalContext.update("selectedTabAutocompleteModel", msg.data);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
// Special
@ -227,29 +227,29 @@ export class Core {
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/addOpenAiKey", (msg) => {
addOpenAIKey(msg.data);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/newPromptFile", async (msg) => {
createNewPromptFile(
void createNewPromptFile(
this.ide,
(await this.config()).experimental?.promptPath,
);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/reload", (msg) => {
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();
});
@ -272,9 +272,12 @@ export class Core {
}
if (hasFailed) {
this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`);
void this.ide.showToast(
"info",
`Successfully indexed ${msg.data.startUrl}`,
);
this.messenger.send("refreshSubmenuItems", undefined);
}
});
@ -331,7 +334,7 @@ export class Core {
fetchwithRequestOptions(url, init, config.requestOptions),
});
Telemetry.capture(
void Telemetry.capture(
"useContextProvider",
{
name: provider.description.title,
@ -344,7 +347,7 @@ export class Core {
id,
}));
} catch (e) {
this.ide.showToast(
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
@ -368,7 +371,7 @@ export class Core {
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
TTS.kill();
void TTS.kill();
}
const model = await configHandler.llmFromTitle(msg.data.title);
@ -396,7 +399,7 @@ export class Core {
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
TTS.read(next.value?.completion);
void TTS.read(next.value?.completion);
}
return { done: true, content: next.value };
@ -477,7 +480,7 @@ export class Core {
TTS.messenger = this.messenger;
on("tts/kill", async () => {
TTS.kill();
void TTS.kill();
});
async function* runNodeJsSlashCommand(
@ -506,7 +509,7 @@ export class Core {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
Telemetry.capture(
void Telemetry.capture(
"useSlashCommand",
{
name: slashCommandName,
@ -529,7 +532,7 @@ export class Core {
params,
ide,
addContextItem: (item) => {
messenger.request("addContextItem", {
void messenger.request("addContextItem", {
item,
historyIndex,
});
@ -636,7 +639,7 @@ export class Core {
editConfigJson(editConfigJsonCallback);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("addAutocompleteModel", (msg) => {
@ -646,7 +649,7 @@ export class Core {
tabAutocompleteModel: msg.data.model,
};
});
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("stats/getTokensPerDay", async (msg) => {
@ -674,13 +677,13 @@ export class Core {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.indexingState.status !== "loading") {
this.messenger.request("indexProgress", this.indexingState);
void this.messenger.request("indexProgress", this.indexingState);
}
});
on("didChangeSelectedProfile", (msg) => {
this.configHandler.setSelectedProfile(msg.data.id);
this.configHandler.reloadConfig();
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
@ -713,7 +716,7 @@ export class Core {
updateToSend.progress = 1.0;
}
this.messenger.request("indexProgress", updateToSend);
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
if (update.status === "failed") {
@ -722,7 +725,7 @@ export class Core {
update.desc,
update.debugInfo,
);
Telemetry.capture(
void Telemetry.capture(
"indexing_error",
{
error: update.desc,

View file

@ -281,7 +281,8 @@ ${prompt}`;
) {
let promptTokens = this.countTokens(prompt);
let generatedTokens = this.countTokens(completion);
Telemetry.capture(
void Telemetry.capture(
"tokens_generated",
{
model: model,
@ -291,12 +292,14 @@ ${prompt}`;
},
true,
);
DevDataSqliteDb.logTokensGenerated(
void DevDataSqliteDb.logTokensGenerated(
model,
this.providerName,
promptTokens,
generatedTokens,
);
logDevData("tokens_generated", {
model: model,
provider: this.providerName,
@ -342,11 +345,11 @@ ${prompt}`;
) {
if (resp.url.includes("codestral.mistral.ai")) {
throw new Error(
'You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting "apiBase" to "https://api.mistral.ai/v1" in config.json.',
"You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
);
} else {
throw new Error(
'You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting "apiBase" to "https://codestral.mistral.ai/v1" in config.json.',
"You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
);
}
}
@ -542,6 +545,7 @@ ${prompt}`;
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
@ -557,6 +561,17 @@ ${prompt}`;
return { role: "assistant" as ChatMessageRole, content: completion };
}
hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean {
const contentStr = typeof content === "string" ? content : content[0].text;
if (!contentStr) {
return false;
}
const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/;
return codeBlockRegex.test(contentStr);
}
async *streamChat(
_messages: ChatMessage[],
options: LLMFullCompletionOptions = {},
@ -604,6 +619,7 @@ ${prompt}`;
}
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}

View file

@ -20,6 +20,56 @@ class Anthropic extends BaseLLM {
apiBase: "https://api.anthropic.com/v1/",
};
static lazySystemMessage: string = `When generating new code:
1. Always produce a single code block.
2. Never separate the code into multiple code blocks.
3. Only include the code that is being added.
4. Replace existing code with a "lazy" block like this: "// ... existing code ..."
5. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
Example 1:
Input:
\`\`\`test.js
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
}
\`\`\`
User request: Add a subtract method
Output:
\`\`\`javascript test.js
class Calculator {
// ... existing code ...
subtract(number) {
this.result -= number;
return this;
}
}
\`\`\`
Example 2:
Input:
\`\`\`javascript test.js (6-9)
function helloWorld() {}
\`\`\`
Output:
\`\`\`javascript test.js
function helloWorld() {
// New code here
}
\`\`\`
Always follow these guidelines when generating code responses.`;
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
top_k: options.topK,
@ -78,6 +128,18 @@ class Anthropic extends BaseLLM {
const shouldCacheSystemMessage =
!!this.systemMessage && !!this.cacheSystemMessage;
// This likely should be set in the base class where we wrap
// _streamChat in a try/catch
let curSystemMsg = this.systemMessage;
// We only are doing lazy prompting with Sonnet right now
if (
this.hasCodeBlockWithFilename(messages[0].content) &&
options.model?.includes("sonnet")
) {
this.systemMessage = `${this.systemMessage} ${Anthropic.lazySystemMessage}`;
}
const response = await this.fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
@ -115,6 +177,8 @@ class Anthropic extends BaseLLM {
yield { role: "assistant", content: value.delta.text };
}
}
this.systemMessage = curSystemMsg;
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.212",
"version": "0.9.213",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.212",
"version": "0.9.213",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.212",
"version": "0.9.213",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -14,6 +14,7 @@ const FileIcon = ({
? filename.split(" ")
: [filename, ""];
filenameParts.pop();
const getIcon = themeIcons({
blue: "#268bd2",
grey: "#657b83",
@ -27,6 +28,7 @@ const FileIcon = ({
yellow: "#b58900",
ignore: "#586e75",
});
// Sanitize the SVG string before rendering it
const { svg, color } = getIcon(filenameParts.join(" "));
const sanitizedSVG = DOMPurify.sanitize(svg);

View file

@ -17,7 +17,7 @@ const ToolbarDiv = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
background: ${vscEditorBackground};
background: inherit;
font-size: ${getFontSize() - 2}px;
padding: 3px;
padding-left: 4px;
@ -46,6 +46,7 @@ interface CodeBlockToolBarProps {
bottom: boolean;
language: string | undefined;
isNextCodeBlock: boolean;
filename?: string;
}
const terminalLanguages = ["bash", "sh"];
@ -98,34 +99,66 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
!props.isNextCodeBlock,
);
function onClickHeader() {
// TODO: Need to turn into relative or fq path
ideMessenger.post("showFile", {
filepath: props.filename,
});
}
function onClickCopy(e) {
const text = typeof props.text === "string" ? props.text : props.text;
if (isJetBrains()) {
ideMessenger.request("copyText", { text });
} else {
navigator.clipboard.writeText(text);
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
function onClickActionButton() {
if (isTerminalCodeBlock(props.language, props.text)) {
let text = props.text;
if (text.startsWith("$ ")) {
text = text.slice(2);
}
ideMessenger.ide.runCommand(text);
return;
}
if (applying) return;
ideMessenger.post("applyToCurrentFile", {
text: props.text,
});
setApplying(true);
setTimeout(() => setApplying(false), 2000);
}
return (
<ToolbarDiv>
<div
className="flex items-center cursor-pointer py-0.5 px-0.5"
onClick={() => {
// Open the file
}}
onClick={onClickHeader}
>
<FileIcon filename="test.py" height="16px" width="16px" />
<span className="hover:brightness-125">{props.language}</span>
{props.filename && (
<>
<FileIcon
filename={props.filename || props.language}
height="18px"
width="18px"
/>
<span className="hover:brightness-125 ml-1">{props.filename}</span>{" "}
</>
)}
</div>
<div className="flex items-center">
<ToolbarButton
onClick={(e) => {
const text =
typeof props.text === "string" ? props.text : props.text;
if (isJetBrains()) {
ideMessenger.request("copyText", { text });
} else {
navigator.clipboard.writeText(text);
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}}
>
<div className="flex items-center">
<ToolbarButton onClick={onClickCopy}>
<div
className={`flex items-center gap-1 text-[${lightGray}] hover:brightness-125 transition-colors duration-200`}
className={`flex items-center gap-1 ] hover:brightness-125 transition-colors duration-200`}
style={{ color: lightGray }}
>
{copied ? (
<>
@ -134,10 +167,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
</>
) : (
<>
<ClipboardIcon
className="w-3 h-3 hover:brightness-125"
color={lightGray}
/>
<ClipboardIcon className="w-3 h-3 hover:brightness-125" />
<span>Copy</span>
</>
)}
@ -148,26 +178,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
<ToolbarButton
disabled={applying}
style={{ backgroundColor: vscEditorBackground }}
onClick={() => {
if (isTerminalCodeBlock(props.language, props.text)) {
let text = props.text;
if (text.startsWith("$ ")) {
text = text.slice(2);
}
ideMessenger.ide.runCommand(text);
return;
}
if (applying) return;
ideMessenger.post("applyToCurrentFile", {
text: props.text,
});
setApplying(true);
setTimeout(() => setApplying(false), 2000);
}}
onClick={onClickActionButton}
>
<div
className={`flex items-center gap-1 text-[${lightGray}] hover:brightness-125 transition-colors duration-200`}
className={`flex items-center gap-1 hover:brightness-125 transition-colors duration-200`}
style={{ color: lightGray }}
>
{applying ? (
<CheckIcon className="w-3 h-3 text-green-500" />
@ -184,15 +199,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
</div>
</ToolbarButton>
)}
{/* <ButtonWithTooltip
text="Insert at cursor"
style={{ backgroundColor: vscEditorBackground }}
onClick={() => {
ideMessenger.post("insertAtCursor", { text: props.text });
}}
>
<ArrowLeftEndOnRectangleIcon className="w-4 h-4" />
</ButtonWithTooltip> */}
</div>
</ToolbarDiv>
);

View file

@ -112,11 +112,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
}}
>
<div className="flex items-center">
<FileIcon
height="20px"
width="20px"
filename={props.item.name}
></FileIcon>
<FileIcon height="20px" width="20px" filename={props.item.name} />
{props.item.name}
</div>
<div className="flex items-center">

View file

@ -33,6 +33,7 @@ function PreWithToolbar(props: {
children: any;
language: string | null;
codeBlockIndex: number;
filename?: string | undefined;
}) {
const uiConfig = useUIConfig();
const toolbarBottom = uiConfig?.codeBlockToolbarPosition == "bottom";
@ -67,7 +68,8 @@ function PreWithToolbar(props: {
text={copyValue}
bottom={toolbarBottom}
language={props.language}
></CodeBlockToolBar>
filename={props.filename}
/>
{props.children}
</TopDiv>
);

View file

@ -51,19 +51,9 @@ const StyledMarkdown = styled.div<{
}
background-color: ${vscBackground};
font-family:
var(--vscode-font-family),
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
"Open Sans",
"Helvetica Neue",
sans-serif;
font-family: var(--vscode-font-family), system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell,
"Open Sans", "Helvetica Neue", sans-serif;
font-size: ${(props) => props.fontSize || getFontSize()}px;
padding-left: 8px;
padding-right: 8px;
@ -113,6 +103,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
} else if (node.lang.includes(".")) {
node.lang = node.lang.split(".").slice(-1)[0];
}
if (node.meta) {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.filename = node.meta;
}
});
};
},
@ -150,12 +146,13 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
);
},
pre: ({ node, ...preProps }) => {
const childrenClassName = preProps?.children?.[0]?.props?.className;
const { className, filename } = preProps?.children?.[0]?.props;
return props.showCodeBorder ? (
<PreWithToolbar
codeBlockIndex={preProps.codeBlockIndex}
language={getLanuageFromClassName(childrenClassName)}
language={getLanuageFromClassName(className)}
filename={filename}
>
<SyntaxHighlightedPre {...preProps}></SyntaxHighlightedPre>
</PreWithToolbar>