🎨 formatting + fix viewType of undefined

This commit is contained in:
Nate Sesti 2024-03-02 19:38:27 -05:00
parent e0fbc85967
commit d90e7dce92
4 changed files with 74 additions and 68 deletions

View file

@ -2,10 +2,13 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "..";
import { LineStream } from "../diff/util";
export async function* avoidPathLine(stream: LineStream, comment: string): LineStream {
export async function* avoidPathLine(
stream: LineStream,
comment: string,
): LineStream {
// Snippets are inserted as comments with a line at the start '// Path: <PATH>'.
// Sometimes the model with copy this pattern, which is unwanted
for await (const line of stream){
for await (const line of stream) {
if (line.startsWith(comment + " Path: ")) {
continue;
}
@ -29,7 +32,7 @@ const bracketsReverse = [")", "]", "}", "`", '"""'];
export async function* stopAtSimilarLine(
stream: LineStream,
line: string
line: string,
): AsyncGenerator<string> {
line = line.trim();
for await (const nextLine of stream) {
@ -50,9 +53,7 @@ export async function* stopAtSimilarLine(
}
}
const LINES_TO_STOP_AT = [
"# End of file."
]
const LINES_TO_STOP_AT = ["# End of file."];
export async function* stopAtLines(stream: LineStream): LineStream {
for await (const line of stream) {
@ -195,7 +196,7 @@ function isUselessLine(line: string): boolean {
}
export async function* filterLeadingAndTrailingNewLineInsertion(
diffLines: AsyncGenerator<DiffLine>
diffLines: AsyncGenerator<DiffLine>,
): AsyncGenerator<DiffLine> {
let isFirst = true;
let buffer: DiffLine[] = [];

View file

@ -94,7 +94,7 @@ export abstract class BaseLLM implements ILLM {
if (CompletionOptionsForModels[options.model as ModelName]) {
this.completionOptions = mergeJson(
this.completionOptions,
CompletionOptionsForModels[options.model as ModelName] || {}
CompletionOptionsForModels[options.model as ModelName] || {},
);
}
this.requestOptions = options.requestOptions;
@ -107,7 +107,7 @@ export abstract class BaseLLM implements ILLM {
autodetectTemplateFunction(
options.model,
this.providerName,
options.template
options.template,
);
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;
@ -131,7 +131,7 @@ export abstract class BaseLLM implements ILLM {
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
functions?: any[]
functions?: any[],
) {
let contextLength = this.contextLength;
if (
@ -150,7 +150,7 @@ export abstract class BaseLLM implements ILLM {
this.supportsImages(),
undefined,
functions,
this.systemMessage
this.systemMessage,
);
}
@ -176,7 +176,7 @@ export abstract class BaseLLM implements ILLM {
private _compileLogMessage(
prompt: string,
completionOptions: CompletionOptions
completionOptions: CompletionOptions,
): string {
const dict = { contextLength: this.contextLength, ...completionOptions };
const settings = Object.entries(dict)
@ -209,7 +209,7 @@ ${prompt}`;
protected fetch(
url: RequestInfo | URL,
init?: RequestInit
init?: RequestInit,
): Promise<Response> {
if (this._fetch) {
// Custom Node.js fetch
@ -219,7 +219,7 @@ ${prompt}`;
// Most of the requestOptions aren't available in the browser
const headers = new Headers(init?.headers);
for (const [key, value] of Object.entries(
this.requestOptions?.headers || {}
this.requestOptions?.headers || {},
)) {
headers.append(key, value as string);
}
@ -238,7 +238,7 @@ ${prompt}`;
const completionOptions: CompletionOptions = mergeJson(
this.completionOptions,
options
options,
);
return { completionOptions, log, raw };
@ -254,7 +254,7 @@ ${prompt}`;
async *streamComplete(
prompt: string,
options: LLMFullCompletionOptions = {}
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -263,7 +263,7 @@ ${prompt}`;
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
);
if (!raw) {
@ -302,7 +302,7 @@ ${prompt}`;
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
);
if (!raw) {
@ -338,7 +338,7 @@ ${prompt}`;
async *streamChat(
messages: ChatMessage[],
options: LLMFullCompletionOptions = {}
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, LLMReturnValue> {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -363,7 +363,7 @@ ${prompt}`;
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
completionOptions
completionOptions,
)) {
completion += chunk;
yield { role: "assistant", content: chunk };
@ -371,7 +371,7 @@ ${prompt}`;
} else {
for await (const chunk of this._streamChat(
messages,
completionOptions
completionOptions,
)) {
completion += chunk.content;
yield chunk;
@ -392,24 +392,24 @@ ${prompt}`;
protected async *_streamComplete(
prompt: string,
options: CompletionOptions
options: CompletionOptions,
): AsyncGenerator<string> {
throw new Error("Not implemented");
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (!this.templateMessages) {
throw new Error(
"You must either implement templateMessages or _streamChat"
"You must either implement templateMessages or _streamChat",
);
}
for await (const chunk of this._streamComplete(
this.templateMessages(messages),
options
options,
)) {
yield { role: "assistant", content: chunk };
}

View file

@ -6,48 +6,53 @@ export function mergeJson(
first: JsonObject,
second: JsonObject,
mergeBehavior?: ConfigMergeType,
mergeKeys?: {[key: string]: (a: any, b: any) => boolean}
mergeKeys?: { [key: string]: (a: any, b: any) => boolean },
): any {
first = { ...first };
const copyOfFirst = JSON.parse(JSON.stringify(first));
try {
for (var key in second) {
let secondValue = second[key];
if (!(key in first) || mergeBehavior === "overwrite") {
if (!(key in copyOfFirst) || mergeBehavior === "overwrite") {
// New value
first[key] = secondValue;
copyOfFirst[key] = secondValue;
continue;
}
const firstValue = first[key];
const firstValue = copyOfFirst[key];
if (Array.isArray(secondValue) && Array.isArray(firstValue)) {
// Array
if (mergeKeys?.[key]) {
// Merge keys are used to determine whether an item form the second object should override one from the first
let keptFromFirst: any[] = [];
firstValue.forEach((item: any) => {
if (!secondValue.some((item2: any) => mergeKeys[key](item, item2))) {
if (
!secondValue.some((item2: any) => mergeKeys[key](item, item2))
) {
keptFromFirst.push(item);
}
})
first[key] = [...keptFromFirst, ...secondValue];
});
copyOfFirst[key] = [...keptFromFirst, ...secondValue];
} else {
first[key] = [...firstValue, ...secondValue];
copyOfFirst[key] = [...firstValue, ...secondValue];
}
} else if (typeof secondValue === "object" && typeof firstValue === "object") {
} else if (
typeof secondValue === "object" &&
typeof firstValue === "object"
) {
// Object
first[key] = mergeJson(firstValue, secondValue, mergeBehavior);
copyOfFirst[key] = mergeJson(firstValue, secondValue, mergeBehavior);
} else {
// Other (boolean, number, string)
first[key] = secondValue;
copyOfFirst[key] = secondValue;
}
}
return first;
return copyOfFirst;
} catch (e) {
console.error("Error merging JSON", e, first, second);
console.error("Error merging JSON", e, copyOfFirst, second);
return {
...first,
...copyOfFirst,
...second,
};
}

View file

@ -16,13 +16,13 @@ import { VsCodeWebviewProtocol } from "./webviewProtocol";
function getFullScreenTab() {
const tabs = vscode.window.tabGroups.all.flatMap((tabGroup) => tabGroup.tabs);
return tabs.find(
(tab) => (tab.input as any).viewType?.endsWith("continue.continueGUIView")
(tab) => (tab.input as any)?.viewType?.endsWith("continue.continueGUIView"),
);
}
function addHighlightedCodeToContext(
edit: boolean,
webviewProtocol: VsCodeWebviewProtocol | undefined
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const editor = vscode.window.activeTextEditor;
if (editor) {
@ -54,7 +54,7 @@ function addHighlightedCodeToContext(
async function addEntireFileToContext(
filepath: vscode.Uri,
edit: boolean,
webviewProtocol: VsCodeWebviewProtocol | undefined
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(filepath);
@ -65,7 +65,7 @@ async function addEntireFileToContext(
addEntireFileToContext(
vscode.Uri.joinPath(filepath, filename),
edit,
webviewProtocol
webviewProtocol,
);
}
}
@ -101,14 +101,14 @@ const commandsMap: (
sidebar: ContinueGUIWebviewViewProvider,
configHandler: ConfigHandler,
diffManager: DiffManager,
verticalDiffManager: VerticalPerLineDiffManager
verticalDiffManager: VerticalPerLineDiffManager,
) => { [command: string]: (...args: any) => any } = (
ide,
extensionContext,
sidebar,
configHandler,
diffManager,
verticalDiffManager
verticalDiffManager,
) => ({
"continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => {
if (newFilepath instanceof vscode.Uri) {
@ -154,7 +154,7 @@ const commandsMap: (
}
sidebar.webviewProtocol?.request(
"focusContinueInputWithoutClear",
undefined
undefined,
);
addHighlightedCodeToContext(true, sidebar.webviewProtocol);
},
@ -200,7 +200,7 @@ const commandsMap: (
{
title: "Add Context",
canPickMany: true,
}
},
);
let text = await vscode.window.showInputBox({
@ -217,7 +217,7 @@ const commandsMap: (
selectedProviders?.map((providerTitle) => {
const provider = config.contextProviders?.find(
(provider) =>
provider.description.title === providerTitle.description
provider.description.title === providerTitle.description,
);
if (!provider) {
return [];
@ -230,7 +230,7 @@ const commandsMap: (
fullInput: text || "",
selectedCode: [],
});
}) || []
}) || [],
)
).flat();
@ -245,12 +245,12 @@ const commandsMap: (
},
"continue.writeCommentsForCode": async () => {
await verticalDiffManager.streamEdit(
"Write comments for this code. Do not change anything about the code itself."
"Write comments for this code. Do not change anything about the code itself.",
);
},
"continue.writeDocstringForCode": async () => {
await verticalDiffManager.streamEdit(
"Write a docstring for this code. Do not change anything about the code itself."
"Write a docstring for this code. Do not change anything about the code itself.",
);
},
"continue.fixCode": async () => {
@ -261,7 +261,7 @@ const commandsMap: (
},
"continue.fixGrammar": async () => {
await verticalDiffManager.streamEdit(
"If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing."
"If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.",
);
},
"continue.viewLogs": async () => {
@ -312,12 +312,12 @@ const commandsMap: (
startLine,
0,
endLine,
0
0,
);
},
"continue.foldAndUnfold": (
foldSelectionLines: number[],
unfoldSelectionLines: number[]
unfoldSelectionLines: number[],
) => {
vscode.commands.executeCommand("editor.unfold", {
selectionLines: unfoldSelectionLines,
@ -357,7 +357,7 @@ const commandsMap: (
vscode.commands.executeCommand(
"vscode.open",
(fullScreenTab.input as any).uri,
openOptions
openOptions,
);
return;
}
@ -369,7 +369,7 @@ const commandsMap: (
const panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
"Continue",
vscode.ViewColumn.One
vscode.ViewColumn.One,
);
panel.webview.html = sidebar.getSidebarContent(
extensionContext,
@ -379,12 +379,12 @@ const commandsMap: (
verticalDiffManager,
undefined,
undefined,
true
true,
);
},
"continue.selectFilesAsContext": (
firstUri: vscode.Uri,
uris: vscode.Uri[]
uris: vscode.Uri[],
) => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
@ -400,12 +400,12 @@ const commandsMap: (
}
const position = editor.selection.active;
sidebar.sendMainUserInput(
`/references ${filepath.fsPath} ${position.line} ${position.character}`
`/references ${filepath.fsPath} ${position.line} ${position.character}`,
);
},
"continue.logAutocompleteOutcome": (
outcome: AutocompleteOutcome,
logRejectionTimeout: NodeJS.Timeout
logRejectionTimeout: NodeJS.Timeout,
) => {
clearTimeout(logRejectionTimeout);
outcome.accepted = true;
@ -415,8 +415,8 @@ const commandsMap: (
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit
})
cacheHit: outcome.cacheHit,
});
},
"continue.toggleTabAutocompleteEnabled": () => {
const config = vscode.workspace.getConfiguration("continue");
@ -424,7 +424,7 @@ const commandsMap: (
config.update(
"enableTabAutocomplete",
!enabled,
vscode.ConfigurationTarget.Global
vscode.ConfigurationTarget.Global,
);
},
});
@ -436,7 +436,7 @@ export function registerAllCommands(
sidebar: ContinueGUIWebviewViewProvider,
configHandler: ConfigHandler,
diffManager: DiffManager,
verticalDiffManager: VerticalPerLineDiffManager
verticalDiffManager: VerticalPerLineDiffManager,
) {
for (const [command, callback] of Object.entries(
commandsMap(
@ -445,11 +445,11 @@ export function registerAllCommands(
sidebar,
configHandler,
diffManager,
verticalDiffManager
)
verticalDiffManager,
),
)) {
context.subscriptions.push(
vscode.commands.registerCommand(command, callback)
vscode.commands.registerCommand(command, callback),
);
}
}