Merge branch 'main' into dallin/docs-ui

This commit is contained in:
Patrick Erichsen 2024-11-18 12:26:52 -08:00 • committed by GitHub
commit 906ce64045
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
72 changed files with 2028 additions and 641 deletions

View file

@ -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,

View file

@ -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",

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,2 @@
export * from "./python";
export * from "./typescript";

View file

@ -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,
];

View file

@ -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: [

View file

@ -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);
}

View file

@ -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 });

View file

@ -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<string, number>();
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);
}
}
}
}

View file

@ -0,0 +1,166 @@
import { noDoubleNewlineAfterClosingBracket } from "./lineStream";
describe("noDoubleNewlineAfterClosingBracket", () => {
// Helper function to convert an array to an async generator
async function* arrayToAsyncGenerator<T>(array: T[]): AsyncGenerator<T> {
for (const item of array) {
yield item;
}
}
// Helper function to collect lines from the async generator
async function collectLines(lines: AsyncIterable<string>): Promise<string[]> {
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);
});
});

View file

@ -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() {
<p>Description text.</p>
</div>
</div>`,
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 {
<ChildComponent <|fim|> />
</main>
`,
llmOutput: "name=\"World\"",
expectedCompletion: "name=\"World\"",
llmOutput: 'name="World"',
expectedCompletion: 'name="World"',
},
{

View file

@ -0,0 +1,215 @@
import { jest } from "@jest/globals";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
function createMockGenerator(
data: string[],
delay: number = 0,
): () => AsyncGenerator<string> {
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<string>>()
.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<string>>()
.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);
});
});

View file

@ -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<string>,
multiline: boolean,
): AsyncGenerator<string> {
// 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;
}
}
}

View file

@ -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<T>(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<number>(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<number>(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<number>(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<number>(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<number>(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<number>(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);
});
});

View file

@ -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(

14
core/index.d.ts vendored
View file

@ -224,11 +224,16 @@ export interface IContextProvider {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
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;

View file

@ -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")) {

59
core/llm/llms/Moonshot.ts Normal file
View file

@ -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<LLMOptions> = {
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<string> {
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;

View file

@ -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,

View file

@ -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 & {

View file

@ -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
}
}
]
}

View file

@ -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": {

View file

@ -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"
},

View file

@ -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

View file

@ -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) {

View file

@ -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,
}),
},
);

View file

@ -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) {

View file

@ -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)$")
)

View file

@ -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)$")
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View file

@ -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));
},
[],

View file

@ -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 (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("rejectDiff")}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-600" />
<span className="sm:hidden">Reject</span>
<span className="max-sm:hidden md:hidden">Reject all</span>
<span className="max-md:hidden">Reject all changes</span>
</button>
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("acceptDiff")}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-600" />
<span className="sm:hidden">Accept</span>
<span className="max-sm:hidden md:hidden">Accept all</span>
<span className="max-md:hidden">Accept all changes</span>
</button>
</div>
);
}

View file

@ -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<boolean | undefined>(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 (
<>
<HeaderButtonWithToolTip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
>
<HandThumbUpIcon
className={`mx-0.5 h-3.5 w-3.5 ${feedback === true ? "text-green-400" : "text-gray-500"}`}
/>
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Unhelpful"
tabIndex={-1}
onClick={() => sendFeedback(false)}
>
<HandThumbDownIcon
className={`h-3.5 w-3.5 ${feedback === false ? "text-red-400" : "text-gray-500"}`}
/>
</HeaderButtonWithToolTip>{" "}
</>
);
}

View file

@ -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 (
<div
className={`mx-2 mb-2 mt-2 flex h-7 items-center justify-between pb-0 text-xs text-gray-400`}
>
<div className="flex-1" />
{isCurCheckpoint && (
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons pendingApplyStates={pendingApplyStates} />
)}
{hasClosedAllStreams && <UndoAndRedoButtons />}
</div>
)}
<div className="flex flex-1 justify-end">
<CopyIconButton
tabIndex={-1}
text={stripImages(item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<FeedbackButtons item={item} />
</div>
</div>
);
}

View file

@ -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 <MultifileEditActions index={index} item={item} />;
}
return (
<div className="mx-2 mb-2 flex h-7 cursor-default items-center justify-end space-x-1 pb-0 text-xs text-gray-400">
{isTruncated && (
<HeaderButtonWithToolTip
tabIndex={-1}
text="Continue generation"
onClick={onContinueGeneration}
>
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</HeaderButtonWithToolTip>
)}
{shouldRenderDelete && (
<HeaderButtonWithToolTip text="Delete" tabIndex={-1} onClick={onDelete}>
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</HeaderButtonWithToolTip>
)}
<CopyIconButton
tabIndex={-1}
text={stripImages(item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<FeedbackButtons item={item} />
</div>
);
}

View file

@ -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 (
<div
className={isStepAheadOfCurCheckpoint ? "opacity-25" : "relative"}
style={{
minHeight: props.isLast ? "50vh" : 0,
}}
>
<ContentDiv>
{uiConfig?.displayRawMarkdown ? (
<pre
className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"
style={{ fontSize: getFontSize() - 2 }}
>
{stripImages(props.item.message.content)}
</pre>
) : (
<StyledMarkdownPreview
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
/>
)}
</ContentDiv>
{/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on */}
<div
className={`${shouldHideActions && "hidden"} transition-opacity duration-300 ease-in-out`}
>
{!shouldHideActions && (
<ResponseActions
isTruncated={isTruncated}
onDelete={onDelete}
onContinueGeneration={onContinueGeneration}
index={props.index}
item={props.item}
/>
)}
</div>
</div>
);
}

View file

@ -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 (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleUndoOrRedo("undo")}
>
<ArrowUturnLeftIcon className="mr-2 h-3.5 w-3.5" />
Undo changes
</button>
{shouldRenderRedo && (
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleUndoOrRedo("redo")}
>
<ArrowUturnRightIcon className="mr-2 h-3.5 w-3.5" />
Redo changes
</button>
)}
</div>
);
}

View file

@ -0,0 +1 @@
export { default } from "./StepContainer";

View file

@ -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<boolean | undefined>(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 (
<div
className="relative"
style={{
minHeight: props.isLast ? "50vh" : 0,
}}
>
<ContentDiv
hidden={!props.open}
isUserInput={isUserInput}
fontSize={getFontSize()}
>
{uiConfig?.displayRawMarkdown ? (
<pre
className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"
style={{ fontSize: getFontSize() - 2 }}
>
{stripImages(props.item.message.content)}
</pre>
) : (
<StyledMarkdownPreview
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
contextItems={props.item.contextItems}
/>
)}
</ContentDiv>
<div
className="xs:flex mx-2 mb-2 flex h-7 cursor-default items-center justify-end gap-0.5 pb-0 text-xs text-gray-400"
style={{
opacity: shouldRenderActions ? 1 : 0,
pointerEvents: shouldRenderActions ? "auto" : "none",
}}
>
{truncatedEarly && (
<HeaderButtonWithToolTip
tabIndex={-1}
text="Continue generation"
onClick={props.onContinueGeneration}
>
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</HeaderButtonWithToolTip>
)}
{props.index !== 1 && (
<HeaderButtonWithToolTip
text="Delete"
tabIndex={-1}
onClick={props.onDelete}
>
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</HeaderButtonWithToolTip>
)}
<CopyIconButton
tabIndex={-1}
text={stripImages(props.item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<HeaderButtonWithToolTip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
>
<HandThumbUpIcon
className={`mx-0.5 h-3.5 w-3.5 ${feedback === true ? "text-green-400" : "text-gray-500"}`}
/>
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Unhelpful"
tabIndex={-1}
onClick={() => sendFeedback(false)}
>
<HandThumbDownIcon
className={`h-3.5 w-3.5 ${feedback === false ? "text-red-400" : "text-gray-500"}`}
/>
</HeaderButtonWithToolTip>
</div>
</div>
);
}
export default StepContainer;

View file

@ -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) {

View file

@ -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 (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={handleRejectAll}
>
<XMarkIcon className="mr-1 h-4 w-4" />
Reject all changes
</button>
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={handleAcceptAll}
>
<CheckIcon className="mr-1 h-4 w-4" />
Accept all changes
</button>
</div>
);
}

View file

@ -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<NodeJS.Timeout | null>(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 (
<div className={`mb-1 ${props.hidden ? "hidden" : ""}`}>
{shouldShowAcceptRejectButtons && <AcceptRejectAllButtons />}
<div className={`relative flex px-2`}>
<GradientBorder
loading={active && props.isLastUserInput ? 1 : 0}

View file

@ -22,7 +22,7 @@ import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
const StyledDiv = styled.div<{ isHidden: boolean }>`
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"
>
<div className="flex items-center justify-start gap-2 whitespace-nowrap">
<ModelSelect />

View file

@ -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<string | null>(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,
);

View file

@ -33,16 +33,17 @@ export default function ApplyActions(props: ApplyActionsProps) {
);
case "done":
return (
<div className="flex items-center rounded bg-zinc-700 pl-2 pr-1">
<span className="mr-2 text-xs text-gray-400">
{`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`} remaining`}
<div className="xs:pl-2 xs:pr-1 flex items-center rounded bg-zinc-700">
<span className="max-xs:hidden xs:mr-1 text-xs text-gray-400">
{`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`}`}
<span className="max-md:hidden">{` remaining`}</span>
</span>
<ToolbarButtonWithTooltip
onClick={onClickReject}
tooltipContent={`Reject all (${getMetaKeyLabel()}⇧⌫)`}
>
<XMarkIcon className="h-4 w-4 text-red-600" />
<XMarkIcon className="h-4 w-4 text-red-600 hover:brightness-125" />
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
@ -56,9 +57,9 @@ export default function ApplyActions(props: ApplyActionsProps) {
case "closed":
if (!hasRejected && props.applyState.numDiffs === 0) {
return (
<span className="flex items-center rounded bg-zinc-700 pl-2 pr-1 text-slate-400">
Applied
<CheckIcon className="h-4 w-4 pl-1 hover:brightness-125" />
<span className="flex items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
<span className="max-sm:hidden">Applied</span>
<CheckIcon className="h-4 w-4 hover:brightness-125 sm:px-1" />
</span>
);
}

View file

@ -15,18 +15,18 @@ export default function CopyButton({ text }: CopyButtonProps) {
onClick={copyText}
>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
className="max-2xs:hidden flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
{copied ? (
<>
<CheckIcon className="h-3 w-3 text-green-500 hover:brightness-125" />
<span className="hidden sm:inline">Copied</span>
<span className="max-sm:hidden">Copied</span>
</>
) : (
<>
<ClipboardIcon className="h-3 w-3 hover:brightness-125" />
<span className="xs:inline hidden text-gray-400">Copy</span>
<span className="text-gray-400 max-sm:hidden">Copy</span>
</>
)}
</div>

View file

@ -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 (
<div className="flex max-w-[20%] items-center">
<div className="flex w-full min-w-0 items-center">
<div
className="flex cursor-pointer items-center gap-1"
className="mr-0.5 flex w-full min-w-0 cursor-pointer items-center gap-0.5"
onClick={onClickFileName}
>
<FileIcon height="20px" width="20px" filename={filepath} />
<span className="truncate hover:underline">
<span className="w-full truncate hover:underline">
{getBasename(filepath)}
{range && ` ${range}`}
</span>

View file

@ -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<string | null>(null);
const streamIdRef = useRef<string>(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 (
<TopDiv active={active}>
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip">
<div className="flex items-center">
<div className="flex min-w-0 max-w-[45%] items-center">
<ChevronDownIcon
onClick={onClickExpand}
className={`h-4 w-4 cursor-pointer text-gray-400 hover:bg-gray-800 hover:brightness-125 ${
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 hover:bg-gray-800 hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
<FileInfo filepath={props.filepath} range={props.range} />
<div className="w-full min-w-0">
<FileInfo filepath={props.filepath} range={props.range} />
</div>
</div>
<div className="flex items-center gap-3">
<div className="flex items-center gap-3 max-sm:gap-1.5">
{isGeneratingCodeBlock && (
<GeneratingCodeLoader
showLineCount={!isExpanded}

View file

@ -19,6 +19,7 @@ import FilenameLink from "./FilenameLink";
import StepContainerPreToolbar from "./StepContainerPreToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
import { ContextItemWithId } from "core";
const StyledMarkdown = styled.div<{
@ -138,8 +139,9 @@ function processCodeBlocks(tree: any) {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.codeBlockContent = node.value;
node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node;
node.data.hProperties.codeBlockContent = node.value;
if (node.meta) {
let meta = node.meta.split(" ");
@ -251,7 +253,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
});
useEffect(() => {
setMarkdownSource(props.source || "");
setMarkdownSource(patchNestedMarkdown(props.source ?? ""));
}, [props.source]);
return (

View file

@ -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;
// };

View file

@ -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;
}

View file

@ -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);

View file

@ -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);

View file

@ -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:

View file

@ -116,6 +116,29 @@ export const providers: Partial<Record<ModelProvider, ProviderInfo>> = {
],
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",

View file

@ -77,7 +77,7 @@ export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) {
)} */}
<div className="flex">
<HeaderButtonWithToolTip text="Accept">
<HeaderButtonWithToolTip text="Reject">
<XMarkIcon
className="h-4 w-4 cursor-pointer px-2"
color="red"
@ -91,7 +91,7 @@ export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) {
}}
></XMarkIcon>
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip text="Reject">
<HeaderButtonWithToolTip text="Accept">
<CheckIcon
className="h-4 w-4 cursor-pointer px-2 text-green-500"
onClick={() => {

View file

@ -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",
);

View file

@ -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() {
<StepContainer
index={index}
isLast={index === state.history.length - 1}
isFirst={index === 0}
open={
typeof stepsOpen[index] === "undefined"
? true
: stepsOpen[index]!
}
key={index}
onUserInput={(input: string) => {}}
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 ?? ""}
/>
</TimelineItem>
</div>

View file

@ -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<boolean>) => {
state.isInMultifileEdit = action.payload;
setIsInMultifileEdit: (state, { payload }: PayloadAction<boolean>) => {
state.isMultifileEdit = payload;
},
setCurCheckpointIndex: (state, { payload }: PayloadAction<number>) => {
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<ApplyState>) => {
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<IndexingStatus>) => {
console.log("update indexing status");
@ -349,6 +398,10 @@ export const {
setIsGatheringContext,
setIsInMultifileEdit,
updateIndexingStatus,
updateCurCheckpoint,
setCurCheckpointIndex,
resetNextCodeBlockToApplyIndex,
updateApplyState,
} = stateSlice.actions;
export default stateSlice.reducer;

View file

@ -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<UiState["showDialog"]>) => {
state.showDialog = action.payload;
},
resetNextCodeBlockToApplyIndex: (state) => {
state.nextCodeBlockToApplyIndex = 0;
},
incrementNextCodeBlockToApplyIndex: (state, action) => {
state.nextCodeBlockToApplyIndex++;
},
updateApplyState: (state, { payload }: PayloadAction<ApplyState>) => {
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;

View file

@ -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;

View file

View file

@ -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<ChatCompletionChunk, any, unknown> {
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",
};
}
}
}

View file

@ -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,