tests: exponential backoff, message content, deduplicate chunks
This commit is contained in:
parent
7dd3f8b6aa
commit
cc50d08e43
10 changed files with 741 additions and 87 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import { Chunk } from "../../index.js";
|
||||
import { deduplicateArray } from "../../util/index.js";
|
||||
import { Chunk } from "../../index";
|
||||
import { deduplicateArray } from "../../util/index";
|
||||
|
||||
export function deduplicateChunks(chunks: Chunk[]): Chunk[] {
|
||||
return deduplicateArray(chunks, (a, b) => {
|
||||
|
|
|
|||
117
core/context/retrieval/utils.test.ts
Normal file
117
core/context/retrieval/utils.test.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
// Generated by Continue
|
||||
import { Chunk } from "../../index";
|
||||
|
||||
import { deduplicateChunks } from "./util";
|
||||
|
||||
describe("deduplicateChunks", () => {
|
||||
it("returns an empty array when given an empty array", () => {
|
||||
const chunks: Chunk[] = [];
|
||||
const result = deduplicateChunks(chunks);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns the same array when given an array with no duplicates", () => {
|
||||
const chunks: Chunk[] = [
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
filepath: "file2.ts",
|
||||
startLine: 2,
|
||||
endLine: 3,
|
||||
content: "chunk 2",
|
||||
digest: "",
|
||||
index: 1,
|
||||
},
|
||||
];
|
||||
const result = deduplicateChunks(chunks);
|
||||
expect(result).toEqual(chunks);
|
||||
});
|
||||
|
||||
it("removes duplicate chunks", () => {
|
||||
const chunks: Chunk[] = [
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1 duplicate",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
filepath: "file2.ts",
|
||||
startLine: 2,
|
||||
endLine: 3,
|
||||
content: "chunk 2",
|
||||
digest: "",
|
||||
index: 1,
|
||||
},
|
||||
];
|
||||
const result = deduplicateChunks(chunks);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
filepath: "file2.ts",
|
||||
startLine: 2,
|
||||
endLine: 3,
|
||||
content: "chunk 2",
|
||||
digest: "",
|
||||
index: 1,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles chunks with different contents but the same file lines as duplicates", () => {
|
||||
const chunks: Chunk[] = [
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1 different content",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
];
|
||||
const result = deduplicateChunks(chunks);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
filepath: "file1.ts",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
content: "chunk 1",
|
||||
digest: "",
|
||||
index: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
0
core/edit/lazy/findInAst.test.ts
Normal file
0
core/edit/lazy/findInAst.test.ts
Normal file
|
|
@ -4,6 +4,16 @@ import {
|
|||
dedentAndGetCommonWhitespace,
|
||||
deduplicateArray,
|
||||
getLastNPathParts,
|
||||
copyOf,
|
||||
getBasename,
|
||||
getMarkdownLanguageTagForFile,
|
||||
getRelativePath,
|
||||
getUniqueFilePath,
|
||||
groupByLastNPathParts,
|
||||
removeCodeBlocksAndTrim,
|
||||
removeQuotesAndEscapes,
|
||||
shortestRelativePaths,
|
||||
splitPath,
|
||||
} from "./";
|
||||
|
||||
describe("getLastNPathParts", () => {
|
||||
|
|
@ -248,15 +258,6 @@ World
|
|||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it.skip("should handle strings with tabs", () => {
|
||||
const result = dedent`
|
||||
\tHello
|
||||
\t\tWorld
|
||||
\t\t\t!
|
||||
`;
|
||||
expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
|
||||
});
|
||||
|
||||
it("should handle interpolated values", () => {
|
||||
const world = "World";
|
||||
const result = dedent`
|
||||
|
|
@ -326,6 +327,15 @@ World
|
|||
expect(result).toBe("Hello\r\n World");
|
||||
});
|
||||
|
||||
it.skip("should handle strings with tabs", () => {
|
||||
const result = dedent`
|
||||
\tHello
|
||||
\t\tWorld
|
||||
\t\t\t!
|
||||
`;
|
||||
expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
|
||||
});
|
||||
|
||||
it("should not count empty lines in the minimum indentation", () => {
|
||||
const result = dedent`
|
||||
Hello
|
||||
|
|
@ -353,3 +363,338 @@ ${code}
|
|||
\`\`\``);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeQuotesAndEscapes", () => {
|
||||
it("should remove surrounding double quotes and unescape characters", () => {
|
||||
const input = '"Hello \\"World\\""';
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe('Hello "World"');
|
||||
});
|
||||
|
||||
it("should remove surrounding single quotes and unescape characters", () => {
|
||||
const input = "'It\\'s a test'";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("It's a test");
|
||||
});
|
||||
|
||||
it("should handle smart quotes and remove them", () => {
|
||||
const input = "“Smart Quotes”";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("Smart Quotes");
|
||||
});
|
||||
|
||||
it("should remove backticks if present", () => {
|
||||
const input = "`Some code snippet`";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("Some code snippet");
|
||||
});
|
||||
|
||||
it("should handle multiple layers of quotes", () => {
|
||||
const input = "\"\"''``Nested``''\"\"";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("Nested");
|
||||
});
|
||||
|
||||
it("should handle strings without quotes", () => {
|
||||
const input = "No quotes here";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("No quotes here");
|
||||
});
|
||||
|
||||
it("should handle empty strings", () => {
|
||||
const input = "";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("");
|
||||
});
|
||||
|
||||
it("should handle strings with only escape sequences", () => {
|
||||
const input = "\\n\\t\\\\";
|
||||
const output = removeQuotesAndEscapes(input);
|
||||
expect(output).toBe("\n\t\\");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBasename", () => {
|
||||
it("should return the base name of a Unix-style path", () => {
|
||||
const filepath = "/home/user/documents/file.txt";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should return the base name of a Windows-style path", () => {
|
||||
const filepath = "C:\\Users\\User\\Documents\\file.txt";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should handle paths with mixed separators", () => {
|
||||
const filepath = "C:/Users\\User/Documents/file.txt";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("file.txt");
|
||||
});
|
||||
|
||||
it("should return an empty string for empty input", () => {
|
||||
const filepath = "";
|
||||
const output = getBasename(filepath);
|
||||
expect(output).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupByLastNPathParts", () => {
|
||||
it("should group filepaths by their last N parts", () => {
|
||||
const filepaths = [
|
||||
"/a/b/c/d/file1.txt",
|
||||
"/x/y/z/file1.txt",
|
||||
"/a/b/c/d/file2.txt",
|
||||
];
|
||||
const output = groupByLastNPathParts(filepaths, 2);
|
||||
expect(output).toEqual({
|
||||
"d/file1.txt": ["/a/b/c/d/file1.txt"],
|
||||
"z/file1.txt": ["/x/y/z/file1.txt"],
|
||||
"d/file2.txt": ["/a/b/c/d/file2.txt"],
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle an empty array", () => {
|
||||
const filepaths: string[] = [];
|
||||
const output = groupByLastNPathParts(filepaths, 2);
|
||||
expect(output).toEqual({});
|
||||
});
|
||||
|
||||
it("should handle N greater than path parts", () => {
|
||||
const filepaths = ["/file.txt"];
|
||||
const output = groupByLastNPathParts(filepaths, 5);
|
||||
expect(output).toEqual({ "/file.txt": ["/file.txt"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUniqueFilePath", () => {
|
||||
it("should return a unique file path within the group", () => {
|
||||
const item = "/a/b/c/file.txt";
|
||||
const itemGroups = {
|
||||
"c/file.txt": ["/a/b/c/file.txt", "/x/y/c/file.txt"],
|
||||
};
|
||||
const output = getUniqueFilePath(item, itemGroups);
|
||||
expect(output).toBe("b/c/file.txt");
|
||||
});
|
||||
|
||||
it("should return the last two parts if unique", () => {
|
||||
const item = "/a/b/c/file.txt";
|
||||
const itemGroups = {
|
||||
"c/file.txt": ["/a/b/c/file.txt"],
|
||||
};
|
||||
const output = getUniqueFilePath(item, itemGroups);
|
||||
expect(output).toBe("c/file.txt");
|
||||
});
|
||||
|
||||
it("should handle when additional parts are needed to make it unique", () => {
|
||||
const item = "/a/b/c/d/e/file.txt";
|
||||
const itemGroups = {
|
||||
"e/file.txt": ["/a/b/c/d/e/file.txt", "/x/y/z/e/file.txt"],
|
||||
};
|
||||
const output = getUniqueFilePath(item, itemGroups);
|
||||
expect(output).toBe("d/e/file.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortestRelativePaths", () => {
|
||||
it("should return shortest unique paths", () => {
|
||||
const paths = [
|
||||
"/a/b/c/file.txt",
|
||||
"/a/b/d/file.txt",
|
||||
"/a/b/d/file2.txt",
|
||||
"/x/y/z/file.txt",
|
||||
];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual([
|
||||
"c/file.txt",
|
||||
"d/file.txt",
|
||||
"file2.txt",
|
||||
"z/file.txt",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle empty array", () => {
|
||||
const paths: string[] = [];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle paths with same base names", () => {
|
||||
const paths = [
|
||||
"/a/b/c/d/file.txt",
|
||||
"/a/b/c/e/file.txt",
|
||||
"/a/b/f/g/h/file.txt",
|
||||
];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual(["d/file.txt", "e/file.txt", "h/file.txt"]);
|
||||
});
|
||||
|
||||
it("should handle paths where entire path is needed", () => {
|
||||
const paths = ["/a/b/c/file.txt", "/a/b/c/file.txt", "/a/b/c/file.txt"];
|
||||
const output = shortestRelativePaths(paths);
|
||||
expect(output).toEqual(["file.txt", "file.txt", "file.txt"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitPath", () => {
|
||||
it("should split Unix-style paths", () => {
|
||||
const path = "/a/b/c/d/e.txt";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual(["", "a", "b", "c", "d", "e.txt"]);
|
||||
});
|
||||
|
||||
it("should split Windows-style paths", () => {
|
||||
const path = "C:\\Users\\User\\Documents\\file.txt";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual(["C:", "Users", "User", "Documents", "file.txt"]);
|
||||
});
|
||||
|
||||
it("should handle withRoot parameter", () => {
|
||||
const path = "/a/b/c/d/e.txt";
|
||||
const withRoot = "/a/b";
|
||||
const output = splitPath(path, withRoot);
|
||||
expect(output).toEqual(["b", "c", "d", "e.txt"]);
|
||||
});
|
||||
|
||||
it("should handle empty path", () => {
|
||||
const path = "";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual([""]);
|
||||
});
|
||||
|
||||
it("should handle paths with multiple consecutive separators", () => {
|
||||
const path = "/a//b/c/d/e.txt";
|
||||
const output = splitPath(path);
|
||||
expect(output).toEqual(["", "a", "", "b", "c", "d", "e.txt"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRelativePath", () => {
|
||||
it("should return the relative path with respect to workspace directories", () => {
|
||||
const filepath = "/workspace/project/src/file.ts";
|
||||
const workspaceDirs = ["/workspace/project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
|
||||
it("should return the filename if not in any workspace", () => {
|
||||
const filepath = "/other/place/file.ts";
|
||||
const workspaceDirs = ["/workspace/project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("file.ts");
|
||||
});
|
||||
|
||||
it("should handle multiple workspace directories", () => {
|
||||
const filepath = "/workspace2/project/src/file.ts";
|
||||
const workspaceDirs = ["/workspace/project", "/workspace2/project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
|
||||
it("should handle Windows-style paths", () => {
|
||||
const filepath = "C:\\workspace\\project\\src\\file.ts";
|
||||
const workspaceDirs = ["C:\\workspace\\project"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
|
||||
it("should handle paths with spaces or special characters", () => {
|
||||
const filepath = "/workspace/project folder/src/file.ts";
|
||||
const workspaceDirs = ["/workspace/project folder"];
|
||||
const output = getRelativePath(filepath, workspaceDirs);
|
||||
expect(output).toBe("src/file.ts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMarkdownLanguageTagForFile", () => {
|
||||
it("should return correct language tag for known extensions", () => {
|
||||
expect(getMarkdownLanguageTagForFile("test.py")).toBe("python");
|
||||
expect(getMarkdownLanguageTagForFile("test.tsx")).toBe("tsx");
|
||||
expect(getMarkdownLanguageTagForFile("test.java")).toBe("java");
|
||||
expect(getMarkdownLanguageTagForFile("test.md")).toBe("markdown");
|
||||
expect(getMarkdownLanguageTagForFile("test.sh")).toBe("shell");
|
||||
expect(getMarkdownLanguageTagForFile("test.sql")).toBe("sql");
|
||||
});
|
||||
|
||||
it("should return the extension if not in the known list", () => {
|
||||
expect(getMarkdownLanguageTagForFile("file.unknownext")).toBe("unknownext");
|
||||
});
|
||||
|
||||
it("should handle filenames without extension", () => {
|
||||
expect(getMarkdownLanguageTagForFile("Makefile")).toBe("Makefile");
|
||||
});
|
||||
|
||||
it("should handle filenames with multiple dots", () => {
|
||||
expect(getMarkdownLanguageTagForFile("archive.tar.gz")).toBe("gz");
|
||||
});
|
||||
|
||||
it("should handle edge case with empty string as filename", () => {
|
||||
expect(getMarkdownLanguageTagForFile("")).toBe("");
|
||||
});
|
||||
|
||||
it("should correctly identify files with no extensions", () => {
|
||||
expect(getMarkdownLanguageTagForFile("README")).toBe("README");
|
||||
});
|
||||
});
|
||||
|
||||
describe("copyOf", () => {
|
||||
it("should create a deep copy of an object", () => {
|
||||
const original = { a: 1, b: { c: 2 } };
|
||||
const copied = copyOf(original);
|
||||
expect(copied).toEqual(original);
|
||||
expect(copied).not.toBe(original);
|
||||
expect(copied.b).not.toBe(original.b);
|
||||
});
|
||||
|
||||
it("should handle arrays", () => {
|
||||
const original = [1, 2, { a: 3 }];
|
||||
const copied = copyOf(original);
|
||||
expect(copied).toEqual(original);
|
||||
expect(copied).not.toBe(original);
|
||||
expect(copied[2]).not.toBe(original[2]);
|
||||
});
|
||||
|
||||
it("should return null for null input", () => {
|
||||
expect(copyOf(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("should return undefined for undefined input", () => {
|
||||
expect(copyOf(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle objects with circular references gracefully", () => {
|
||||
// This may not be feasible with JSON.stringify – consider alternative methods like a library for deep cloning.
|
||||
const a: any = {};
|
||||
a.self = a;
|
||||
expect(() => copyOf(a)).toThrow(); // Ideally, handle circular refs before calling JSON.stringify
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeCodeBlocksAndTrim", () => {
|
||||
it("should remove code blocks from text", () => {
|
||||
const text =
|
||||
"Here is some text.\n```javascript\nconsole.log('Hello');\n```\nMore text.";
|
||||
const output = removeCodeBlocksAndTrim(text);
|
||||
expect(output).toBe("Here is some text.\n\nMore text.");
|
||||
});
|
||||
|
||||
it("should remove multiple code blocks", () => {
|
||||
const text =
|
||||
"Text before.\n```code block 1```\nBetween code blocks.\n```code block 2```\nText after.";
|
||||
const output = removeCodeBlocksAndTrim(text);
|
||||
expect(output).toBe("Text before.\n\nBetween code blocks.\n\nText after.");
|
||||
});
|
||||
|
||||
it("should handle text without code blocks", () => {
|
||||
const text = "No code blocks here.";
|
||||
const output = removeCodeBlocksAndTrim(text);
|
||||
expect(output).toBe("No code blocks here.");
|
||||
});
|
||||
|
||||
it("should trim whitespace from the result", () => {
|
||||
const text = " \n```code```\n ";
|
||||
const output = removeCodeBlocksAndTrim(text);
|
||||
expect(output).toBe("");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
export function removeQuotesAndEscapes(output: string): string {
|
||||
output = output.trim();
|
||||
export function removeQuotesAndEscapes(input: string): string {
|
||||
let output = input.trim();
|
||||
|
||||
// Replace smart quotes
|
||||
output = output.replace("“", '"');
|
||||
output = output.replace("”", '"');
|
||||
output = output.replace("‘", "'");
|
||||
output = output.replace("’", "'");
|
||||
output = output.replaceAll("“", '"');
|
||||
output = output.replaceAll("”", '"');
|
||||
output = output.replaceAll("‘", "'");
|
||||
output = output.replaceAll("’", "'");
|
||||
|
||||
// Remove escapes
|
||||
output = output.replace('\\"', '"');
|
||||
output = output.replace("\\'", "'");
|
||||
output = output.replace("\\n", "\n");
|
||||
output = output.replace("\\t", "\t");
|
||||
output = output.replace("\\\\", "\\");
|
||||
output = output.replaceAll('\\"', '"');
|
||||
output = output.replaceAll("\\'", "'");
|
||||
output = output.replaceAll("\\n", "\n");
|
||||
output = output.replaceAll("\\t", "\t");
|
||||
output = output.replaceAll("\\\\", "\\");
|
||||
while (
|
||||
(output.startsWith('"') && output.endsWith('"')) ||
|
||||
(output.startsWith("'") && output.endsWith("'"))
|
||||
|
|
@ -192,63 +192,37 @@ export function getRelativePath(
|
|||
}
|
||||
|
||||
export function getMarkdownLanguageTagForFile(filepath: string): string {
|
||||
const extToLangMap: { [key: string]: string } = {
|
||||
py: "python",
|
||||
js: "javascript",
|
||||
jsx: "jsx",
|
||||
tsx: "tsx",
|
||||
ts: "typescript",
|
||||
java: "java",
|
||||
go: "go",
|
||||
rb: "ruby",
|
||||
rs: "rust",
|
||||
c: "c",
|
||||
cpp: "cpp",
|
||||
cs: "csharp",
|
||||
php: "php",
|
||||
scala: "scala",
|
||||
swift: "swift",
|
||||
kt: "kotlin",
|
||||
md: "markdown",
|
||||
json: "json",
|
||||
html: "html",
|
||||
css: "css",
|
||||
sh: "shell",
|
||||
yaml: "yaml",
|
||||
toml: "toml",
|
||||
tex: "latex",
|
||||
sql: "sql",
|
||||
ps1: "powershell",
|
||||
};
|
||||
|
||||
const ext = filepath.split(".").pop();
|
||||
switch (ext) {
|
||||
case "py":
|
||||
return "python";
|
||||
case "js":
|
||||
return "javascript";
|
||||
case "jsx":
|
||||
return "jsx";
|
||||
case "tsx":
|
||||
return "tsx";
|
||||
case "ts":
|
||||
return "typescript";
|
||||
case "java":
|
||||
return "java";
|
||||
case "go":
|
||||
return "go";
|
||||
case "rb":
|
||||
return "ruby";
|
||||
case "rs":
|
||||
return "rust";
|
||||
case "c":
|
||||
return "c";
|
||||
case "cpp":
|
||||
return "cpp";
|
||||
case "cs":
|
||||
return "csharp";
|
||||
case "php":
|
||||
return "php";
|
||||
case "scala":
|
||||
return "scala";
|
||||
case "swift":
|
||||
return "swift";
|
||||
case "kt":
|
||||
return "kotlin";
|
||||
case "md":
|
||||
return "markdown";
|
||||
case "json":
|
||||
return "json";
|
||||
case "html":
|
||||
return "html";
|
||||
case "css":
|
||||
return "css";
|
||||
case "sh":
|
||||
return "shell";
|
||||
case "yaml":
|
||||
return "yaml";
|
||||
case "toml":
|
||||
return "toml";
|
||||
case "tex":
|
||||
return "latex";
|
||||
case "sql":
|
||||
return "sql";
|
||||
case "ps1":
|
||||
return "powershell";
|
||||
default:
|
||||
return ext ?? "";
|
||||
}
|
||||
return ext ? (extToLangMap[ext] ?? ext) : "";
|
||||
}
|
||||
|
||||
export function copyOf(obj: any): any {
|
||||
|
|
@ -257,6 +231,7 @@ export function copyOf(obj: any): any {
|
|||
}
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
``;
|
||||
|
||||
export function deduplicateArray<T>(
|
||||
array: T[],
|
||||
|
|
|
|||
74
core/util/messageContent.test.ts
Normal file
74
core/util/messageContent.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { stripImages, renderChatMessage, renderContextItems, normalizeToMessageParts } from "./messageContent.js";
|
||||
import { ChatMessage, ContextItem, MessageContent, MessagePart } from "../index.js";
|
||||
|
||||
describe("messageContent utility functions", () => {
|
||||
describe("stripImages", () => {
|
||||
it("should return the string as is if messageContent is a string", () => {
|
||||
const content: MessageContent = "This is a test message.";
|
||||
expect(stripImages(content)).toBe("This is a test message.");
|
||||
});
|
||||
|
||||
it("should strip out image parts and join text parts of a message", () => {
|
||||
const content: MessageContent = [
|
||||
{ type: "text", text: "This is" },
|
||||
{ type: "imageUrl", imageUrl: { url: "http://example.com/image1.png" } },
|
||||
{ type: "text", text: "a test message." },
|
||||
];
|
||||
expect(stripImages(content)).toBe("This is\na test message.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderChatMessage", () => {
|
||||
it("should render user, assistant, or system messages with stripped image content", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{ type: "text", text: "Hello," },
|
||||
{ type: "imageUrl", imageUrl: { url: "http://example.com/image.png" } },
|
||||
{ type: "text", text: "world!" },
|
||||
],
|
||||
};
|
||||
expect(renderChatMessage(message)).toBe("Hello,\nworld!");
|
||||
});
|
||||
|
||||
it("should render tool messages as is", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "tool",
|
||||
content: "Command output message",
|
||||
toolCallId: "1",
|
||||
};
|
||||
expect(renderChatMessage(message)).toBe("Command output message");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderContextItems", () => {
|
||||
it("should concatenate the content of context items with two newlines", () => {
|
||||
const items: ContextItem[] = [
|
||||
{ content: "Context Item 1", name: "Item1", description: "Description1" },
|
||||
{ content: "Context Item 2", name: "Item2", description: "Description2" },
|
||||
];
|
||||
expect(renderContextItems(items)).toBe("Context Item 1\n\nContext Item 2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeToMessageParts", () => {
|
||||
it("should normalize user, assistant, or system messages to MessagePart array", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: "This is a test message.",
|
||||
};
|
||||
const expected: MessagePart[] = [{ type: "text", text: "This is a test message." }];
|
||||
expect(normalizeToMessageParts(message)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should normalize tool messages to MessagePart array", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "tool",
|
||||
content: "Tool message content",
|
||||
toolCallId: "1",
|
||||
};
|
||||
const expected: MessagePart[] = [{ type: "text", text: "Tool message content" }];
|
||||
expect(normalizeToMessageParts(message)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,7 @@ import {
|
|||
ContextItem,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
} from "../index.js";
|
||||
} from "../index";
|
||||
|
||||
export function stripImages(messageContent: MessageContent): string {
|
||||
if (typeof messageContent === "string") {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@ dotenv.config();
|
|||
const CONTINUE_GLOBAL_DIR =
|
||||
process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue");
|
||||
|
||||
// export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config {
|
||||
// return config;
|
||||
// }`;
|
||||
|
||||
export const DEFAULT_CONFIG_TS_CONTENTS = `export function modifyConfig(config: Config): Config {
|
||||
return config;
|
||||
}`;
|
||||
|
|
|
|||
142
core/util/withExponentialBackoff.test.ts
Normal file
142
core/util/withExponentialBackoff.test.ts
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
// Generated by continue
|
||||
|
||||
import {
|
||||
withExponentialBackoff,
|
||||
APIError,
|
||||
RETRY_AFTER_HEADER,
|
||||
} from "./withExponentialBackoff";
|
||||
|
||||
describe("withExponentialBackoff", () => {
|
||||
it("should return result when apiCall succeeds on first attempt", async () => {
|
||||
// Arrange
|
||||
const apiCall = jest.fn().mockResolvedValue("Success");
|
||||
|
||||
// Act
|
||||
const result = await withExponentialBackoff(apiCall);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe("Success");
|
||||
expect(apiCall).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should throw error when apiCall fails with non-429 error", async () => {
|
||||
// Arrange
|
||||
const error = new Error("Some error");
|
||||
const apiCall = jest.fn().mockRejectedValue(error);
|
||||
|
||||
// Act & Assert
|
||||
await expect(withExponentialBackoff(apiCall)).rejects.toThrow("Some error");
|
||||
expect(apiCall).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should retry when apiCall fails with 429 and no Retry-After header", async () => {
|
||||
// Arrange
|
||||
const apiCall = jest.fn();
|
||||
|
||||
const firstError: APIError = new Error("Rate limit");
|
||||
firstError.response = {
|
||||
status: 429,
|
||||
headers: {
|
||||
get: () => null, // No Retry-After header
|
||||
},
|
||||
} as unknown as Response;
|
||||
|
||||
// First call fails with 429, second call succeeds
|
||||
apiCall.mockRejectedValueOnce(firstError).mockResolvedValueOnce("Success");
|
||||
|
||||
// Act
|
||||
const result = await withExponentialBackoff(
|
||||
apiCall,
|
||||
5,
|
||||
0.01, // initialDelaySeconds
|
||||
);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe("Success");
|
||||
expect(apiCall).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should retry when apiCall fails with 429 and Retry-After header", async () => {
|
||||
// Arrange
|
||||
const apiCall = jest.fn();
|
||||
|
||||
const firstError: APIError = new Error("Rate limit");
|
||||
firstError.response = {
|
||||
status: 429,
|
||||
headers: {
|
||||
get: (headerName: string) => {
|
||||
if (headerName === RETRY_AFTER_HEADER) {
|
||||
return "0.02";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
} as unknown as Response;
|
||||
|
||||
// First call fails with 429, second call succeeds
|
||||
apiCall.mockRejectedValueOnce(firstError).mockResolvedValueOnce("Success");
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
const promise = withExponentialBackoff(apiCall, 5, 0.01);
|
||||
|
||||
// Advance timers to cover the delay
|
||||
await jest.advanceTimersByTimeAsync(20);
|
||||
|
||||
const result = await promise;
|
||||
|
||||
// Assert
|
||||
expect(result).toBe("Success");
|
||||
expect(apiCall).toHaveBeenCalledTimes(2);
|
||||
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it("should throw error after maxTries reached", async () => {
|
||||
// Arrange
|
||||
const apiCall = jest.fn();
|
||||
|
||||
const error: APIError = new Error("Rate limit");
|
||||
error.response = {
|
||||
status: 429,
|
||||
headers: {
|
||||
get: () => null,
|
||||
},
|
||||
} as unknown as Response;
|
||||
|
||||
apiCall.mockRejectedValue(error);
|
||||
|
||||
const maxTries = 3;
|
||||
const initialDelaySeconds = 0.01;
|
||||
|
||||
// Act & Assert
|
||||
await expect(
|
||||
withExponentialBackoff(apiCall, maxTries, initialDelaySeconds),
|
||||
).rejects.toThrow("Failed to make API call after max tries");
|
||||
|
||||
expect(apiCall).toHaveBeenCalledTimes(maxTries);
|
||||
});
|
||||
|
||||
it("should not call if maxTries is 0", async () => {
|
||||
const apiCall = jest.fn();
|
||||
|
||||
const error: APIError = new Error("Rate limit");
|
||||
error.response = {
|
||||
status: 429,
|
||||
headers: {
|
||||
get: () => null,
|
||||
},
|
||||
} as unknown as Response;
|
||||
|
||||
apiCall.mockRejectedValue(error);
|
||||
|
||||
const maxTries = 0;
|
||||
const initialDelaySeconds = 0.01;
|
||||
|
||||
await expect(
|
||||
withExponentialBackoff(apiCall, maxTries, initialDelaySeconds),
|
||||
).rejects.toThrow("Failed to make API call after max tries");
|
||||
|
||||
expect(apiCall).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
interface APIError extends Error {
|
||||
export interface APIError extends Error {
|
||||
response?: Response;
|
||||
}
|
||||
|
||||
|
|
@ -6,18 +6,15 @@ export const RETRY_AFTER_HEADER = "Retry-After";
|
|||
|
||||
const withExponentialBackoff = async <T>(
|
||||
apiCall: () => Promise<T>,
|
||||
maxRetries = 5,
|
||||
maxTries = 5,
|
||||
initialDelaySeconds = 1,
|
||||
) => {
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
for (let attempt = 0; attempt < maxTries; attempt++) {
|
||||
try {
|
||||
const result = await apiCall();
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
if (
|
||||
(error as APIError).response?.status === 429 &&
|
||||
attempt < maxRetries - 1
|
||||
) {
|
||||
if ((error as APIError).response?.status === 429) {
|
||||
const retryAfter = (error as APIError).response?.headers.get(
|
||||
RETRY_AFTER_HEADER,
|
||||
);
|
||||
|
|
@ -35,7 +32,7 @@ const withExponentialBackoff = async <T>(
|
|||
}
|
||||
}
|
||||
}
|
||||
throw new Error("Failed to make API call after multiple retries");
|
||||
throw new Error("Failed to make API call after max tries");
|
||||
};
|
||||
|
||||
export { withExponentialBackoff };
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue