diff --git a/.vscode/settings.json b/.vscode/settings.json index 4a982ecff..22d8d3287 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -20,6 +20,7 @@ "binary/build/**": true, "binary/out/**": true, "binary/tmp/**": true, + "core/edit/lazy/test-examples/**": true, "core/llm/llamaTokenizer.js": true, "core/llm/llamaTokenizer.mjs": true, "core/vendor/**": true, diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index 78aed69a7..a954dda84 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -1,30 +1,9 @@ -import { TYPESCRIPT_TEST_CASES } from "./testCases/typescript"; +import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases"; import { testRootPathContext } from "./testUtils"; const TEST_CASES = [ + ...PYTHON_TEST_CASES, ...TYPESCRIPT_TEST_CASES, - { - nodeType: "function_definition", - fileName: "file1.py", - language: "Python", - cursorPosition: { line: 4, character: 25 }, - definitionPositions: [ - { row: 3, column: 30 }, // Person - { row: 3, column: 42 }, // Address - ], - }, - { - nodeType: "function_definition (inside a class)", - fileName: "file1.py", - language: "Python", - cursorPosition: { line: 12, character: 33 }, - definitionPositions: [ - { row: 6, column: 21 }, // BaseClass - { row: 6, column: 33 }, // Collection - { row: 11, column: 47 }, // Person - { row: 11, column: 59 }, // Address - ], - }, { nodeType: "function_definition", fileName: "file1.php", diff --git a/core/autocomplete/context/root-path-context/test/files/file1.py b/core/autocomplete/context/root-path-context/test/files/file1.py deleted file mode 100644 index 55c3d9c25..000000000 --- a/core/autocomplete/context/root-path-context/test/files/file1.py +++ /dev/null @@ -1,13 +0,0 @@ -from .base_module import BaseClass, Collection, Person, Address -from typing import List - -def get_address(person: Person) -> Address: - return person.address - -class Group(BaseClass, Collection): - def __init__(self, people: List[Person]) -> None: - super().__init__() - self.people = people - - def get_person_address(self, person: Person) -> Address: - return get_address(person) diff --git a/core/autocomplete/context/root-path-context/test/files/python/classes.py b/core/autocomplete/context/root-path-context/test/files/python/classes.py new file mode 100644 index 000000000..d752d8433 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/python/classes.py @@ -0,0 +1,11 @@ +class Group(BaseClass, Person): + pass + +class Group(metaclass=MetaGroup): + pass + +class Group(BaseClass[Address], Gathering[Person]): + pass + +class Group(List[Address], Person[str]): + pass \ No newline at end of file diff --git a/core/autocomplete/context/root-path-context/test/files/python/functions.py b/core/autocomplete/context/root-path-context/test/files/python/functions.py new file mode 100644 index 000000000..74a9d8b58 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/python/functions.py @@ -0,0 +1,42 @@ +from typing import List, Union, TypeVar, Generic + +T = TypeVar('T') + +class Address: + pass + +class Person: + pass + +class PersonWithGeneric(Generic[T]): + pass + + +def get_address(person: Person) -> Address: + pass + +def get_group_address(people: Group[Person]) -> Group[Address]: + pass + +def log_person(person: Person) -> None: + pass + +def get_hardcoded_address() -> Address: + pass + +def log_person_or_address(value: Union[Person, Address]) -> Union[Person, Address]: + pass + +def log_person_and_address(person: Person, address: Address) -> None: + pass + +def get_address_generator(person: Person) -> Generator[Address, None, None]: + yield + + +class Group: + def log_person_and_address(self, person: Person, address: Address) -> None: + pass + +async def get_person(address: Address) -> Person: + pass \ No newline at end of file diff --git a/core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts b/core/autocomplete/context/root-path-context/test/files/typescript/arrowFunctions.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/arrowFunctions.ts diff --git a/core/autocomplete/context/root-path-context/test/files/classMethods.ts b/core/autocomplete/context/root-path-context/test/files/typescript/classMethods.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/classMethods.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/classMethods.ts diff --git a/core/autocomplete/context/root-path-context/test/files/classes.ts b/core/autocomplete/context/root-path-context/test/files/typescript/classes.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/classes.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/classes.ts diff --git a/core/autocomplete/context/root-path-context/test/files/functions.ts b/core/autocomplete/context/root-path-context/test/files/typescript/functions.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/functions.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/functions.ts diff --git a/core/autocomplete/context/root-path-context/test/files/generators.ts b/core/autocomplete/context/root-path-context/test/files/typescript/generators.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/generators.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/generators.ts diff --git a/core/autocomplete/context/root-path-context/test/testCases/index.ts b/core/autocomplete/context/root-path-context/test/testCases/index.ts new file mode 100644 index 000000000..7859fc23d --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/testCases/index.ts @@ -0,0 +1,2 @@ +export * from "./python"; +export * from "./typescript"; diff --git a/core/autocomplete/context/root-path-context/test/testCases/python.ts b/core/autocomplete/context/root-path-context/test/testCases/python.ts new file mode 100644 index 000000000..9c8d46e43 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/testCases/python.ts @@ -0,0 +1,145 @@ +export const FUNCTIONS = [ + { + nodeType: "function_definition with argument and return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 15, character: 8 }, + definitionPositions: [ + { row: 14, column: 30 }, // Person + { row: 14, column: 42 }, // Address + ], + }, + { + nodeType: + "function_definition with generic argument and generic return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 18, character: 8 }, + definitionPositions: [ + { row: 17, column: 35 }, // Group + { row: 17, column: 42 }, // Person + { row: 17, column: 53 }, // Group + { row: 17, column: 61 }, // Address + ], + }, + { + nodeType: "function_definition with single argument and None return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 21, character: 8 }, + definitionPositions: [ + { row: 20, column: 29 }, // Person + ], + }, + { + nodeType: "function_definition with no arguments and single return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 24, character: 8 }, + definitionPositions: [ + { row: 23, column: 38 }, // Address + ], + }, + { + nodeType: "function_definition with Union arguments and Union return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 27, character: 8 }, + definitionPositions: [ + { row: 26, column: 45 }, // Person + { row: 26, column: 54 }, // Address + { row: 26, column: 72 }, // Person + { row: 26, column: 81 }, // Address + ], + }, + { + nodeType: + "function_definition with multiple arguments and None return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 30, character: 8 }, + definitionPositions: [ + { row: 29, column: 41 }, // Person + { row: 29, column: 59 }, // Address + ], + }, + { + nodeType: "function_definition with one argument and Generator return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 33, character: 9 }, + definitionPositions: [ + { row: 32, column: 40 }, // Person + { row: 32, column: 62 }, // Address + ], + }, + { + nodeType: "function_definition inside a class", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 38, character: 12 }, + definitionPositions: [ + { row: 37, column: 51 }, // Person + { row: 37, column: 69 }, // Address + ], + }, + { + nodeType: "function_definition of an async function", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 41, character: 8 }, + definitionPositions: [ + { row: 40, column: 37 }, // Address + { row: 40, column: 48 }, // Person + ], + }, +]; + +export const CLASSES = [ + { + nodeType: "class_definition with multiple superclasses", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 1, character: 8 }, + definitionPositions: [ + { row: 0, column: 21 }, // BaseClass + { row: 0, column: 29 }, // Person + ], + }, + { + nodeType: "class_definition with multiple superclasses", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 4, character: 8 }, + definitionPositions: [ + { row: 3, column: 31 }, // MetaGroup + ], + }, + { + nodeType: "class_definition with generic superclasses", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 7, character: 8 }, + definitionPositions: [ + { row: 6, column: 21 }, // BaseClass + { row: 6, column: 29 }, // Address + { row: 6, column: 41 }, // Gathering + { row: 6, column: 48 }, // Person + ], + }, + { + nodeType: "class_definition with generic superclasses (built in types)", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 10, character: 8 }, + definitionPositions: [ + { row: 9, column: 24 }, // Address + { row: 9, column: 33 }, // Person + ], + }, +]; + +export const PYTHON_TEST_CASES = [ + // ...FUNCTIONS, + ...CLASSES, +]; diff --git a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts index f945a02a9..ddda2bfde 100644 --- a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts +++ b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts @@ -1,7 +1,7 @@ const FUNCTIONS = [ { nodeType: "function_declaration with a param and a return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 3, character: 9 }, definitionPositions: [ @@ -11,7 +11,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration with array param", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 7, character: 9 }, definitionPositions: [ @@ -21,7 +21,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration without return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 11, character: 9 }, definitionPositions: [ @@ -30,7 +30,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration without params", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 15, character: 9 }, definitionPositions: [ @@ -39,7 +39,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration with array params and array return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 19, character: 9 }, definitionPositions: [ @@ -50,7 +50,7 @@ const FUNCTIONS = [ { nodeType: "function_declaration with generic params and generic return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 23, character: 9 }, definitionPositions: [ @@ -63,7 +63,7 @@ const FUNCTIONS = [ { nodeType: "function_declaration with union type params and union return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 27, character: 9 }, definitionPositions: [ @@ -75,7 +75,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration with two arguments", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 31, character: 9 }, definitionPositions: [ @@ -88,7 +88,7 @@ const FUNCTIONS = [ const GENERATORS = [ { nodeType: "function_declaration with a param and a return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 3, character: 9 }, definitionPositions: [ @@ -98,7 +98,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration with array param", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 7, character: 9 }, definitionPositions: [ @@ -108,7 +108,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration without return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 11, character: 9 }, definitionPositions: [ @@ -117,7 +117,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration without params", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 15, character: 9 }, definitionPositions: [ @@ -126,7 +126,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration with array params and array return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 19, character: 9 }, definitionPositions: [ @@ -137,7 +137,7 @@ const GENERATORS = [ { nodeType: "function_declaration with generic params and generic return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 23, character: 9 }, definitionPositions: [ @@ -150,7 +150,7 @@ const GENERATORS = [ { nodeType: "function_declaration with union type params and union return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 27, character: 9 }, definitionPositions: [ @@ -162,7 +162,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration with two arguments", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 31, character: 9 }, definitionPositions: [ @@ -175,7 +175,7 @@ const GENERATORS = [ const ARROW_FUNCTIONS = [ { nodeType: "arrow_function with a param and a return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 3, character: 9 }, definitionPositions: [ @@ -185,7 +185,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function without return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 7, character: 9 }, definitionPositions: [ @@ -194,7 +194,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function without params", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 11, character: 9 }, definitionPositions: [ @@ -203,7 +203,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with array params and array return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 15, character: 9 }, definitionPositions: [ @@ -213,7 +213,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with generic params and generic return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 19, character: 9 }, definitionPositions: [ @@ -225,7 +225,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with union type params and union return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 23, character: 9 }, definitionPositions: [ @@ -237,7 +237,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with two arguments", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 27, character: 11 }, definitionPositions: [ @@ -250,7 +250,7 @@ const ARROW_FUNCTIONS = [ const CLASS_METHODS = [ { nodeType: "method_declaration with a param and a return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 4, character: 11 }, definitionPositions: [ @@ -260,7 +260,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration without arguments", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 8, character: 11 }, definitionPositions: [ @@ -269,7 +269,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration without return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 12, character: 11 }, definitionPositions: [ @@ -278,7 +278,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration with array type arguments", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 16, character: 11 }, definitionPositions: [ @@ -288,7 +288,7 @@ const CLASS_METHODS = [ { nodeType: "method_declaration with array type arguments and array type return", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 20, character: 11 }, definitionPositions: [ @@ -299,7 +299,7 @@ const CLASS_METHODS = [ { nodeType: "method_declaration with with generic params and generic return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 24, character: 11 }, definitionPositions: [ @@ -311,7 +311,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration with union type params and union return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 28, character: 11 }, definitionPositions: [ @@ -323,7 +323,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration with two arguments", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 32, character: 11 }, definitionPositions: [ @@ -336,7 +336,7 @@ const CLASS_METHODS = [ const CLASS_DEFINITIONS = [ { nodeType: "class_declaration with base class", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 2, character: 31 }, definitionPositions: [ @@ -345,7 +345,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with interface", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 4, character: 39 }, definitionPositions: [ @@ -354,7 +354,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with base class and multiple interfaces", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 6, character: 74 }, definitionPositions: [ @@ -365,7 +365,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with base class and multiple interfaces", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 6, character: 74 }, definitionPositions: [ @@ -376,7 +376,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with generic base class and generic interface", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 8, character: 69 }, definitionPositions: [ diff --git a/core/autocomplete/filtering/BracketMatchingService.ts b/core/autocomplete/filtering/BracketMatchingService.ts index d4415259e..da7d38e61 100644 --- a/core/autocomplete/filtering/BracketMatchingService.ts +++ b/core/autocomplete/filtering/BracketMatchingService.ts @@ -1,3 +1,13 @@ +export const BRACKETS: { [key: string]: string } = { + "(": ")", + "{": "}", + "[": "]", +}; +export const BRACKETS_REVERSE: { [key: string]: string } = { + ")": "(", + "}": "{", + "]": "[", +}; /** * We follow the policy of only completing bracket pairs that we started * But sometimes we started the pair in a previous autocomplete suggestion @@ -6,30 +16,18 @@ export class BracketMatchingService { private openingBracketsFromLastCompletion: string[] = []; private lastCompletionFile: string | undefined = undefined; - static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" }; - static BRACKETS_REVERSE: { [key: string]: string } = { - ")": "(", - "}": "{", - "]": "[", - }; - handleAcceptedCompletion(completion: string, filepath: string) { this.openingBracketsFromLastCompletion = []; const stack: string[] = []; for (let i = 0; i < completion.length; i++) { const char = completion[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { break; } } @@ -63,17 +61,12 @@ export class BracketMatchingService { (prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? ""); for (let i = 0; i < currentLine.length; i++) { const char = currentLine[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { break; } } @@ -87,7 +80,7 @@ export class BracketMatchingService { if (suffix[i] === " ") { continue; } - const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; + const openBracket = BRACKETS_REVERSE[suffix[i]]; if (!openBracket) { break; } @@ -115,19 +108,14 @@ export class BracketMatchingService { const allLines = all.split("\n"); for (let i = 0; i < chunk.length; i++) { const char = chunk[i]; - if (Object.values(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { // If the stack is empty or the top of the stack doesn't match the current closing bracket yield chunk.slice(0, i); return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream } - } else if ( - Object.keys(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); } diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 5576ee26b..6097ff797 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -6,6 +6,7 @@ import { stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, avoidPathLine, + noDoubleNewlineAfterClosingBracket, showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, @@ -47,6 +48,7 @@ export class StreamTransformPipeline { ); lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); lineGenerator = skipPrefixes(lineGenerator); + lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator); for (const lineFilter of helper.lang.lineFilters ?? []) { lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 8c7936e2d..160fc9d85 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -2,6 +2,7 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService"; export type LineFilter = (args: { lines: LineStream; @@ -545,3 +546,43 @@ export async function* showWhateverWeHaveAtXMs( } } } + +export async function* noDoubleNewlineAfterClosingBracket( + lines: LineStream, +): LineStream { + const bracketTypeCounts = new Map(); + + for await (const line of lines) { + if (line.trim() === "") { + // Double newline detected + // Check if any bracket counts are negative + let hasNegativeCount = false; + for (const count of bracketTypeCounts.values()) { + if (count < 0) { + hasNegativeCount = true; + break; + } + } + if (hasNegativeCount) { + // Stop the generator if we've closed brackets we didn't open + return; + } + } + + yield line; + + // Update bracket counts + for (const char of line) { + if (BRACKETS[char]) { + // It's an opening bracket + const count = bracketTypeCounts.get(char) || 0; + bracketTypeCounts.set(char, count + 1); + } else if (BRACKETS_REVERSE[char]) { + // It's a closing bracket + const openingBracket = BRACKETS_REVERSE[char]; + const count = bracketTypeCounts.get(openingBracket) || 0; + bracketTypeCounts.set(openingBracket, count - 1); + } + } + } +} diff --git a/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts new file mode 100644 index 000000000..a25b5d4bf --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts @@ -0,0 +1,166 @@ +import { noDoubleNewlineAfterClosingBracket } from "./lineStream"; + +describe("noDoubleNewlineAfterClosingBracket", () => { + // Helper function to convert an array to an async generator + async function* arrayToAsyncGenerator(array: T[]): AsyncGenerator { + for (const item of array) { + yield item; + } + } + + // Helper function to collect lines from the async generator + async function collectLines(lines: AsyncIterable): Promise { + const result: string[] = []; + for await (const line of lines) { + result.push(line); + } + return result; + } + + test("should yield all lines when no double newline and no unmatched brackets", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should yield all lines when double newline but brackets are matched", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + "", + "", + "// End of function", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => { + const inputLines = [ + // "function test() {", + ' console.log("Hello World");', + // Unmatched closing bracket + "}", + "", + "", + "// This should not be yielded", + 'console.log("End");', + ]; + const expectedOutputLines = [' console.log("Hello World");', "}"]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(expectedOutputLines); + }); + + test("should yield all lines when unmatched brackets but no double newline", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + // Unmatched closing bracket + ")", + "// Continue code", + 'console.log("End");', + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should continue yielding if unmatched closing bracket occurs after double newline", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + "", + "", + // Unmatched closing bracket after double newline + ")", + 'console.log("End");', + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should yield all lines when brackets are matched even with double newline", async () => { + const inputLines = [ + "const arr = [", + " 1, 2, 3,", + "];", + "", + "", + "console.log(arr);", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should stop yielding when unmatched closing bracket occurs before double newline", async () => { + const inputLines = [ + "if (condition) {", + " doSomething();", + "}", + // Unmatched closing bracket + "}", + "", + "", + "doSomethingElse();", + ]; + const expectedOutputLines = [ + "if (condition) {", + " doSomething();", + "}", + "}", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(expectedOutputLines); + }); + + test("should yield all lines when no unmatched closing brackets and double newline", async () => { + const inputLines = [ + "while (true) {", + " // Infinite loop", + "}", + "", + "", + "// Loop exited", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); +}); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 406faf66f..f0584ab48 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -63,7 +63,7 @@ function sayHello() { `, llmOutput: `world!"); `, - expectedCompletion: "world!\");", + expectedCompletion: 'world!");', }, { description: "Should autocomplete Java when inside a block", @@ -131,10 +131,6 @@ public class Calculator { } `, expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; }`, }, { @@ -489,8 +485,8 @@ echo calculateArea(5, 3);`, $colors = array("Red", "Green", <|fim|>); echo "First color is: " . $colors[0];`, - llmOutput: "\"Blue\"", - expectedCompletion: "\"Blue\"", + llmOutput: '"Blue"', + expectedCompletion: '"Blue"', filename: "colors.php", }, { @@ -775,8 +771,10 @@ func main() { FROM users u WHERE u.active = 1 <|fim|>`, - llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", - expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + llmOutput: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + expectedCompletion: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", }, { description: @@ -817,8 +815,8 @@ func main() {

Description text.

`, - llmOutput: "alt=\"Description of image\"", - expectedCompletion: "alt=\"Description of image\"", + llmOutput: 'alt="Description of image"', + expectedCompletion: 'alt="Description of image"', filename: "test.html", }, { @@ -930,8 +928,8 @@ public class App { <|fim|> ] }`, - llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }", - expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }", + llmOutput: ', { "id": 3, "name": "Charlie" }', + expectedCompletion: ', { "id": 3, "name": "Charlie" }', }, { description: "Should autocomplete within a CSV record", @@ -1237,8 +1235,8 @@ class Counter { :age 30 <|fim|> (println "User information loaded"))`, - llmOutput: ":location \"Unknown\"}", - expectedCompletion: ":location \"Unknown\"}", + llmOutput: ':location "Unknown"}', + expectedCompletion: ':location "Unknown"}', filename: "test.clj", }, { @@ -1301,8 +1299,8 @@ if (grade >= 90) { } else { print("C") }`, - llmOutput: "print(\"B\")", - expectedCompletion: "print(\"B\")", + llmOutput: 'print("B")', + expectedCompletion: 'print("B")', }, { description: "Should autocomplete R ggplot2 plot structure", @@ -1324,8 +1322,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) + <|fim|> } }`, - llmOutput: "s\"Hello, my name is $name and I am $age years old.\"", - expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"", + llmOutput: 's"Hello, my name is $name and I am $age years old."', + expectedCompletion: 's"Hello, my name is $name and I am $age years old."', }, { @@ -1335,8 +1333,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) + case class Person(name: String, age: Int, address: Address) val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, - llmOutput: "\"12345\")", - expectedCompletion: "\"12345\")", + llmOutput: '"12345")', + expectedCompletion: '"12345")', }, { @@ -2066,8 +2064,8 @@ export default { /> `, - llmOutput: "name=\"World\"", - expectedCompletion: "name=\"World\"", + llmOutput: 'name="World"', + expectedCompletion: 'name="World"', }, { diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts new file mode 100644 index 000000000..2454377d3 --- /dev/null +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -0,0 +1,215 @@ +import { jest } from "@jest/globals"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +function createMockGenerator( + data: string[], + delay: number = 0, +): () => AsyncGenerator { + const mockGenerator = async function* () { + for (const chunk of data) { + yield chunk; + + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + }; + const newGenerator = jest + .fn<() => AsyncGenerator>() + .mockReturnValue(mockGenerator()); + + return newGenerator; +} + +describe("GeneratorReuseManager", () => { + let reuseManager: GeneratorReuseManager; + let onErrorMock: jest.Mock; + + beforeEach(() => { + onErrorMock = jest.fn(); + reuseManager = new GeneratorReuseManager(onErrorMock); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test("creates new generator when there is no current generator", async () => { + const data = ["hello ", "world"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("reuses generator when prefix matches pending completion", async () => { + const newGenerator = createMockGenerator(["llo ", "world"]); + + // First call with initial prefix + const prefix1 = "he"; + const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); + + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + } + + expect(output1).toEqual(["llo ", "world"]); + + // Second call with extended prefix that matches pending completion + const prefix2 = "hello "; + const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); + + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + expect(output2).toEqual(["world"]); + + // Ensure generator was reused (newGenerator should be called only once) + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("creates new generator when prefix does not match pending completion", async () => { + const data = ["goodbye ", "world"]; + const newGenerator = createMockGenerator(data); + + // Initial generator with different prefix + reuseManager.pendingGeneratorPrefix = "hello "; + reuseManager.pendingCompletion = "world"; + + const prefix = "good"; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + // Ensure a new generator was created + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("handles multiline=false by stopping at newline", async () => { + const data = ["first line\n", "second line"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, false); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(["first line"]); + // Ensure it stops after the first newline + }); + + test("handles multiline=true by not stopping at newline", async () => { + const data = ["first line\n", "second line"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + }); + + test("cancels previous generator when creating a new one", async () => { + const data1 = ["data from generator 1", "not generated"]; + const data2 = ["data from generator 2"]; + + const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it + const newGenerator2 = createMockGenerator(data2); + + const prefix1 = "prefix1"; + const prefix2 = "prefix2"; + + // First generator + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + // Simulate the generator being canceled before completing + reuseManager.currentGenerator?.cancel(); + } + + expect(output1.length).toEqual(1); + expect(output1[0]).toEqual(data1[0]); + + // Second generator + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + expect(output2).toEqual(data2); + }); + + test("calls onError when generator throws an error", async () => { + const error = new Error("Generator error"); + const mockGenerator = async function* () { + throw error; + }; + const newGenerator = jest + .fn<() => AsyncGenerator>() + .mockReturnValue(mockGenerator()); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + await expect(async () => { + for await (const chunk of generator) { + output.push(chunk); + } + }).not.toThrow(); // getGenerator handles errors internally + + expect(onErrorMock).toHaveBeenCalledWith(error); + expect(output).toEqual([]); + }); + + test("handles backspacing by creating new generator when prefix is shorter", async () => { + const data = ["hello world"]; + const newGenerator1 = createMockGenerator(data); + const newGenerator2 = createMockGenerator(data); + + // First prefix + const prefix1 = "hello world"; + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + } + + // Simulate backspace (prefix is shorter) + const prefix2 = "hello worl"; + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + // Ensure a new generator was created + expect(newGenerator1).toHaveBeenCalledTimes(1); + expect(newGenerator2).toHaveBeenCalledTimes(1); + }); +}); diff --git a/core/autocomplete/generation/GeneratorReuseManager.ts b/core/autocomplete/generation/GeneratorReuseManager.ts index 7a67e686f..0b19183ce 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -21,47 +21,54 @@ export class GeneratorReuseManager { this.currentGenerator = listenableGen; } + private shouldReuseExistingGenerator(prefix: string): boolean { + return ( + !!this.currentGenerator && + !!this.pendingGeneratorPrefix && + (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( + prefix, + ) && + // for e.g. backspace + this.pendingGeneratorPrefix?.length <= prefix?.length + ); + } + async *getGenerator( prefix: string, newGenerator: () => AsyncGenerator, multiline: boolean, ): AsyncGenerator { - // Check if current can be reused - if ( - !( - this.currentGenerator && - this.pendingGeneratorPrefix && - (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( - prefix, - ) && - // for e.g. backspace - this.pendingGeneratorPrefix?.length <= prefix?.length - ) - ) { + // If we can't reuse, then create a new generator + if (!this.shouldReuseExistingGenerator(prefix)) { // Create a wrapper over the current generator to fix the prompt this._createListenableGenerator(newGenerator(), prefix); } - let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || ""; + // Already typed characters are those that are new in the prefix from the old generator + let typedSinceLastGenerator = + prefix.slice(this.pendingGeneratorPrefix?.length) || ""; for await (let chunk of this.currentGenerator?.tee() ?? []) { if (!chunk) { continue; } - while (chunk.length && alreadyTyped.length) { - if (chunk[0] === alreadyTyped[0]) { - alreadyTyped = alreadyTyped.slice(1); + + // Ignore already typed characters in the completion + while (chunk.length && typedSinceLastGenerator.length) { + if (chunk[0] === typedSinceLastGenerator[0]) { + typedSinceLastGenerator = typedSinceLastGenerator.slice(1); chunk = chunk.slice(1); } else { break; } } + // Break at newline unless we are in multiline mode const newLineIndex = chunk.indexOf("\n"); - if (multiline || newLineIndex === -1) { - yield chunk; - } else { + if (newLineIndex >= 0 && !multiline) { yield chunk.slice(0, newLineIndex); break; + } else if (chunk !== "") { + yield chunk; } } } diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.test.ts new file mode 100644 index 000000000..69797959e --- /dev/null +++ b/core/autocomplete/generation/ListenableGenerator.test.ts @@ -0,0 +1,149 @@ +import { jest } from "@jest/globals"; +import { ListenableGenerator } from "./ListenableGenerator"; + +describe("ListenableGenerator", () => { + // Helper function to create an async generator + async function* asyncGenerator(values: T[], delay = 0) { + for (const value of values) { + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + yield value; + } + } + + it("should yield values from the source generator via tee()", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + for await (const value of lg.tee()) { + result.push(value); + } + + expect(result).toEqual(values); + expect(onError).not.toHaveBeenCalled(); + }); + + it("should allow listeners to receive values", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const listener = jest.fn(); + + // Add listener after some delay to simulate late subscription + setTimeout(() => { + lg.listen(listener); + }, 15); + + // Wait for generator to finish + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + // Listener should receive null at the end + expect(listener).toHaveBeenCalledWith(null); + }); + + it("should buffer values for listeners added after some values have been yielded", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values, 10); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const initialListener = jest.fn(); + + lg.listen(initialListener); + + // Wait for the first value to be yielded + await new Promise((resolve) => setTimeout(resolve, 15)); + + // Add a second listener + const newListener = jest.fn(); + lg.listen(newListener); + + // Wait for generator to finish + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Both listeners should have received all values + [initialListener, newListener].forEach((listener) => { + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + expect(listener).toHaveBeenCalledWith(null); + }); + }); + + it("should handle cancellation", async () => { + const values = [1, 2, 3, 4, 5]; + const source = asyncGenerator(values, 10); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + const teeIterator = lg.tee(); + + const consume = async () => { + for await (const value of teeIterator) { + result.push(value); + if (value === 3) { + lg.cancel(); + } + } + }; + + await consume(); + + expect(result).toEqual([1, 2, 3]); + expect(lg["_isEnded"]).toBe(true); + }); + + it("should call onError when the source generator throws an error", async () => { + async function* errorGenerator() { + yield 1; + throw new Error("Test error"); + } + + const source = errorGenerator(); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + for await (const value of lg.tee()) { + result.push(value); + } + + expect(result).toEqual([1]); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(new Error("Test error")); + }); + + it("should notify listeners when the generator ends", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const listener = jest.fn(); + lg.listen(listener); + + // Wait for the generator to finish + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + expect(listener).toHaveBeenCalledWith(null); + }); +}); diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index ff0c5d493..96261e646 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -37,6 +37,7 @@ export class AutocompleteLoggingService { if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; + outcome.accepted = true; this.logAutocompleteOutcome(outcome); this._outcomes.delete(completionId); return outcome; @@ -94,7 +95,6 @@ export class AutocompleteLoggingService { } private logAutocompleteOutcome(outcome: AutocompleteOutcome) { - outcome.accepted = true; logDevData("autocomplete", outcome); const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; void Telemetry.capture( diff --git a/core/index.d.ts b/core/index.d.ts index 32685b79a..077b872b4 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -224,11 +224,16 @@ export interface IContextProvider { loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } +export interface Checkpoint { + [filepath: string]: string; +} + export interface PersistedSessionInfo { history: ChatHistory; title: string; workspaceDirectory: string; sessionId: string; + checkpoints?: Checkpoint[]; } export interface SessionInfo { @@ -678,7 +683,8 @@ type ModelProvider = | "askSage" | "vertexai" | "nebius" - | "xAI"; + | "xAI" + | "moonshot"; export type ModelName = | "AUTODETECT" @@ -773,7 +779,11 @@ export type ModelName = | "starcoder-1b" | "starcoder-3b" | "starcoder2-3b" - | "stable-code-3b"; + | "stable-code-3b" + // Moonshot + | "moonshot-v1-8k" + | "moonshot-v1-32k" + | "moonshot-v1-128k"; export interface RequestOptions { timeout?: number; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index bebb8ead1..8e475d01e 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -117,6 +117,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "huggingface-inference-api", "huggingface-tgi", "mistral", + "moonshot", "free-trial", "replicate", "together", @@ -149,9 +150,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || - lower.includes("grok") + lower.includes("grok")|| + lower.includes("moonshot") ) { - return undefined; + return undefined; } if (lower.includes("llama3")) { diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts new file mode 100644 index 000000000..022fa8af2 --- /dev/null +++ b/core/llm/llms/Moonshot.ts @@ -0,0 +1,59 @@ +import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { streamSse } from "../stream.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; + +import OpenAI from "./OpenAI.js"; + +class Moonshot extends OpenAI { + static providerName: ModelProvider = "moonshot"; + static defaultOptions: Partial = { + apiBase: "https://api.moonshot.cn/v1/", + model: "moonshot-v1-8k", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; + maxStopWords: number | undefined = 16; + + supportsFim(): boolean { + return true; + } + + async *_streamFim( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("v1/chat/completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages: [ + { + role: "user", + content: prefix + "[fill]" + suffix, + }, + ], + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].delta.content; + } + } +} + +export default Moonshot; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 48088dc34..121f0f46d 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -31,6 +31,7 @@ import Llamafile from "./Llamafile"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; import Mock from "./Mock"; +import Moonshot from "./Moonshot"; import Msty from "./Msty"; import Nebius from "./Nebius"; import Nvidia from "./Nvidia"; @@ -54,6 +55,7 @@ const LLMs = [ FreeTrial, Gemini, Llamafile, + Moonshot, Ollama, Replicate, TextGenWebUI, diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 93d2192e9..c833c3a7a 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -27,6 +27,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, void, ]; + overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; @@ -40,8 +41,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "jetbrains/isOSREnabled": [undefined, void]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; - acceptDiff: [{ filepath: string }, void]; - rejectDiff: [{ filepath: string }, void]; + acceptDiff: [{ filepath: string; streamId?: string }, void]; + rejectDiff: [{ filepath: string; streamId?: string }, void]; "edit/sendPrompt": [ { prompt: MessageContent; range: RangeInFileWithContents }, void, @@ -64,11 +65,17 @@ export type EditStatus = | "accepting:full-diff" | "done"; +export type ApplyStateStatus = + | "streaming" // Changes are being applied to the file + | "done" // All changes have been applied, awaiting user to accept/reject + | "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed" + export interface ApplyState { streamId: string; - status?: "streaming" | "done" | "closed"; + status?: ApplyStateStatus; numDiffs?: number; filepath?: string; + fileContent?: string; } export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/docs/docs/customize/model-providers/moonshot.md b/docs/docs/customize/model-providers/moonshot.md new file mode 100644 index 000000000..64017d1bd --- /dev/null +++ b/docs/docs/customize/model-providers/moonshot.md @@ -0,0 +1,60 @@ +# Moonshot + +[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance. + +## Configuration + +To use Moonshot AI models, you need to: + +1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/) +2. Add the following configuration to your `config.json`: + +```json +{ + "models": [ + { + "title": "Moonshot", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +## Available Models + +Moonshot AI currently provides the following models: + +- `moonshot-v1-8k`: Base model with 8K context window +- `moonshot-v1-32k`: Base model with 32K context window +- `moonshot-v1-128k`: Base model with 128K context window + +## Configuration Options + +| Option | Description | Default | +|--------|-------------|---------| +| `apiKey` | Moonshot API key | Required | +| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` | +| `model` | Model name to use | `moonshot-v1-8k` | + +## Example + +Here's a complete configuration example: + +```json +{ + "models": [ + { + "title": "Moonshot-8K", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "YOUR_API_KEY", + "completionOptions": { + "temperature": 0.7, + "topP": 0.95, + "maxTokens": 2048 + } + } + ] +} diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 76d27bec2..3c88058ef 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -205,7 +205,8 @@ "nebius", "vertexai", "xAI", - "kindo" + "kindo", + "moonshot" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -242,7 +243,8 @@ "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)", "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)", - "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)" + "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", + "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)" ], "type": "string" }, @@ -769,9 +771,6 @@ "starcoder-1b", "starcoder-3b", "starcoder2-3b", - "mistral-tiny", - "mistral-small", - "mistral-medium", "qwen2.5-coder:1.5b", "qwen2.5-coder:3b", "qwen2.5-coder:7b", @@ -1147,6 +1146,35 @@ "required": ["projectId", "region"] } }, + { + "if": { + "properties": { + "provider": { + "enum": ["moonshot"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "moonshot-v1-8k", + "moonshot-v1-32k", + "moonshot-v1-128k", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] + } + } + } + }, { "if": { "properties": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 186d18219..697bf61c1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -368,11 +368,6 @@ "mac": "alt+cmd+n", "key": "alt+ctrl+n" }, - { - "command": "continue.quickEdit", - "mac": "cmd+shift+i", - "key": "ctrl+shift+i" - }, { "command": "continue.edit", "mac": "cmd+i", @@ -415,9 +410,6 @@ ], "menus": { "commandPalette": [ - { - "command": "continue.quickEdit" - }, { "command": "continue.focusContinueInput" }, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 42c10c3c9..6847238e3 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -271,7 +271,10 @@ const commandsMap: ( } return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + "continue.acceptDiff": async ( + newFilepath?: string | vscode.Uri, + streamId?: string, + ) => { captureCommandTelemetry("acceptDiff"); let fullPath = newFilepath; @@ -290,8 +293,23 @@ const commandsMap: ( void sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); + + if (streamId && fullPath) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId: streamId, + status: "closed", + numDiffs: 0, + }); + } }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + "continue.rejectDiff": async ( + newFilepath?: string | vscode.Uri, + streamId?: string, + ) => { captureCommandTelemetry("rejectDiff"); let fullPath = newFilepath; @@ -309,6 +327,18 @@ const commandsMap: ( void sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); + + if (streamId && fullPath) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId: streamId, + status: "closed", + numDiffs: 0, + }); + } }, "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { captureCommandTelemetry("acceptVerticalDiffBlock"); @@ -387,7 +417,10 @@ const commandsMap: ( if (historyLength === 0) { hideGUI(); } else { - void sidebar.webviewProtocol?.request("focusContinueInput", undefined); + void sidebar.webviewProtocol?.request( + "focusContinueInput", + undefined, + ); } } else { focusGUI(); @@ -596,7 +629,9 @@ const commandsMap: ( prompt: "Enter the Session ID", }); } - void sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + void sidebar.webviewProtocol?.request("focusContinueSessionId", { + sessionId, + }); }, "continue.applyCodeFromChat": () => { void sidebar.webviewProtocol.request("applyCodeFromChat", undefined); @@ -734,7 +769,7 @@ const commandsMap: ( !selected || !autocompleteModels.some((model) => model.title === selected) ) { - selected = autocompleteModels[0].title; + selected = autocompleteModels[0]?.title; } // Toggle between Disabled, Paused, and Enabled diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index f2bf20ef6..3286749a6 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -18,6 +18,7 @@ export interface VerticalDiffHandlerOptions { onStatusUpdate: ( status?: ApplyState["status"], numDiffs?: ApplyState["numDiffs"], + fileContent?: ApplyState["fileContent"], ) => void; } @@ -271,6 +272,7 @@ export class VerticalDiffHandler implements vscode.Disposable { this.options.onStatusUpdate( "closed", this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0, + this.editor.document.getText(), ); this.cancelled = true; @@ -362,6 +364,7 @@ export class VerticalDiffHandler implements vscode.Disposable { this.options.onStatusUpdate( "done", this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0, + this.editor.document.getText(), ); // Reject on user typing @@ -416,7 +419,11 @@ export class VerticalDiffHandler implements vscode.Disposable { this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0; const status = numDiffs === 0 ? "closed" : undefined; - this.options.onStatusUpdate(status, numDiffs); + this.options.onStatusUpdate( + status, + numDiffs, + this.editor.document.getText(), + ); } private shiftCodeLensObjects(startLine: number, offset: number) { diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 4595ca013..3342c5341 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -217,11 +217,13 @@ export class VerticalDiffManager { endLine, { instant, - onStatusUpdate: (status, numDiffs) => + onStatusUpdate: (status, numDiffs, fileContent) => void this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, + fileContent, + filepath, }), }, ); @@ -336,12 +338,14 @@ export class VerticalDiffManager { endLine, { input, - onStatusUpdate: (status, numDiffs) => + onStatusUpdate: (status, numDiffs, fileContent) => streamId && void this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, + fileContent, + filepath, }), }, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index e71bd2bfd..3b5baad5f 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -152,15 +152,35 @@ export class VsCodeMessenger { ); }); - webviewProtocol.on("acceptDiff", async ({ data: { filepath } }) => { - void vscode.commands.executeCommand("continue.acceptDiff", filepath); - }); + webviewProtocol.on( + "acceptDiff", + async ({ data: { filepath, streamId } }) => { + await vscode.commands.executeCommand( + "continue.acceptDiff", + filepath, + streamId, + ); + }, + ); - webviewProtocol.on("rejectDiff", async ({ data: { filepath } }) => { - void vscode.commands.executeCommand("continue.rejectDiff", filepath); - }); + webviewProtocol.on( + "rejectDiff", + async ({ data: { filepath, streamId } }) => { + await vscode.commands.executeCommand( + "continue.rejectDiff", + filepath, + streamId, + ); + }, + ); this.onWebview("applyToFile", async ({ data }) => { + webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "streaming", + fileContent: data.text, + }); + let filepath = data.filepath; // If there is a filepath, verify it exists and then open the file @@ -173,18 +193,10 @@ export class VsCodeMessenger { const fileExists = await this.ide.fileExists(fullPath); - // If it's a new file, no need to apply, just write directly + // If there is no existing file at the path, create it if (!fileExists) { - await this.ide.writeFile(fullPath, data.text); + await this.ide.writeFile(fullPath, ""); await this.ide.openFile(fullPath); - - void webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "done", - numDiffs: 0, - }); - - return; } await this.ide.openFile(fullPath); @@ -203,11 +215,14 @@ export class VsCodeMessenger { editor.edit((builder) => builder.insert(new vscode.Position(0, 0), data.text), ); + void webviewProtocol.request("updateApplyState", { streamId: data.streamId, - status: "done", + status: "closed", numDiffs: 0, + fileContent: data.text, }); + return; } @@ -295,6 +310,37 @@ export class VsCodeMessenger { this.onWebview("openUrl", (msg) => { vscode.env.openExternal(vscode.Uri.parse(msg.data)); }); + + this.onWebview( + "overwriteFile", + async ({ data: { prevFileContent, filepath } }) => { + if (prevFileContent === null) { + // TODO: Delete the file + return; + } + + await this.ide.openFile(filepath); + + // Get active text editor + const editor = vscode.window.activeTextEditor; + + if (!editor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + + editor.edit((builder) => + builder.replace( + new vscode.Range( + editor.document.positionAt(0), + editor.document.positionAt(editor.document.getText().length), + ), + prevFileContent, + ), + ); + }, + ); + this.onWebview("insertAtCursor", async (msg) => { const editor = vscode.window.activeTextEditor; if (editor === undefined || !editor.selection) { diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm b/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm index 5a9e34b86..61fdb29ec 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm @@ -1,5 +1,24 @@ -( - (class_definition - superclasses: (argument_list - (identifier) @superclass)) +; Match superclass identifiers in a simple inheritance +(class_definition + superclasses: (argument_list + (identifier) @catch) + (#not-match? @catch "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; Match the value of a keyword argument in class inheritance +(class_definition + superclasses: (argument_list + (keyword_argument + (_) + (identifier) @catch)) + (#not-match? @catch "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; Match identifiers within subscripts in class inheritance +(class_definition + superclasses: (argument_list + (subscript + (identifier) @catch + )) + (#not-match? @catch "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") ) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm b/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm index 864666a4a..535882bfa 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm @@ -1,17 +1,60 @@ -( - (function_definition - (parameters - (_ - (type) @a - (#not-match? @a "^(str|int|float|bool|list|dict|tuple)$") - ) - ) - ) +; When the type is a simple identifier: +(function_definition + parameters: (parameters + (typed_parameter + type: (type + (identifier) @type_identifier))) + + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") ) -( - (function_definition - (type) @b - (#not-match? @b "^(str|int|float|bool|list|dict|tuple)$") - ) +; When the type is a generic type with one identifier +(function_definition + parameters: (parameters + (typed_parameter + type: (type + (generic_type + (identifier) @type_identifier)))) + + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the generic type has type parameters with one identifier +(function_definition + parameters: (parameters + (typed_parameter + type: (type + (generic_type + (identifier) + (type_parameter + (type + (identifier) @type_identifier)))))) + + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the return type is a simple identifier +(function_definition + return_type: (type + (identifier) @type_identifier) + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the return type is a generic type with one identifier +(function_definition + return_type: (type + (generic_type + (identifier) @type_identifier)) + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the generic type has type parameters with one identifier +(function_definition + return_type: (type + (generic_type + (identifier) + (type_parameter + (type + (identifier) @type_identifier)))) + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") ) \ No newline at end of file diff --git a/gui/public/logos/moonshot.png b/gui/public/logos/moonshot.png new file mode 100644 index 000000000..f51df62eb Binary files /dev/null and b/gui/public/logos/moonshot.png differ diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 42a1182e6..5879bd2e0 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,7 +12,11 @@ import { setEditStatus, startEditMode, } from "../redux/slices/editModeState"; -import { setShowDialog, updateApplyState } from "../redux/slices/uiStateSlice"; +import { setShowDialog } from "../redux/slices/uiStateSlice"; +import { + updateApplyState, + updateCurCheckpoint, +} from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; @@ -158,6 +162,12 @@ const Layout = () => { useWebviewListener( "updateApplyState", async (state) => { + dispatch( + updateCurCheckpoint({ + filepath: state.filepath, + content: state.fileContent, + }), + ); dispatch(updateApplyState(state)); }, [], diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx new file mode 100644 index 000000000..a1e7b28f6 --- /dev/null +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -0,0 +1,46 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { ApplyState } from "core/protocol/ideWebview"; + +export interface AcceptRejectAllButtonsProps { + pendingApplyStates: ApplyState[]; +} + +export default function AcceptRejectAllButtons({ + pendingApplyStates, +}: AcceptRejectAllButtonsProps) { + const ideMessenger = useContext(IdeMessengerContext); + + async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") { + for (const { filepath, streamId } of pendingApplyStates) { + ideMessenger.post(status, { + filepath, + streamId, + }); + } + } + + return ( +
+ + +
+ ); +} diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/StepContainer/FeedbackButtons.tsx new file mode 100644 index 000000000..55e870991 --- /dev/null +++ b/gui/src/components/StepContainer/FeedbackButtons.tsx @@ -0,0 +1,55 @@ +import { + HandThumbUpIcon, + HandThumbDownIcon, +} from "@heroicons/react/24/outline"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { ChatHistoryItem } from "core"; +import { useState, useContext } from "react"; +import { useSelector } from "react-redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { RootState } from "../../redux/store"; + +export interface FeedbackButtonsProps { + item: ChatHistoryItem; +} + +export default function FeedbackButtons({ item }: FeedbackButtonsProps) { + const [feedback, setFeedback] = useState(undefined); + const ideMessenger = useContext(IdeMessengerContext); + const sessionId = useSelector((store: RootState) => store.state.sessionId); + + const sendFeedback = (feedback: boolean) => { + setFeedback(feedback); + if (item.promptLogs?.length) { + for (const promptLog of item.promptLogs) { + ideMessenger.post("devdata/log", { + tableName: "chat", + data: { ...promptLog, feedback, sessionId }, + }); + } + } + }; + + return ( + <> + sendFeedback(true)} + > + + + sendFeedback(false)} + > + + {" "} + + ); +} diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx new file mode 100644 index 000000000..5fb7122df --- /dev/null +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -0,0 +1,65 @@ +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; +import FeedbackButtons from "./FeedbackButtons"; +import UndoAndRedoButtons from "./UndoAndRedoButtons"; +import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/images"; +import { CopyIconButton } from "../gui/CopyIconButton"; + +export interface MultifileEditActionsProps { + index: number; + item: ChatHistoryItem; +} + +export default function MultifileEditActions({ + index, + item, +}: MultifileEditActionsProps) { + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + + const hasClosedAllStreams = applyStates.every( + (state) => state.status === "closed", + ); + + const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; + const hasPendingApplies = pendingApplyStates.length > 0; + + return ( +
+
+ + {isCurCheckpoint && ( +
+ {hasPendingApplies && ( + + )} + {hasClosedAllStreams && } +
+ )} + +
+ + + +
+
+ ); +} diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx new file mode 100644 index 000000000..66d62575c --- /dev/null +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -0,0 +1,65 @@ +import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; +import { stripImages } from "core/llm/images"; +import { CopyIconButton } from "../gui/CopyIconButton"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import { ChatHistoryItem } from "core"; +import FeedbackButtons from "./FeedbackButtons"; +import MultifileEditActions from "./MultifileEditActions"; + +export interface ResponseActionsProps { + isTruncated: boolean; + onContinueGeneration: () => void; + index: number; + onDelete: () => void; + item: ChatHistoryItem; +} + +export default function ResponseActions({ + onContinueGeneration, + index, + item, + isTruncated, + onDelete, +}: ResponseActionsProps) { + const isInMultifileEdit = useSelector( + (store: RootState) => store.state.isMultifileEdit, + ); + + // Only render delete button if there is more than one message + const shouldRenderDelete = index !== 1; + + if (isInMultifileEdit) { + return ; + } + + return ( +
+ {isTruncated && ( + + + + )} + + {shouldRenderDelete && ( + + + + )} + + + + +
+ ); +} diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx new file mode 100644 index 000000000..f5673e4e8 --- /dev/null +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -0,0 +1,115 @@ +import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/images"; +import { useEffect, useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { vscBackground } from ".."; +import useUIConfig from "../../hooks/useUIConfig"; +import { RootState } from "../../redux/store"; +import { getFontSize } from "../../util"; +import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import ResponseActions from "./ResponseActions"; +import { deleteMessage } from "../../redux/slices/stateSlice"; + +interface StepContainerProps { + item: ChatHistoryItem; + index: number; + isLast: boolean; +} + +const ContentDiv = styled.div<{ fontSize?: number }>` + padding-top: 4px; + background-color: ${vscBackground}; + font-size: ${getFontSize()}px; + overflow: hidden; +`; + +export default function StepContainer(props: StepContainerProps) { + const dispatch = useDispatch(); + const [isTruncated, setIsTruncated] = useState(false); + const active = useSelector((store: RootState) => store.state.active); + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + const isMultifileEdit = useSelector( + (store: RootState) => store.state.isMultifileEdit, + ); + const uiConfig = useUIConfig(); + const shouldHideActions = active && props.isLast; + const isStepAheadOfCurCheckpoint = + isMultifileEdit && Math.floor(props.index / 2) > curCheckpointIndex; + + useEffect(() => { + if (!active) { + const content = stripImages(props.item.message.content).trim(); + const endingPunctuation = [".", "?", "!", "```"]; + + // If not ending in punctuation or emoji, we assume the response got truncated + if ( + !( + endingPunctuation.some((p) => content.endsWith(p)) || + /\p{Emoji}/u.test(content.slice(-2)) + ) + ) { + setIsTruncated(true); + } else { + setIsTruncated(false); + } + } + }, [props.item.message.content, active]); + + function onDelete() { + dispatch(deleteMessage(props.index)); + } + + function onContinueGeneration() { + window.postMessage( + { + messageType: "userInput", + data: { + input: "Continue your response exactly where you left off:", + }, + }, + "*", + ); + } + + return ( +
+ + {uiConfig?.displayRawMarkdown ? ( +
+            {stripImages(props.item.message.content)}
+          
+ ) : ( + + )} +
+ {/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on */} +
+ {!shouldHideActions && ( + + )} +
+
+ ); +} diff --git a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx new file mode 100644 index 000000000..2ee69a11a --- /dev/null +++ b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx @@ -0,0 +1,61 @@ +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import { + ArrowUturnLeftIcon, + ArrowUturnRightIcon, +} from "@heroicons/react/24/outline"; +import { setCurCheckpointIndex } from "../../redux/slices/stateSlice"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +export default function UndoAndRedoButtons() { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const checkpoints = useSelector( + (store: RootState) => store.state.checkpoints, + ); + + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + + const shouldRenderRedo = curCheckpointIndex !== checkpoints.length - 1; + + async function handleUndoOrRedo(type: "undo" | "redo") { + const checkpointIndex = Math.max( + 0, + type === "undo" ? curCheckpointIndex - 1 : curCheckpointIndex + 1, + ); + + const checkpoint = checkpoints[checkpointIndex]; + + for (const [filepath, prevFileContent] of Object.entries(checkpoint)) { + ideMessenger.post("overwriteFile", { filepath, prevFileContent }); + } + + dispatch(setCurCheckpointIndex(checkpointIndex)); + } + + return ( +
+ + + {shouldRenderRedo && ( + + )} +
+ ); +} diff --git a/gui/src/components/StepContainer/index.ts b/gui/src/components/StepContainer/index.ts new file mode 100644 index 000000000..41d4fa945 --- /dev/null +++ b/gui/src/components/StepContainer/index.ts @@ -0,0 +1 @@ +export { default } from "./StepContainer"; diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx deleted file mode 100644 index 22523cfb2..000000000 --- a/gui/src/components/gui/StepContainer.tsx +++ /dev/null @@ -1,170 +0,0 @@ -import { - BarsArrowDownIcon, - HandThumbDownIcon, - HandThumbUpIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; -import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; -import { useContext, useEffect, useState } from "react"; -import { useSelector } from "react-redux"; -import styled from "styled-components"; -import { vscBackground, vscInputBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import useUIConfig from "../../hooks/useUIConfig"; -import { RootState } from "../../redux/store"; -import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; -import { CopyIconButton } from "./CopyIconButton"; -import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip"; - -interface StepContainerProps { - item: ChatHistoryItem; - onReverse: () => void; - onUserInput: (input: string) => void; - onRetry: () => void; - onContinueGeneration: () => void; - onDelete: () => void; - open: boolean; - isFirst: boolean; - isLast: boolean; - index: number; - modelTitle?: string; -} - -const ContentDiv = styled.div<{ isUserInput: boolean; fontSize?: number }>` - padding-top: 4px; - background-color: ${(props) => - props.isUserInput ? vscInputBackground : vscBackground}; - font-size: ${(props) => props.fontSize || getFontSize()}px; - overflow: hidden; -`; - -function StepContainer(props: StepContainerProps) { - const active = useSelector((store: RootState) => store.state.active); - const [truncatedEarly, setTruncatedEarly] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const [feedback, setFeedback] = useState(undefined); - const sessionId = useSelector((store: RootState) => store.state.sessionId); - - const isUserInput = props.item.message.role === "user"; - const uiConfig = useUIConfig(); - const shouldRenderActions = !active || !props.isLast; - - useEffect(() => { - if (!active) { - const content = stripImages(props.item.message.content).trim(); - const endingPunctuation = [".", "?", "!", "```"]; - - // If not ending in punctuation or emoji, we assume the response got truncated - if ( - !( - endingPunctuation.some((p) => content.endsWith(p)) || - /\p{Emoji}/u.test(content.slice(-2)) - ) - ) { - setTruncatedEarly(true); - } else { - setTruncatedEarly(false); - } - } - }, [props.item.message.content, active]); - - const sendFeedback = (feedback: boolean) => { - setFeedback(feedback); - if (props.item.promptLogs?.length) { - for (const promptLog of props.item.promptLogs) { - ideMessenger.post("devdata/log", { - tableName: "chat", - data: { ...promptLog, feedback, sessionId }, - }); - } - } - }; - - return ( -
- -
- {truncatedEarly && ( - - - - )} - - {props.index !== 1 && ( - - - - )} - - - - sendFeedback(true)} - > - - - - sendFeedback(false)} - > - - -
-
- ); -} - -export default StepContainer; diff --git a/gui/src/components/gui/TimelineItem.tsx b/gui/src/components/gui/TimelineItem.tsx index 3796a4cd9..c3edc4c76 100644 --- a/gui/src/components/gui/TimelineItem.tsx +++ b/gui/src/components/gui/TimelineItem.tsx @@ -30,8 +30,8 @@ interface TimelineItemProps { item: ChatHistoryItem; open: boolean; onToggle: () => void; - children: any; - iconElement?: any; + children: JSX.Element; + iconElement?: JSX.Element; } function TimelineItem(props: TimelineItemProps) { diff --git a/gui/src/components/mainInput/AcceptRejectAllButtons.tsx b/gui/src/components/mainInput/AcceptRejectAllButtons.tsx deleted file mode 100644 index aff8355e0..000000000 --- a/gui/src/components/mainInput/AcceptRejectAllButtons.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { updateApplyState } from "../../redux/slices/uiStateSlice"; -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -export default function AcceptRejectAllButtons() { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - - const applyStates = useSelector( - (state: RootState) => state.uiState.applyStates, - ); - - const pendingApplyStates = applyStates.filter( - (state) => state.status === "done", - ); - - const handleAcceptAll = async () => { - for (const applyState of pendingApplyStates) { - ideMessenger.post("acceptDiff", { filepath: applyState.filepath }); - dispatch( - updateApplyState({ - streamId: applyState.streamId, - status: "closed", - }), - ); - } - }; - - const handleRejectAll = async () => { - for (const applyState of pendingApplyStates) { - ideMessenger.post("rejectDiff", { filepath: applyState.filepath }); - dispatch( - updateApplyState({ - streamId: applyState.streamId, - status: "closed", - }), - ); - } - }; - - return ( -
- - -
- ); -} diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index c98a69403..4a9ea0dfd 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -10,7 +10,6 @@ import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; -import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; interface ContinueInputBoxProps { isLastUserInput: boolean; @@ -77,13 +76,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const [isGatheringContext, setIsGatheringContext] = useState(false); const timeoutRef = useRef(null); - const isInMultifileEdit = useSelector( - (state: RootState) => state.state.isInMultifileEdit, - ); - - const shouldShowAcceptRejectButtons = - props.isMainInput && isInMultifileEdit && !active; - useWebviewListener( "newSessionWithPrompt", async (data) => { @@ -118,8 +110,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { return (
- {shouldShowAcceptRejectButtons && } -
` - padding: 4px 0; + padding-top: 4px; justify-content: space-between; gap: 1px; background-color: ${vscInputBackground}; @@ -103,7 +103,7 @@ function InputToolbar(props: InputToolbarProps) { isHidden={props.hidden} onClick={props.onClick} id="input-toolbar" - className="flex find-widget-skip" + className="find-widget-skip flex" >
diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index e14cd7b09..21fafc2f5 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -13,10 +13,10 @@ import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { CopyIconButton } from "../gui/CopyIconButton"; import useUIConfig from "../../hooks/useUIConfig"; import { v4 as uuidv4 } from "uuid"; -import { useApplyCodeBlock } from "./utils/useApplyCodeBlock"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; +import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; const TopDiv = styled.div` outline: 0.5px solid rgba(153, 153, 152); @@ -66,12 +66,8 @@ export default function StepContainerPreActionButtons({ const uiConfig = useUIConfig(); const streamIdRef = useRef(null); const nextCodeBlockIndex = useSelector( - (state: RootState) => state.uiState.nextCodeBlockToApplyIndex, + (state: RootState) => state.state.nextCodeBlockToApplyIndex, ); - const onClickApply = useApplyCodeBlock({ - codeBlockContent, - streamId: streamIdRef.current, - }); const isBottomToolbarPosition = uiConfig?.codeBlockToolbarPosition == "bottom"; @@ -83,10 +79,19 @@ export default function StepContainerPreActionButtons({ streamIdRef.current = uuidv4(); } + const defaultModel = useSelector(defaultModelSelector); + function onClickApply() { + ideMessenger.post("applyToFile", { + streamId: streamIdRef.current, + text: codeBlockContent, + curSelectedModelTitle: defaultModel.title, + }); + } + // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", - onClickApply, + async () => onClickApply(), [isNextCodeBlock, codeBlockContent], !isNextCodeBlock, ); diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 9d4f965f7..286277d4f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -33,16 +33,17 @@ export default function ApplyActions(props: ApplyActionsProps) { ); case "done": return ( -
- - {`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`} remaining`} +
+ + {`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`}`} + {` remaining`} - + - Applied - + + Applied + ); } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx index 99dfddfaa..195615380 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx @@ -15,18 +15,18 @@ export default function CopyButton({ text }: CopyButtonProps) { onClick={copyText} >
{copied ? ( <> - Copied + Copied ) : ( <> - Copy + Copy )}
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c95e7962d..6d8fc8d74 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -12,7 +12,6 @@ export interface FileInfoProps { const FileInfo = ({ filepath, range }: FileInfoProps) => { const ideMessenger = useContext(IdeMessengerContext); - // TODO: Need to turn into relative or fq path function onClickFileName() { ideMessenger.post("showFile", { filepath, @@ -20,13 +19,13 @@ const FileInfo = ({ filepath, range }: FileInfoProps) => { } return ( -
+
- + {getBasename(filepath)} {range && ` ${range}`} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 0fa57fd08..fbc43e5d2 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -1,21 +1,20 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { debounce } from "lodash"; import { useContext, useEffect, useRef, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useSelector } from "react-redux"; import styled, { css, keyframes } from "styled-components"; import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, lightGray, vscEditorBackground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { updateApplyState } from "../../../redux/slices/uiStateSlice"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; import { childrenToText } from "../utils"; -import { useApplyCodeBlock } from "../utils/useApplyCodeBlock"; import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; import FileInfo from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; +import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; const fadeInAnimation = keyframes` from { @@ -32,6 +31,7 @@ const TopDiv = styled.div<{ active?: boolean }>` border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; background-color: ${vscEditorBackground}; + min-width: 0; ${(props) => props.active ? "animation: none;" @@ -65,28 +65,23 @@ export interface StepContainerPreToolbarProps { export default function StepContainerPreToolbar( props: StepContainerPreToolbarProps, ) { - const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const streamIdRef = useRef(null); + const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isMultifileEdit = useSelector( - (state: RootState) => state.state.isInMultifileEdit, + (state: RootState) => state.state.isMultifileEdit, ); const active = useSelector((state: RootState) => state.state.active); const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true); const [codeBlockContent, setCodeBlockContent] = useState(""); const isChatActive = useSelector((state: RootState) => state.state.active); - const onClickApply = useApplyCodeBlock({ - streamId: streamIdRef.current, - filepath: props.filepath, - codeBlockContent: props.codeBlockContent, - }); + const nextCodeBlockIndex = useSelector( - (state: RootState) => state.uiState.nextCodeBlockToApplyIndex, + (state: RootState) => state.state.nextCodeBlockToApplyIndex, ); const applyState = useSelector((store: RootState) => - store.uiState.applyStates.find( + store.state.applyStates.find( (state) => state.streamId === streamIdRef.current, ), ); @@ -103,14 +98,20 @@ export default function StepContainerPreToolbar( const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.filepath); - if (streamIdRef.current === null) { - streamIdRef.current = uuidv4(); + const defaultModel = useSelector(defaultModelSelector); + function onClickApply() { + ideMessenger.post("applyToFile", { + streamId: streamIdRef.current, + filepath: props.filepath, + text: codeBlockContent, + curSelectedModelTitle: defaultModel.title, + }); } // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", - onClickApply, + async () => onClickApply(), [isNextCodeBlock, codeBlockContent], !isNextCodeBlock, ); @@ -144,23 +145,17 @@ export default function StepContainerPreToolbar( }, [isGeneratingCodeBlock]); function onClickAcceptApply() { - ideMessenger.post("acceptDiff", { filepath: props.filepath }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "closed", - }), - ); + ideMessenger.post("acceptDiff", { + filepath: props.filepath, + streamId: streamIdRef.current, + }); } function onClickRejectApply() { - ideMessenger.post("rejectDiff", { filepath: props.filepath }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "closed", - }), - ); + ideMessenger.post("rejectDiff", { + filepath: props.filepath, + streamId: streamIdRef.current, + }); } function onClickExpand() { @@ -176,17 +171,19 @@ export default function StepContainerPreToolbar( return ( -
+
- +
+ +
-
+
{isGeneratingCodeBlock && ( { - setMarkdownSource(props.source || ""); + setMarkdownSource(patchNestedMarkdown(props.source ?? "")); }, [props.source]); return ( diff --git a/gui/src/components/markdown/utils/index.ts b/gui/src/components/markdown/utils.ts similarity index 100% rename from gui/src/components/markdown/utils/index.ts rename to gui/src/components/markdown/utils.ts diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts new file mode 100644 index 000000000..29b305b26 --- /dev/null +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -0,0 +1,90 @@ +/* + This is a patch for outputing markdown code that contains codeblocks + + It notices markdown blocks, keeps track of when that specific block is closed, + and uses ~~~ instead of ``` for that block + + Note, this was benchmarked at sub-millisecond + + // TODO support github-specific markdown as well, edge case +*/ + +export const patchNestedMarkdown = (source: string): string => { + if (!source.match(/```(md|markdown)/)) return source; // For performance + // const start = Date.now(); + let nestCount = 0; + const lines = source.split("\n"); + const trimmedLines = lines.map((l) => l.trim()); + for (let i = 0; i < trimmedLines.length; i++) { + const line = trimmedLines[i]; + if (nestCount) { + if (line.match(/^`+$/)) { + // Ending a block + if (nestCount === 1) lines[i] = "~~~"; // End of markdown block + nestCount--; + } else if (line.startsWith("```")) { + // Going into a nested codeblock + nestCount++; + } + } else { + // Enter the markdown block, start tracking nesting + if (line.startsWith("```md") || line.startsWith("```markdown")) { + nestCount = 1; + lines[i] = lines[i].replace(/```(md|markdown)/, "~~~"); // Replace backticks with tildes + } + } + } + const out = lines.join("\n"); + // console.log(`patched in ${Date.now() - start}ms`); + return out; +}; + +// This version tries to detect if a codeblock without a language specified is a starter codeblock +// It tries again if didn't come back to root nesting, without checking for that ^ +// I didn't use for performance and also because the root nest check doesn't make sense mid-generation + +// export const patchNestedMarkdown = (source: string): string => { +// const start = Date.now(); + +// let attempts = 0; + +// while (attempts <= 2) { +// let nestCount = 0; +// const lines = source.split("\n"); +// const trimmedLines = lines.map((l) => l.trim()); +// for (let i = 0; i < trimmedLines.length; i++) { +// const line = trimmedLines[i]; +// if (nestCount) { +// if (line.match(/^`+$/)) { +// if (attempts === 0 && i !== lines.length && lines[i + 1] !== "") { +// nestCount++; +// continue; +// } +// if (nestCount === 1) lines[i] = "~~~"; +// nestCount--; +// } else if (line.startsWith("```")) { +// // Going into a nested codeblock +// nestCount++; +// } +// } else { +// // Enter the markdown block, start tracking nesting +// if (line.startsWith("```md") || line.startsWith("```markdown")) { +// nestCount = 1; +// lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes +// } +// } +// } +// if (nestCount === 0) { +// console.log( +// `patch successful in ${Date.now() - start} ms with ${attempts} attempts`, +// ); +// return lines.join("\n"); +// } +// attempts++; +// } + +// console.log( +// `patch failed in ${Date.now() - start} ms with ${attempts} attempts`, +// ); +// return source; +// }; diff --git a/gui/src/components/markdown/utils/useApplyCodeBlock.ts b/gui/src/components/markdown/utils/useApplyCodeBlock.ts deleted file mode 100644 index cb016e1d8..000000000 --- a/gui/src/components/markdown/utils/useApplyCodeBlock.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { - incrementNextCodeBlockToApplyIndex, - updateApplyState, -} from "../../../redux/slices/uiStateSlice"; -import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; - -export interface useApplyCodeBlock { - streamId: string; - filepath?: string; - codeBlockContent: string; -} - -export function useApplyCodeBlock({ - streamId, - filepath, - codeBlockContent, -}: useApplyCodeBlock) { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const defaultModel = useSelector(defaultModelSelector); - - const applyCodeBlock = async () => { - dispatch( - updateApplyState({ - streamId, - filepath, - status: "streaming", - }), - ); - - await ideMessenger.request("applyToFile", { - text: codeBlockContent, - streamId, - curSelectedModelTitle: defaultModel.title, - filepath, - }); - - dispatch(incrementNextCodeBlockToApplyIndex({})); - }; - - return applyCodeBlock; -} diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 229c03ebc..ce599454d 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -27,13 +27,14 @@ import { clearLastResponse, initNewActiveMessage, resubmitAtIndex, + setCurCheckpointIndex, setInactive, setIsGatheringContext, setIsInMultifileEdit, setMessageAtIndex, streamUpdate, } from "../redux/slices/stateSlice"; -import { resetNextCodeBlockToApplyIndex } from "../redux/slices/uiStateSlice"; +import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import useHistory from "./useHistory"; @@ -190,6 +191,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { // Reset current code block index dispatch(resetNextCodeBlockToApplyIndex()); + if (index) { + dispatch(setCurCheckpointIndex(Math.floor(index / 2))); + } + const shouldGatherContext = modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 911a2a014..f159ffea3 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -94,6 +94,7 @@ function useHistory(dispatch: Dispatch) { title: title, sessionId: stateCopy.sessionId, workspaceDirectory: window.workspacePaths?.[0] || "", + checkpoints: stateCopy.checkpoints, }; return await ideMessenger.request("history/save", sessionInfo); diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 01293f87a..5e55c5c64 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -182,6 +182,42 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["nebius"], isOpenSource: true, }, + moonshotChat: { + title: "Moonshot Chat", + description: "Moonshot AI provides high-performance large language models", + refUrl: "https://platform.moonshot.cn/", + params: { + title: "Moonshot-v1-8k", + model: "moonshot-v1-8k", + contextLength: 8192, + }, + icon: "moonshot.png", + dimensions: [ + { + name: "Context Window", + description: "The size of the model's context window", + options: { + "8K": { + model: "moonshot-v1-8k", + title: "Moonshot-v1-8k", + contextLength: 8192, + }, + "32K": { + model: "moonshot-v1-32k", + title: "Moonshot-v1-32k", + contextLength: 32768, + }, + "128K": { + model: "moonshot-v1-128k", + title: "Moonshot-v1-128k", + contextLength: 131072, + }, + }, + }, + ], + providerOptions: ["moonshot"], + isOpenSource: false, + }, mistralOs: { title: "Mistral", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 5047fbad0..3100f1ddc 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -116,6 +116,29 @@ export const providers: Partial> = { ], apiKeyUrl: "https://console.anthropic.com/account/keys", }, + moonshot: { + title: "Moonshot", + provider: "moonshot", + description: "Use the Moonshot API for LLMs", + longDescription: `[Visit our documentation](https://docs.continue.dev/reference/Model%20Providers/moonshot) for information on obtaining an API key.`, + icon: "moonshot.png", + tags: [ModelProviderTags.RequiresApiKey], + refPage: "moonshot", + apiKeyUrl: "https://docs.moonshot.cn/docs/getting-started", + packages: [ + models.moonshotChat, + ], + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your Moonshot API key", + required: true, + }, + ...completionParamsInputsConfigs, + ], + }, azure: { title: "Azure OpenAI", provider: "azure", diff --git a/gui/src/pages/edit/EditInputHeader.tsx b/gui/src/pages/edit/EditInputHeader.tsx index 8248bbfa6..00695e66b 100644 --- a/gui/src/pages/edit/EditInputHeader.tsx +++ b/gui/src/pages/edit/EditInputHeader.tsx @@ -77,7 +77,7 @@ export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) { )} */}
- + - + { diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 3b708e980..c601c9650 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -105,7 +105,7 @@ function Edit() { const applyState = useSelector( (store: RootState) => - store.uiState.applyStates.find((state) => state.streamId === "edit") + store.state.applyStates.find((state) => state.streamId === "edit") ?.status ?? "closed", ); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index cd1104fa9..8a5dcb8ad 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -25,11 +25,9 @@ import { vscBackground, } from "../../components"; import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; -import { useFindWidget } from "../../components/find/FindWidget"; -import StepContainer from "../../components/gui/StepContainer"; +import StepContainer from "../../components/StepContainer"; import TimelineItem from "../../components/gui/TimelineItem"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import { defaultInputModifiers } from "../../components/mainInput/inputModifiers"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import { TutorialCard } from "../../components/mainInput/TutorialCard"; import { @@ -44,7 +42,6 @@ import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { clearLastResponse, - deleteMessage, newSession, setInactive, } from "../../redux/slices/stateSlice"; @@ -63,6 +60,8 @@ import { import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; +import { useFindWidget } from "../../components/find/FindWidget"; + const StopButton = styled.div` background-color: ${vscBackground}; @@ -371,41 +370,7 @@ export function Chat() { {}} item={item} - onReverse={() => {}} - onRetry={() => { - streamResponse( - state.history[index - 1].editorState, - state.history[index - 1].modifiers ?? - defaultInputModifiers, - ideMessenger, - index - 1, - ); - }} - onContinueGeneration={() => { - window.postMessage( - { - messageType: "userInput", - data: { - input: - "Continue your response exactly where you left off:", - }, - }, - "*", - ); - }} - onDelete={() => { - dispatch(deleteMessage(index)); - }} - modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} />
diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index fa85427e5..0c6dfd618 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -3,6 +3,8 @@ import { JSONContent } from "@tiptap/react"; import { ChatHistoryItem, ChatMessage, + Checkpoint, + ContextItemId, ContextItemWithId, IndexingStatus, PersistedSessionInfo, @@ -12,13 +14,14 @@ import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; import { v4 as uuidv4, v4 } from "uuid"; +import { RootState } from "../store"; +import { ApplyState } from "core/protocol/ideWebview"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. type ChatHistoryItemWithMessageId = ChatHistoryItem & { message: ChatMessage & { id: string }; }; - type State = { history: ChatHistoryItemWithMessageId[]; ttsActive: boolean; @@ -31,8 +34,12 @@ type State = { mainEditorContent?: JSONContent; selectedProfileId: string; configError: ConfigValidationError[] | undefined; - isInMultifileEdit: boolean; indexingStatuses: { [id: string]: IndexingStatus }; + checkpoints: Checkpoint[]; + curCheckpointIndex: number; + isMultifileEdit: boolean; + applyStates: ApplyState[]; + nextCodeBlockToApplyIndex: number; }; const initialState: State = { @@ -59,8 +66,12 @@ const initialState: State = { sessionId: v4(), defaultModelTitle: "GPT-4", selectedProfileId: "local", - isInMultifileEdit: false, indexingStatuses: {}, + checkpoints: [], + isMultifileEdit: false, + curCheckpointIndex: 0, + nextCodeBlockToApplyIndex: 0, + applyStates: [], }; export const stateSlice = createSlice({ @@ -187,6 +198,7 @@ export const stateSlice = createSlice({ }); state.active = true; + state.curCheckpointIndex = state.curCheckpointIndex + 1; }, setMessageAtIndex: ( state, @@ -253,12 +265,15 @@ export const stateSlice = createSlice({ state.history = payload.history as any; state.title = payload.title; state.sessionId = payload.sessionId; + state.checkpoints = payload.checkpoints; + state.curCheckpointIndex = 0; } else { state.history = []; state.active = false; state.title = "New Session"; state.sessionId = v4(); - state.isInMultifileEdit = false; + state.checkpoints = []; + state.curCheckpointIndex = 0; } }, addHighlightedCode: ( @@ -311,8 +326,42 @@ export const stateSlice = createSlice({ selectedProfileId: payload, }; }, - setIsInMultifileEdit: (state, action: PayloadAction) => { - state.isInMultifileEdit = action.payload; + + setIsInMultifileEdit: (state, { payload }: PayloadAction) => { + state.isMultifileEdit = payload; + }, + setCurCheckpointIndex: (state, { payload }: PayloadAction) => { + state.curCheckpointIndex = payload; + }, + updateCurCheckpoint: ( + state, + { payload }: PayloadAction<{ filepath: string; content: string }>, + ) => { + state.checkpoints[state.curCheckpointIndex] = { + ...state.checkpoints[state.curCheckpointIndex], + [payload.filepath]: payload.content, + }; + }, + updateApplyState: (state, { payload }: PayloadAction) => { + const index = state.applyStates.findIndex( + (applyState) => applyState.streamId === payload.streamId, + ); + + const curApplyState = state.applyStates[index]; + + if (index === -1) { + state.applyStates.push(payload); + } else { + curApplyState.status = payload.status ?? curApplyState.status; + curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; + curApplyState.filepath = payload.filepath ?? curApplyState.filepath; + } + if(payload.status === "done"){ + state.nextCodeBlockToApplyIndex++; + } + }, + resetNextCodeBlockToApplyIndex: (state) => { + state.nextCodeBlockToApplyIndex = 0; }, updateIndexingStatus: (state, action: PayloadAction) => { console.log("update indexing status"); @@ -349,6 +398,10 @@ export const { setIsGatheringContext, setIsInMultifileEdit, updateIndexingStatus, + updateCurCheckpoint, + setCurCheckpointIndex, + resetNextCodeBlockToApplyIndex, + updateApplyState, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index 24c4fc194..f4b531c39 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -1,5 +1,4 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { ApplyState } from "core/protocol/ideWebview"; import { defaultOnboardingCardState, OnboardingCardState, @@ -9,13 +8,7 @@ type UiState = { showDialog: boolean; dialogMessage: string | JSX.Element | undefined; dialogEntryOn: boolean; - nextCodeBlockToApplyIndex: number; onboardingCard: OnboardingCardState; - - /** - * Syncs the sidebar with the accepted/rejected blocks in the editor. Reused for Edit as well. - */ - applyStates: ApplyState[]; }; export const uiStateSlice = createSlice({ @@ -24,9 +17,7 @@ export const uiStateSlice = createSlice({ showDialog: false, dialogMessage: "", dialogEntryOn: false, - nextCodeBlockToApplyIndex: 0, onboardingCard: defaultOnboardingCardState, - applyStates: [], } as UiState, reducers: { setOnboardingCard: ( @@ -50,28 +41,6 @@ export const uiStateSlice = createSlice({ setShowDialog: (state, action: PayloadAction) => { state.showDialog = action.payload; }, - - resetNextCodeBlockToApplyIndex: (state) => { - state.nextCodeBlockToApplyIndex = 0; - }, - incrementNextCodeBlockToApplyIndex: (state, action) => { - state.nextCodeBlockToApplyIndex++; - }, - updateApplyState: (state, { payload }: PayloadAction) => { - const index = state.applyStates.findIndex( - (applyState) => applyState.streamId === payload.streamId, - ); - - const curApplyState = state.applyStates[index]; - - if (index === -1) { - state.applyStates.push(payload); - } else { - curApplyState.status = payload.status ?? curApplyState.status; - curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; - curApplyState.filepath = payload.filepath ?? curApplyState.filepath; - } - }, }, }); @@ -80,9 +49,6 @@ export const { setDialogMessage, setDialogEntryOn, setShowDialog, - resetNextCodeBlockToApplyIndex, - incrementNextCodeBlockToApplyIndex, - updateApplyState, } = uiStateSlice.actions; export default uiStateSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 221d275c9..725d88c01 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -10,7 +10,6 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import editModeStateReducer from "./slices/editModeState"; - export interface ChatMessage { role: "system" | "user" | "assistant"; content: string; diff --git a/manual-testing-sandbox/helloNested.py b/manual-testing-sandbox/helloNested.py new file mode 100644 index 000000000..e69de29bb diff --git a/packages/openai-adapters/src/apis/Moonshot.ts b/packages/openai-adapters/src/apis/Moonshot.ts new file mode 100644 index 000000000..eb11124f0 --- /dev/null +++ b/packages/openai-adapters/src/apis/Moonshot.ts @@ -0,0 +1,63 @@ +import { streamSse } from "@continuedev/fetch"; +import fetch from "node-fetch"; +import { ChatCompletionChunk } from "openai/resources/index.mjs"; +import { LlmApiConfig } from "../index.js"; +import { OpenAIApi } from "./OpenAI.js"; +import { FimCreateParamsStreaming } from "./base.js"; + +export class MoonshotApi extends OpenAIApi { + constructor(config: LlmApiConfig) { + super(config); + this.apiBase = "https://api.moonshot.cn/"; + } + + async *fimStream( + body: FimCreateParamsStreaming, + ): AsyncGenerator { + const endpoint = new URL("v1/chat/completions", this.apiBase); + const resp = await fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: [ + { + role: "user", + content: body.prompt + "[fill]" + body.suffix, + }, + ], + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + }); + + for await (const chunk of streamSse(resp as any)) { + yield { + choices: [ + { + delta: { + content: chunk.choices[0].delta.content, + role: "assistant", + }, + finish_reason: chunk.finish_reason, + index: 0, + logprobs: null, + }, + ], + created: Date.now(), + id: "", + model: body.model, + object: "chat.completion.chunk", + }; + } + } +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index f782f1c78..4856a7b11 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -6,6 +6,7 @@ import { CohereApi } from "./apis/Cohere.js"; import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; import { JinaApi } from "./apis/Jina.js"; +import { MoonshotApi } from "./apis/Moonshot.js"; import { OpenAIApi } from "./apis/OpenAI.js"; dotenv.config(); @@ -48,6 +49,8 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi { }); case "deepseek": return new DeepSeekApi(config); + case "moonshot": + return new MoonshotApi(config); case "groq": return new OpenAIApi({ ...config,