Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into bdougie/anthropic-prompt-true
Changeset92f20c61b109f8deecccda37c8f8785ecbbfb98e9b458bd01b3eda5b28985569
AuthorBrian 'bdougie' Douglas <brian@opensauced.pizza> · 2025-06-18 06:52 -07:00
CommitterBrian 'bdougie' Douglas <brian@opensauced.pizza> · 2025-06-18 06:52 -07:00
Parentscf53120a1148, 2d6927f4747d

Browse the files at this changeset

70 files changed

modified .github/workflows/pr_checks.yaml +1 −1
@@ -439,7 +439,7 @@
439439 GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
440440 MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
441441 AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
442- AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
442+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
443443 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
444444 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
445445
deleted core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +0 −56
@@ -1,56 +0,0 @@
1-import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases";
2-import { testRootPathContext } from "./testUtils";
3-
4-const TEST_CASES = [
5- ...PYTHON_TEST_CASES,
6- ...TYPESCRIPT_TEST_CASES,
7- {
8- nodeType: "function_definition",
9- fileName: "file1.php",
10- language: "PHP",
11- cursorPosition: { line: 12, character: 32 },
12- definitionPositions: [
13- { row: 10, column: 26 }, // Person
14- { row: 10, column: 44 }, // Address
15- ],
16- },
17- {
18- nodeType: "method_declaration",
19- fileName: "file1.php",
20- language: "PHP",
21- cursorPosition: { line: 26, character: 35 },
22- definitionPositions: [
23- { row: 15, column: 29 }, // BaseClass
24- { row: 15, column: 55 }, // FirstInterface
25- { row: 15, column: 72 }, // SecondInterface
26- { row: 25, column: 43 }, // Person
27- { row: 25, column: 61 }, // Address
28- ],
29- },
30- {
31- nodeType: "function_declaration",
32- fileName: "file1.go",
33- language: "Go",
34- cursorPosition: { line: 7, character: 21 },
35- definitionPositions: [
36- { row: 6, column: 33 }, // models.User
37- { row: 6, column: 50 }, // models.Address
38- ],
39- },
40-];
41-
42-describe("RootPathContextService", () => {
43- describe("should look for correct type definitions", () => {
44- test.each(TEST_CASES)(
45- "$language: $nodeType",
46- async ({ fileName, cursorPosition, definitionPositions }) => {
47- await testRootPathContext(
48- "files",
49- fileName,
50- cursorPosition,
51- definitionPositions,
52- );
53- },
54- );
55- });
56-});
added core/autocomplete/context/root-path-context/test/RootPathContextService.vitest.ts +57 −0
@@ -0,0 +1,57 @@
1+import { describe, test } from "vitest";
2+import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases";
3+import { testRootPathContext } from "./testUtils";
4+
5+const TEST_CASES = [
6+ ...PYTHON_TEST_CASES,
7+ ...TYPESCRIPT_TEST_CASES,
8+ {
9+ nodeType: "function_definition",
10+ fileName: "file1.php",
11+ language: "PHP",
12+ cursorPosition: { line: 12, character: 32 },
13+ definitionPositions: [
14+ { row: 10, column: 26 }, // Person
15+ { row: 10, column: 44 }, // Address
16+ ],
17+ },
18+ {
19+ nodeType: "method_declaration",
20+ fileName: "file1.php",
21+ language: "PHP",
22+ cursorPosition: { line: 26, character: 35 },
23+ definitionPositions: [
24+ { row: 15, column: 29 }, // BaseClass
25+ { row: 15, column: 55 }, // FirstInterface
26+ { row: 15, column: 72 }, // SecondInterface
27+ { row: 25, column: 43 }, // Person
28+ { row: 25, column: 61 }, // Address
29+ ],
30+ },
31+ {
32+ nodeType: "function_declaration",
33+ fileName: "file1.go",
34+ language: "Go",
35+ cursorPosition: { line: 7, character: 21 },
36+ definitionPositions: [
37+ { row: 6, column: 33 }, // models.User
38+ { row: 6, column: 50 }, // models.Address
39+ ],
40+ },
41+];
42+
43+describe("RootPathContextService", () => {
44+ describe("should look for correct type definitions", () => {
45+ test.each(TEST_CASES)(
46+ "$language: $nodeType",
47+ async ({ fileName, cursorPosition, definitionPositions }) => {
48+ await testRootPathContext(
49+ "files",
50+ fileName,
51+ cursorPosition,
52+ definitionPositions,
53+ );
54+ },
55+ );
56+ });
57+});
modified core/autocomplete/context/root-path-context/test/testUtils.ts +3 −3
@@ -1,6 +1,6 @@
1-import { jest } from "@jest/globals";
21 import fs from "fs";
32 import path from "path";
3+import { expect, vi } from "vitest";
44
55 import Parser from "web-tree-sitter";
66 import { Position } from "../../../..";
@@ -36,7 +36,7 @@
3636 const importDefinitionsService = new ImportDefinitionsService(ide);
3737 const service = new RootPathContextService(importDefinitionsService, ide);
3838
39- const getSnippetsMock = jest
39+ const getSnippetsMock = vi
4040 // @ts-ignore
4141 .spyOn(service, "getSnippets")
4242 // @ts-ignore
@@ -46,7 +46,7 @@
4646
4747 // Copy the folder to the test directory
4848 const folderPath = path.join(
49- __dirname,
49+ process.cwd(),
5050 "autocomplete",
5151 "context",
5252 "root-path-context",
deleted core/autocomplete/filtering/streamTransforms/charStream.test.ts +0 −215
@@ -1,215 +0,0 @@
1-import { stopAtStartOf, stopAtStopTokens } from "./charStream";
2-
3-async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
4- for (const chunk of chunks) {
5- yield chunk;
6- }
7-}
8-
9-async function streamToString(stream: AsyncGenerator<string>): Promise<string> {
10- let result = "";
11- for await (const chunk of stream) {
12- result += chunk;
13- }
14- return result;
15-}
16-
17-describe("stopAtStopTokens", () => {
18- it("should yield characters until a stop token is encountered", async () => {
19- const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
20- const stopTokens = ["Stop"];
21- const result = stopAtStopTokens(mockStream, stopTokens);
22-
23- const output = [];
24- for await (const char of result) {
25- output.push(char);
26- }
27-
28- expect(output.join("")).toBe("Hello world! ");
29- });
30-
31- it("should handle multiple stop tokens", async () => {
32- const mockStream = createMockStream([
33- "This",
34- " is a ",
35- "test. END",
36- " of stream",
37- ]);
38- const stopTokens = ["END", "STOP", "HALT"];
39- const result = stopAtStopTokens(mockStream, stopTokens);
40-
41- expect(await streamToString(result)).toBe("This is a test. ");
42- });
43-
44- it("should handle stop tokens split across chunks", async () => {
45- const mockStream = createMockStream([
46- "Hello",
47- " wo",
48- "r",
49- "ld! ST",
50- "OP now",
51- ]);
52- const stopTokens = ["STOP"];
53- const result = stopAtStopTokens(mockStream, stopTokens);
54-
55- const output = [];
56- for await (const char of result) {
57- output.push(char);
58- }
59-
60- expect(output.join("")).toBe("Hello world! ");
61- });
62-
63- it("should yield all characters if no stop token is encountered", async () => {
64- const mockStream = createMockStream([
65- "This",
66- " is ",
67- "a complete",
68- " stream",
69- ]);
70- const stopTokens = ["END"];
71- const result = stopAtStopTokens(mockStream, stopTokens);
72-
73- expect(await streamToString(result)).toBe("This is a complete stream");
74- });
75-
76- it("should handle empty chunks", async () => {
77- const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]);
78- const stopTokens = ["STOP"];
79- const result = stopAtStopTokens(mockStream, stopTokens);
80-
81- expect(await streamToString(result)).toBe("Hello world! ");
82- });
83-
84- it("should handle stop token at the beginning of the stream", async () => {
85- const mockStream = createMockStream(["STOP", "Hello world"]);
86- const stopTokens = ["STOP"];
87- const result = stopAtStopTokens(mockStream, stopTokens);
88-
89- const output = [];
90- for await (const char of result) {
91- output.push(char);
92- }
93-
94- expect(output.join("")).toBe("");
95- });
96-
97- it("should handle stop token at the end of the stream", async () => {
98- const mockStream = createMockStream(["Hello world", "STOP"]);
99- const stopTokens = ["STOP"];
100- const result = stopAtStopTokens(mockStream, stopTokens);
101-
102- expect(await streamToString(result)).toBe("Hello world");
103- });
104-
105- it("should handle multiple stop tokens of different lengths", async () => {
106- const mockStream = createMockStream([
107- "This is a ",
108- "test with ",
109- "multiple STOP",
110- " tokens END",
111- ]);
112- const stopTokens = ["STOP", "END", "HALT"];
113- const result = stopAtStopTokens(mockStream, stopTokens);
114-
115- expect(await streamToString(result)).toBe("This is a test with multiple ");
116- });
117-
118- it("should handle an empty stream", async () => {
119- const mockStream = createMockStream([]);
120- const stopTokens = ["STOP"];
121- const result = stopAtStopTokens(mockStream, stopTokens);
122-
123- expect(await streamToString(result)).toBe("");
124- });
125-
126- it("should handle an empty stop tokens array", async () => {
127- const mockStream = createMockStream(["Hello", " world!"]);
128- const stopTokens: string[] = [];
129- const result = stopAtStopTokens(mockStream, stopTokens);
130-
131- const output = [];
132- for await (const char of result) {
133- output.push(char);
134- }
135-
136- expect(output.join("")).toBe("Hello world!");
137- });
138-
139- it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => {
140- const mockStream = createMockStream(["Hello world!STOP"]);
141- const stopTokens: string[] = [
142- "STOP",
143- "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER",
144- ];
145- const result = stopAtStopTokens(mockStream, stopTokens);
146-
147- expect(await streamToString(result)).toBe("Hello world!");
148- });
149-});
150-
151-describe("stopAtStartOf", () => {
152- const sampleCode = ` {
153- method: "GET",
154- headers: {
155- "Content-Type": "application/json",
156- Authorization: \`Bearer \${this.workOsAccessToken}\`,
157- },
158- },
159- );
160- const data = await response.json();
161- return data.items;
162- }
163-
164- async getContextItems(
165- query: string,
166- extras: ContextProviderExtras,
167- ): Promise<ContextItem[]> {
168- const response = await extras.fetch(
169- new URL(
170- \`/proxy/context/\${this.options.id}/retrieve\`,
171- controlPlaneEnv.CONTROL_PLANE_URL,
172- ),
173-`;
174-
175- /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
176-and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
177- it("should stop if the start of the suffix is reached", async () => {
178- const suffix = `
179- const data = await response.json();
180- return data.items;
181-}`;
182- const mockStream = createMockStream(sampleCode.split(/(?! )/g));
183- const result = stopAtStartOf(mockStream, suffix);
184-
185- const resultStr = await streamToString(result);
186- expect(resultStr).toBe(` {
187- method: "GET",
188- headers: {
189- "Content-Type": "application/json",
190- Authorization: \`Bearer \${this.workOsAccessToken}\`,
191- },
192- },
193- );
194- `);
195- });
196- it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
197- const suffix = `
198- xxxconst data = await response.json();
199- return data.items;
200-}`;
201- const mockStream = createMockStream(sampleCode.split(/(?! )/g));
202- const result = stopAtStartOf(mockStream, suffix);
203-
204- const resultStr = await streamToString(result);
205- expect(resultStr).toBe(` {
206- method: "GET",
207- headers: {
208- "Content-Type": "application/json",
209- Authorization: \`Bearer \${this.workOsAccessToken}\`,
210- },
211- },
212- );
213- `);
214- });
215-});
added core/autocomplete/filtering/streamTransforms/charStream.vitest.ts +216 −0
@@ -0,0 +1,216 @@
1+import { describe, expect, it } from "vitest";
2+import { stopAtStartOf, stopAtStopTokens } from "./charStream";
3+
4+async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
5+ for (const chunk of chunks) {
6+ yield chunk;
7+ }
8+}
9+
10+async function streamToString(stream: AsyncGenerator<string>): Promise<string> {
11+ let result = "";
12+ for await (const chunk of stream) {
13+ result += chunk;
14+ }
15+ return result;
16+}
17+
18+describe("stopAtStopTokens", () => {
19+ it("should yield characters until a stop token is encountered", async () => {
20+ const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
21+ const stopTokens = ["Stop"];
22+ const result = stopAtStopTokens(mockStream, stopTokens);
23+
24+ const output = [];
25+ for await (const char of result) {
26+ output.push(char);
27+ }
28+
29+ expect(output.join("")).toBe("Hello world! ");
30+ });
31+
32+ it("should handle multiple stop tokens", async () => {
33+ const mockStream = createMockStream([
34+ "This",
35+ " is a ",
36+ "test. END",
37+ " of stream",
38+ ]);
39+ const stopTokens = ["END", "STOP", "HALT"];
40+ const result = stopAtStopTokens(mockStream, stopTokens);
41+
42+ expect(await streamToString(result)).toBe("This is a test. ");
43+ });
44+
45+ it("should handle stop tokens split across chunks", async () => {
46+ const mockStream = createMockStream([
47+ "Hello",
48+ " wo",
49+ "r",
50+ "ld! ST",
51+ "OP now",
52+ ]);
53+ const stopTokens = ["STOP"];
54+ const result = stopAtStopTokens(mockStream, stopTokens);
55+
56+ const output = [];
57+ for await (const char of result) {
58+ output.push(char);
59+ }
60+
61+ expect(output.join("")).toBe("Hello world! ");
62+ });
63+
64+ it("should yield all characters if no stop token is encountered", async () => {
65+ const mockStream = createMockStream([
66+ "This",
67+ " is ",
68+ "a complete",
69+ " stream",
70+ ]);
71+ const stopTokens = ["END"];
72+ const result = stopAtStopTokens(mockStream, stopTokens);
73+
74+ expect(await streamToString(result)).toBe("This is a complete stream");
75+ });
76+
77+ it("should handle empty chunks", async () => {
78+ const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]);
79+ const stopTokens = ["STOP"];
80+ const result = stopAtStopTokens(mockStream, stopTokens);
81+
82+ expect(await streamToString(result)).toBe("Hello world! ");
83+ });
84+
85+ it("should handle stop token at the beginning of the stream", async () => {
86+ const mockStream = createMockStream(["STOP", "Hello world"]);
87+ const stopTokens = ["STOP"];
88+ const result = stopAtStopTokens(mockStream, stopTokens);
89+
90+ const output = [];
91+ for await (const char of result) {
92+ output.push(char);
93+ }
94+
95+ expect(output.join("")).toBe("");
96+ });
97+
98+ it("should handle stop token at the end of the stream", async () => {
99+ const mockStream = createMockStream(["Hello world", "STOP"]);
100+ const stopTokens = ["STOP"];
101+ const result = stopAtStopTokens(mockStream, stopTokens);
102+
103+ expect(await streamToString(result)).toBe("Hello world");
104+ });
105+
106+ it("should handle multiple stop tokens of different lengths", async () => {
107+ const mockStream = createMockStream([
108+ "This is a ",
109+ "test with ",
110+ "multiple STOP",
111+ " tokens END",
112+ ]);
113+ const stopTokens = ["STOP", "END", "HALT"];
114+ const result = stopAtStopTokens(mockStream, stopTokens);
115+
116+ expect(await streamToString(result)).toBe("This is a test with multiple ");
117+ });
118+
119+ it("should handle an empty stream", async () => {
120+ const mockStream = createMockStream([]);
121+ const stopTokens = ["STOP"];
122+ const result = stopAtStopTokens(mockStream, stopTokens);
123+
124+ expect(await streamToString(result)).toBe("");
125+ });
126+
127+ it("should handle an empty stop tokens array", async () => {
128+ const mockStream = createMockStream(["Hello", " world!"]);
129+ const stopTokens: string[] = [];
130+ const result = stopAtStopTokens(mockStream, stopTokens);
131+
132+ const output = [];
133+ for await (const char of result) {
134+ output.push(char);
135+ }
136+
137+ expect(output.join("")).toBe("Hello world!");
138+ });
139+
140+ it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => {
141+ const mockStream = createMockStream(["Hello world!STOP"]);
142+ const stopTokens: string[] = [
143+ "STOP",
144+ "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER",
145+ ];
146+ const result = stopAtStopTokens(mockStream, stopTokens);
147+
148+ expect(await streamToString(result)).toBe("Hello world!");
149+ });
150+});
151+
152+describe("stopAtStartOf", () => {
153+ const sampleCode = ` {
154+ method: "GET",
155+ headers: {
156+ "Content-Type": "application/json",
157+ Authorization: \`Bearer \${this.workOsAccessToken}\`,
158+ },
159+ },
160+ );
161+ const data = await response.json();
162+ return data.items;
163+ }
164+
165+ async getContextItems(
166+ query: string,
167+ extras: ContextProviderExtras,
168+ ): Promise<ContextItem[]> {
169+ const response = await extras.fetch(
170+ new URL(
171+ \`/proxy/context/\${this.options.id}/retrieve\`,
172+ controlPlaneEnv.CONTROL_PLANE_URL,
173+ ),
174+`;
175+
176+ /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
177+and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
178+ it("should stop if the start of the suffix is reached", async () => {
179+ const suffix = `
180+ const data = await response.json();
181+ return data.items;
182+}`;
183+ const mockStream = createMockStream(sampleCode.split(/(?! )/g));
184+ const result = stopAtStartOf(mockStream, suffix);
185+
186+ const resultStr = await streamToString(result);
187+ expect(resultStr).toBe(` {
188+ method: "GET",
189+ headers: {
190+ "Content-Type": "application/json",
191+ Authorization: \`Bearer \${this.workOsAccessToken}\`,
192+ },
193+ },
194+ );
195+ `);
196+ });
197+ it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
198+ const suffix = `
199+ xxxconst data = await response.json();
200+ return data.items;
201+}`;
202+ const mockStream = createMockStream(sampleCode.split(/(?! )/g));
203+ const result = stopAtStartOf(mockStream, suffix);
204+
205+ const resultStr = await streamToString(result);
206+ expect(resultStr).toBe(` {
207+ method: "GET",
208+ headers: {
209+ "Content-Type": "application/json",
210+ Authorization: \`Bearer \${this.workOsAccessToken}\`,
211+ },
212+ },
213+ );
214+ `);
215+ });
216+});
deleted core/autocomplete/filtering/streamTransforms/lineStream.test.ts +0 −616
@@ -1,616 +0,0 @@
1-import { jest } from "@jest/globals";
2-
3-import * as lineStream from "./lineStream";
4-
5-// eslint-disable-next-line max-lines-per-function
6-describe("lineStream", () => {
7- let mockFullStop: jest.Mock;
8-
9- async function getLineGenerator(lines: any) {
10- return (async function* () {
11- for (const line of lines) {
12- yield line;
13- }
14- })();
15- }
16-
17- async function getFilteredLines(results: any) {
18- const output = [];
19-
20- for await (const line of results) {
21- output.push(line);
22- }
23-
24- return output;
25- }
26-
27- beforeEach(() => {
28- mockFullStop = jest.fn();
29- });
30-
31- describe("noTopLevelKeywordsMidline", () => {
32- it.todo("Need some sample inputs to properly test this");
33- });
34-
35- describe("avoidPathLine", () => {
36- it("should filter out path lines", async () => {
37- const linesGenerator = await getLineGenerator([
38- "// Path: src/index.ts",
39- "const x = 5;",
40- "//",
41- "console.log(x);",
42- ]);
43- const result = lineStream.avoidPathLine(linesGenerator, "//");
44- const filteredLines = await getFilteredLines(result);
45- expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]);
46- });
47- });
48-
49- describe("avoidEmptyComments", () => {
50- it("should filter out empty comments", async () => {
51- const linesGenerator = await getLineGenerator([
52- "// Path: src/index.ts",
53- "const x = 5;",
54- "//",
55- "console.log(x);",
56- ]);
57- const result = lineStream.avoidEmptyComments(linesGenerator, "//");
58- const filteredLines = await getFilteredLines(result);
59- expect(filteredLines).toEqual([
60- "// Path: src/index.ts",
61- "const x = 5;",
62- "console.log(x);",
63- ]);
64- });
65- });
66-
67- describe("streamWithNewLines", () => {
68- it("should add newlines between lines", async () => {
69- const linesGenerator = await getLineGenerator([
70- "line1",
71- "line2",
72- "line3",
73- ]);
74-
75- const result = lineStream.streamWithNewLines(linesGenerator);
76- const filteredLines = await getFilteredLines(result);
77-
78- expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]);
79- });
80- });
81-
82- describe("lineIsRepeated", () => {
83- it("should return true for similar lines", () => {
84- expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe(
85- true,
86- );
87- });
88-
89- it("should return false for different lines", () => {
90- expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe(
91- false,
92- );
93- });
94-
95- it("should return false for short lines", () => {
96- expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false);
97- });
98- });
99-
100- describe("stopAtSimilarLine", () => {
101- it("should stop at the exact same line", async () => {
102- const lineToTest = "const x = 6";
103- const linesGenerator = await getLineGenerator([
104- "console.log();",
105- "const y = () => {};",
106- lineToTest,
107- ]);
108-
109- const result = lineStream.stopAtSimilarLine(
110- linesGenerator,
111- lineToTest,
112- mockFullStop,
113- );
114- const filteredLines = await getFilteredLines(result);
115-
116- expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
117- expect(mockFullStop).toHaveBeenCalledTimes(1);
118- });
119-
120- it("should stop at a similar line", async () => {
121- const lineToTest = "const x = 6;";
122- const linesGenerator = await getLineGenerator([
123- "console.log();",
124- "const y = () => {};",
125- lineToTest,
126- ]);
127-
128- const result = lineStream.stopAtSimilarLine(
129- linesGenerator,
130- "a" + lineToTest,
131- mockFullStop,
132- );
133- const filteredLines = await getFilteredLines(result);
134-
135- expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
136- expect(mockFullStop).toHaveBeenCalledTimes(1);
137- });
138-
139- it("should continue on bracket ending lines", async () => {
140- const linesGenerator = await getLineGenerator([
141- " if (x > 0) {",
142- " console.log(x);",
143- " }",
144- ]);
145-
146- const result = lineStream.stopAtSimilarLine(
147- linesGenerator,
148- "}",
149- mockFullStop,
150- );
151- const filteredLines = await getFilteredLines(result);
152-
153- expect(filteredLines).toEqual([
154- " if (x > 0) {",
155- " console.log(x);",
156- " }",
157- ]);
158- expect(mockFullStop).toHaveBeenCalledTimes(0);
159- });
160- });
161-
162- describe("stopAtLines", () => {
163- it("should stop at specified lines", async () => {
164- const linesGenerator = await getLineGenerator([
165- "const x = 5;",
166- "let y = 10;",
167- lineStream.LINES_TO_STOP_AT[0],
168- "const z = 15;",
169- ]);
170-
171- const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
172- const filteredLines = await getFilteredLines(result);
173-
174- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
175- expect(mockFullStop).toHaveBeenCalledTimes(1);
176- });
177- });
178-
179- describe("skipPrefixes", () => {
180- it("should skip specified prefixes", async () => {
181- const linesGenerator = await getLineGenerator([
182- `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`,
183- "let y = 10;",
184- ]);
185-
186- const result = lineStream.skipPrefixes(linesGenerator);
187- const filteredLines = await getFilteredLines(result);
188-
189- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
190- });
191- });
192-
193- describe("skipLines", () => {
194- it("should skip specified lines", async () => {
195- const linesGenerator = await getLineGenerator([
196- `${lineStream.LINES_TO_SKIP[0]}const x = 5;`,
197- "let y = 10;",
198- ]);
199-
200- const result = lineStream.skipLines(linesGenerator);
201- const filteredLines = await getFilteredLines(result);
202-
203- expect(filteredLines).toEqual(["let y = 10;"]);
204- });
205- });
206-
207- describe("filterCodeBlockLines", () => {
208- it("should handle unfenced code", async () => {
209- const linesGenerator = await getLineGenerator(["const x = 5;"]);
210-
211- const result = lineStream.filterCodeBlockLines(linesGenerator);
212- const filteredLines = await getFilteredLines(result);
213-
214- expect(filteredLines).toEqual(["const x = 5;"]);
215- });
216-
217- it("should handle unfenced code with a code block", async () => {
218- const linesGenerator = await getLineGenerator([
219- "const x = 5;",
220- "```bash",
221- "ls -al",
222- "```",
223- ]);
224-
225- const result = lineStream.filterCodeBlockLines(linesGenerator);
226- const filteredLines = await getFilteredLines(result);
227-
228- expect(filteredLines).toEqual([
229- "const x = 5;",
230- "```bash",
231- "ls -al",
232- "```",
233- ]);
234- });
235-
236- it("should handle unfenced code with two code blocks", async () => {
237- const linesGenerator = await getLineGenerator([
238- "const x = 5;",
239- "```bash",
240- "ls -al",
241- "```",
242- "```bash",
243- "ls -al",
244- "```",
245- ]);
246-
247- const result = lineStream.filterCodeBlockLines(linesGenerator);
248- const filteredLines = await getFilteredLines(result);
249-
250- expect(filteredLines).toEqual([
251- "const x = 5;",
252- "```bash",
253- "ls -al",
254- "```",
255- "```bash",
256- "ls -al",
257- "```",
258- ]);
259- });
260-
261- it("should remove lines before the first valid line", async () => {
262- const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
263-
264- const result = lineStream.filterCodeBlockLines(linesGenerator);
265- const filteredLines = await getFilteredLines(result);
266-
267- expect(filteredLines).toEqual(["const x = 5;"]);
268- });
269-
270- it("should remove outer blocks", async () => {
271- const linesGenerator = await getLineGenerator([
272- "```ts",
273- "const x = 5;",
274- "```",
275- ]);
276-
277- const result = lineStream.filterCodeBlockLines(linesGenerator);
278- const filteredLines = await getFilteredLines(result);
279-
280- expect(filteredLines).toEqual(["const x = 5;"]);
281- });
282-
283- it("should leave inner blocks intact", async () => {
284- const linesGenerator = await getLineGenerator([
285- "```md",
286- "const x = 5;",
287- "```bash",
288- "ls -al",
289- "```",
290- "```",
291- ]);
292-
293- const result = lineStream.filterCodeBlockLines(linesGenerator);
294- const filteredLines = await getFilteredLines(result);
295-
296- expect(filteredLines).toEqual([
297- "const x = 5;",
298- "```bash",
299- "ls -al",
300- "```",
301- ]);
302- });
303-
304- it("should handle included inner ticks", async () => {
305- const linesGenerator = await getLineGenerator([
306- "```md",
307- "const x = 5;",
308- "```bash",
309- "echo ```test```",
310- "```",
311- "```",
312- ]);
313-
314- const result = lineStream.filterCodeBlockLines(linesGenerator);
315- const filteredLines = await getFilteredLines(result);
316-
317- expect(filteredLines).toEqual([
318- "const x = 5;",
319- "```bash",
320- "echo ```test```",
321- "```",
322- ]);
323- });
324-
325- it("should leave single inner blocks intact but not return trailing text", async () => {
326- const linesGenerator = await getLineGenerator([
327- "```md",
328- "const x = 5;",
329- "```bash",
330- "ls -al",
331- "```",
332- "```",
333- "trailing text",
334- ]);
335-
336- const result = lineStream.filterCodeBlockLines(linesGenerator);
337- const filteredLines = await getFilteredLines(result);
338-
339- expect(filteredLines).toEqual([
340- "const x = 5;",
341- "```bash",
342- "ls -al",
343- "```",
344- ]);
345- });
346-
347- it("should leave double inner blocks intact but not return trailing text", async () => {
348- const linesGenerator = await getLineGenerator([
349- "```md",
350- "const x = 5;",
351- "```bash",
352- "ls -al",
353- "```",
354- "const y = 10;",
355- "```sh",
356- "echo `hello world`",
357- "```",
358- "```",
359- "trailing text",
360- ]);
361-
362- const result = lineStream.filterCodeBlockLines(linesGenerator);
363- const filteredLines = await getFilteredLines(result);
364-
365- expect(filteredLines).toEqual([
366- "const x = 5;",
367- "```bash",
368- "ls -al",
369- "```",
370- "const y = 10;",
371- "```sh",
372- "echo `hello world`",
373- "```",
374- ]);
375- });
376-
377- it("should leave inner blocks intact but not return trailing or leading text", async () => {
378- const linesGenerator = await getLineGenerator([
379- "[CODE]",
380- "const x = 5;",
381- "```bash",
382- "ls -al",
383- "```",
384- "[/CODE]",
385- "trailing text",
386- ]);
387-
388- const result = lineStream.filterCodeBlockLines(linesGenerator);
389- const filteredLines = await getFilteredLines(result);
390-
391- expect(filteredLines).toEqual([
392- "const x = 5;",
393- "```bash",
394- "ls -al",
395- "```",
396- ]);
397- });
398- });
399-
400- describe("filterEnglishLinesAtStart", () => {
401- it("should skip initial empty line", async () => {
402- const linesGenerator = await getLineGenerator([
403- "",
404- "const x = 5;",
405- "let y = 10;",
406- ]);
407-
408- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
409- const filteredLines = await getFilteredLines(result);
410-
411- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
412- });
413-
414- it("should filter out English first line", async () => {
415- const linesGenerator = await getLineGenerator([
416- lineStream.ENGLISH_START_PHRASES[0],
417- "let y = 10;",
418- ]);
419-
420- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
421- const filteredLines = await getFilteredLines(result);
422-
423- expect(filteredLines).toEqual(["let y = 10;"]);
424- });
425-
426- it("should not filter out non-English first line", async () => {
427- const linesGenerator = await getLineGenerator([
428- "const x = 5;",
429- "let y = 10;",
430- ]);
431-
432- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
433- const filteredLines = await getFilteredLines(result);
434-
435- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
436- });
437-
438- it("should filter out empty newline after first line english word", async () => {
439- const linesGenerator = await getLineGenerator([
440- lineStream.ENGLISH_START_PHRASES[0],
441- "",
442- "const x = 5;",
443- ]);
444-
445- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
446- const filteredLines = await getFilteredLines(result);
447-
448- expect(filteredLines).toEqual(["const x = 5;"]);
449- });
450-
451- it("should filter out sentences ending in a semi-colon that are not code keywords", async () => {
452- const linesGenerator = await getLineGenerator([
453- "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":",
454- "const x = 5;",
455- ]);
456-
457- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
458- const filteredLines = await getFilteredLines(result);
459-
460- expect(filteredLines).toEqual(["const x = 5;"]);
461- });
462-
463- it("should not filter out sentences ending in a semi-colon that are code keywords", async () => {
464- const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":";
465-
466- const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]);
467-
468- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
469- const filteredLines = await getFilteredLines(result);
470-
471- expect(filteredLines).toEqual([keyword, "const x = 5;"]);
472- });
473- });
474-
475- describe("filterEnglishLinesAtEnd", () => {
476- it("should stop at English explanation after code block", async () => {
477- const linesGenerator = await getLineGenerator([
478- "const x = 5;",
479- "```",
480- lineStream.ENGLISH_POST_PHRASES[0],
481- ]);
482-
483- const result = lineStream.filterEnglishLinesAtEnd(linesGenerator);
484- const filteredLines = await getFilteredLines(result);
485-
486- expect(filteredLines).toEqual(["const x = 5;", "```"]);
487- });
488- });
489-
490- describe("fixCodeLlamaFirstLineIndentation", () => {
491- it("should fix indentation of the first line", async () => {
492- const linesGenerator = await getLineGenerator([
493- " const x = 5;",
494- "let y = 10;",
495- ]);
496-
497- const result =
498- lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator);
499- const filteredLines = await getFilteredLines(result);
500-
501- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
502- });
503- });
504-
505- describe("filterLeadingAndTrailingNewLineInsertion", () => {
506- it("should ignore 'useless' new first lines", async () => {
507- const linesGenerator = await getLineGenerator([
508- { type: "new", line: lineStream.USELESS_LINES[0] },
509- { type: "new", line: "const x = 5;" },
510- ]);
511-
512- const result =
513- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
514- const filteredLines = await getFilteredLines(result);
515-
516- expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]);
517- });
518-
519- it("should handle preserve newlines chars in old lines", async () => {
520- const linesGenerator = await getLineGenerator([
521- { type: "new", line: "const x = 5;" },
522- { type: "old", line: "let y = 10;" },
523- { type: "old", line: "" },
524- { type: "new", line: "const z = 15;" },
525- ]);
526-
527- const result =
528- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
529- const filteredLines = await getFilteredLines(result);
530-
531- expect(filteredLines).toEqual([
532- { type: "new", line: "const x = 5;" },
533- { type: "old", line: "let y = 10;" },
534- { type: "old", line: "" },
535- { type: "new", line: "const z = 15;" },
536- ]);
537- });
538-
539- it("should filter leading and trailing new line insertions", async () => {
540- const linesGenerator = await getLineGenerator([
541- { type: "new", line: "" },
542- { type: "new", line: "const x = 5;" },
543- { type: "new", line: "let y = 10;" },
544- { type: "new", line: "" },
545- ]);
546-
547- const result =
548- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
549- const filteredLines = await getFilteredLines(result);
550-
551- expect(filteredLines).toEqual([
552- { type: "new", line: "const x = 5;" },
553- { type: "new", line: "let y = 10;" },
554- ]);
555- });
556-
557- it("should buffer newline chars and then render them if we encounter another non-empty line", async () => {
558- const linesGenerator = await getLineGenerator([
559- { type: "new", line: "const x = 5;" },
560- { type: "new", line: "" },
561- { type: "new", line: "let y = 10;" },
562- ]);
563-
564- const result =
565- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
566- const filteredLines = await getFilteredLines(result);
567-
568- expect(filteredLines).toEqual([
569- { type: "new", line: "const x = 5;" },
570- { type: "new", line: "" },
571- { type: "new", line: "let y = 10;" },
572- ]);
573- });
574- });
575-
576- describe("stopAtRepeatingLines", () => {
577- it("should handle non-repeating lines correctly", async () => {
578- const linesGenerator = await getLineGenerator([
579- "const x = 5;",
580- "let y = 10;",
581- "const z = 15;",
582- ]);
583-
584- const result = lineStream.stopAtRepeatingLines(
585- linesGenerator,
586- mockFullStop,
587- );
588- const filteredLines = await getFilteredLines(result);
589-
590- expect(filteredLines).toEqual([
591- "const x = 5;",
592- "let y = 10;",
593- "const z = 15;",
594- ]);
595- });
596-
597- it("should stop at repeating lines", async () => {
598- const linesGenerator = await getLineGenerator([
599- "const x = 5;",
600- "let y = 10;",
601- "let y = 10;",
602- "let y = 10;",
603- "const z = 15;",
604- ]);
605-
606- const result = lineStream.stopAtRepeatingLines(
607- linesGenerator,
608- mockFullStop,
609- );
610- const filteredLines = await getFilteredLines(result);
611-
612- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
613- expect(mockFullStop).toHaveBeenCalledTimes(1);
614- });
615- });
616-});
added core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +616 −0
@@ -0,0 +1,616 @@
1+import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
2+
3+import * as lineStream from "./lineStream";
4+
5+// eslint-disable-next-line max-lines-per-function
6+describe("lineStream", () => {
7+ let mockFullStop: Mock;
8+
9+ async function getLineGenerator(lines: any) {
10+ return (async function* () {
11+ for (const line of lines) {
12+ yield line;
13+ }
14+ })();
15+ }
16+
17+ async function getFilteredLines(results: any) {
18+ const output = [];
19+
20+ for await (const line of results) {
21+ output.push(line);
22+ }
23+
24+ return output;
25+ }
26+
27+ beforeEach(() => {
28+ mockFullStop = vi.fn();
29+ });
30+
31+ describe("noTopLevelKeywordsMidline", () => {
32+ it.todo("Need some sample inputs to properly test this");
33+ });
34+
35+ describe("avoidPathLine", () => {
36+ it("should filter out path lines", async () => {
37+ const linesGenerator = await getLineGenerator([
38+ "// Path: src/index.ts",
39+ "const x = 5;",
40+ "//",
41+ "console.log(x);",
42+ ]);
43+ const result = lineStream.avoidPathLine(linesGenerator, "//");
44+ const filteredLines = await getFilteredLines(result);
45+ expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]);
46+ });
47+ });
48+
49+ describe("avoidEmptyComments", () => {
50+ it("should filter out empty comments", async () => {
51+ const linesGenerator = await getLineGenerator([
52+ "// Path: src/index.ts",
53+ "const x = 5;",
54+ "//",
55+ "console.log(x);",
56+ ]);
57+ const result = lineStream.avoidEmptyComments(linesGenerator, "//");
58+ const filteredLines = await getFilteredLines(result);
59+ expect(filteredLines).toEqual([
60+ "// Path: src/index.ts",
61+ "const x = 5;",
62+ "console.log(x);",
63+ ]);
64+ });
65+ });
66+
67+ describe("streamWithNewLines", () => {
68+ it("should add newlines between lines", async () => {
69+ const linesGenerator = await getLineGenerator([
70+ "line1",
71+ "line2",
72+ "line3",
73+ ]);
74+
75+ const result = lineStream.streamWithNewLines(linesGenerator);
76+ const filteredLines = await getFilteredLines(result);
77+
78+ expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]);
79+ });
80+ });
81+
82+ describe("lineIsRepeated", () => {
83+ it("should return true for similar lines", () => {
84+ expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe(
85+ true,
86+ );
87+ });
88+
89+ it("should return false for different lines", () => {
90+ expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe(
91+ false,
92+ );
93+ });
94+
95+ it("should return false for short lines", () => {
96+ expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false);
97+ });
98+ });
99+
100+ describe("stopAtSimilarLine", () => {
101+ it("should stop at the exact same line", async () => {
102+ const lineToTest = "const x = 6";
103+ const linesGenerator = await getLineGenerator([
104+ "console.log();",
105+ "const y = () => {};",
106+ lineToTest,
107+ ]);
108+
109+ const result = lineStream.stopAtSimilarLine(
110+ linesGenerator,
111+ lineToTest,
112+ mockFullStop,
113+ );
114+ const filteredLines = await getFilteredLines(result);
115+
116+ expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
117+ expect(mockFullStop).toHaveBeenCalledTimes(1);
118+ });
119+
120+ it("should stop at a similar line", async () => {
121+ const lineToTest = "const x = 6;";
122+ const linesGenerator = await getLineGenerator([
123+ "console.log();",
124+ "const y = () => {};",
125+ lineToTest,
126+ ]);
127+
128+ const result = lineStream.stopAtSimilarLine(
129+ linesGenerator,
130+ "a" + lineToTest,
131+ mockFullStop,
132+ );
133+ const filteredLines = await getFilteredLines(result);
134+
135+ expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
136+ expect(mockFullStop).toHaveBeenCalledTimes(1);
137+ });
138+
139+ it("should continue on bracket ending lines", async () => {
140+ const linesGenerator = await getLineGenerator([
141+ " if (x > 0) {",
142+ " console.log(x);",
143+ " }",
144+ ]);
145+
146+ const result = lineStream.stopAtSimilarLine(
147+ linesGenerator,
148+ "}",
149+ mockFullStop,
150+ );
151+ const filteredLines = await getFilteredLines(result);
152+
153+ expect(filteredLines).toEqual([
154+ " if (x > 0) {",
155+ " console.log(x);",
156+ " }",
157+ ]);
158+ expect(mockFullStop).toHaveBeenCalledTimes(0);
159+ });
160+ });
161+
162+ describe("stopAtLines", () => {
163+ it("should stop at specified lines", async () => {
164+ const linesGenerator = await getLineGenerator([
165+ "const x = 5;",
166+ "let y = 10;",
167+ lineStream.LINES_TO_STOP_AT[0],
168+ "const z = 15;",
169+ ]);
170+
171+ const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
172+ const filteredLines = await getFilteredLines(result);
173+
174+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
175+ expect(mockFullStop).toHaveBeenCalledTimes(1);
176+ });
177+ });
178+
179+ describe("skipPrefixes", () => {
180+ it("should skip specified prefixes", async () => {
181+ const linesGenerator = await getLineGenerator([
182+ `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`,
183+ "let y = 10;",
184+ ]);
185+
186+ const result = lineStream.skipPrefixes(linesGenerator);
187+ const filteredLines = await getFilteredLines(result);
188+
189+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
190+ });
191+ });
192+
193+ describe("skipLines", () => {
194+ it("should skip specified lines", async () => {
195+ const linesGenerator = await getLineGenerator([
196+ `${lineStream.LINES_TO_SKIP[0]}const x = 5;`,
197+ "let y = 10;",
198+ ]);
199+
200+ const result = lineStream.skipLines(linesGenerator);
201+ const filteredLines = await getFilteredLines(result);
202+
203+ expect(filteredLines).toEqual(["let y = 10;"]);
204+ });
205+ });
206+
207+ describe("filterCodeBlockLines", () => {
208+ it("should handle unfenced code", async () => {
209+ const linesGenerator = await getLineGenerator(["const x = 5;"]);
210+
211+ const result = lineStream.filterCodeBlockLines(linesGenerator);
212+ const filteredLines = await getFilteredLines(result);
213+
214+ expect(filteredLines).toEqual(["const x = 5;"]);
215+ });
216+
217+ it("should handle unfenced code with a code block", async () => {
218+ const linesGenerator = await getLineGenerator([
219+ "const x = 5;",
220+ "```bash",
221+ "ls -al",
222+ "```",
223+ ]);
224+
225+ const result = lineStream.filterCodeBlockLines(linesGenerator);
226+ const filteredLines = await getFilteredLines(result);
227+
228+ expect(filteredLines).toEqual([
229+ "const x = 5;",
230+ "```bash",
231+ "ls -al",
232+ "```",
233+ ]);
234+ });
235+
236+ it("should handle unfenced code with two code blocks", async () => {
237+ const linesGenerator = await getLineGenerator([
238+ "const x = 5;",
239+ "```bash",
240+ "ls -al",
241+ "```",
242+ "```bash",
243+ "ls -al",
244+ "```",
245+ ]);
246+
247+ const result = lineStream.filterCodeBlockLines(linesGenerator);
248+ const filteredLines = await getFilteredLines(result);
249+
250+ expect(filteredLines).toEqual([
251+ "const x = 5;",
252+ "```bash",
253+ "ls -al",
254+ "```",
255+ "```bash",
256+ "ls -al",
257+ "```",
258+ ]);
259+ });
260+
261+ it("should remove lines before the first valid line", async () => {
262+ const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
263+
264+ const result = lineStream.filterCodeBlockLines(linesGenerator);
265+ const filteredLines = await getFilteredLines(result);
266+
267+ expect(filteredLines).toEqual(["const x = 5;"]);
268+ });
269+
270+ it("should remove outer blocks", async () => {
271+ const linesGenerator = await getLineGenerator([
272+ "```ts",
273+ "const x = 5;",
274+ "```",
275+ ]);
276+
277+ const result = lineStream.filterCodeBlockLines(linesGenerator);
278+ const filteredLines = await getFilteredLines(result);
279+
280+ expect(filteredLines).toEqual(["const x = 5;"]);
281+ });
282+
283+ it("should leave inner blocks intact", async () => {
284+ const linesGenerator = await getLineGenerator([
285+ "```md",
286+ "const x = 5;",
287+ "```bash",
288+ "ls -al",
289+ "```",
290+ "```",
291+ ]);
292+
293+ const result = lineStream.filterCodeBlockLines(linesGenerator);
294+ const filteredLines = await getFilteredLines(result);
295+
296+ expect(filteredLines).toEqual([
297+ "const x = 5;",
298+ "```bash",
299+ "ls -al",
300+ "```",
301+ ]);
302+ });
303+
304+ it("should handle included inner ticks", async () => {
305+ const linesGenerator = await getLineGenerator([
306+ "```md",
307+ "const x = 5;",
308+ "```bash",
309+ "echo ```test```",
310+ "```",
311+ "```",
312+ ]);
313+
314+ const result = lineStream.filterCodeBlockLines(linesGenerator);
315+ const filteredLines = await getFilteredLines(result);
316+
317+ expect(filteredLines).toEqual([
318+ "const x = 5;",
319+ "```bash",
320+ "echo ```test```",
321+ "```",
322+ ]);
323+ });
324+
325+ it("should leave single inner blocks intact but not return trailing text", async () => {
326+ const linesGenerator = await getLineGenerator([
327+ "```md",
328+ "const x = 5;",
329+ "```bash",
330+ "ls -al",
331+ "```",
332+ "```",
333+ "trailing text",
334+ ]);
335+
336+ const result = lineStream.filterCodeBlockLines(linesGenerator);
337+ const filteredLines = await getFilteredLines(result);
338+
339+ expect(filteredLines).toEqual([
340+ "const x = 5;",
341+ "```bash",
342+ "ls -al",
343+ "```",
344+ ]);
345+ });
346+
347+ it("should leave double inner blocks intact but not return trailing text", async () => {
348+ const linesGenerator = await getLineGenerator([
349+ "```md",
350+ "const x = 5;",
351+ "```bash",
352+ "ls -al",
353+ "```",
354+ "const y = 10;",
355+ "```sh",
356+ "echo `hello world`",
357+ "```",
358+ "```",
359+ "trailing text",
360+ ]);
361+
362+ const result = lineStream.filterCodeBlockLines(linesGenerator);
363+ const filteredLines = await getFilteredLines(result);
364+
365+ expect(filteredLines).toEqual([
366+ "const x = 5;",
367+ "```bash",
368+ "ls -al",
369+ "```",
370+ "const y = 10;",
371+ "```sh",
372+ "echo `hello world`",
373+ "```",
374+ ]);
375+ });
376+
377+ it("should leave inner blocks intact but not return trailing or leading text", async () => {
378+ const linesGenerator = await getLineGenerator([
379+ "[CODE]",
380+ "const x = 5;",
381+ "```bash",
382+ "ls -al",
383+ "```",
384+ "[/CODE]",
385+ "trailing text",
386+ ]);
387+
388+ const result = lineStream.filterCodeBlockLines(linesGenerator);
389+ const filteredLines = await getFilteredLines(result);
390+
391+ expect(filteredLines).toEqual([
392+ "const x = 5;",
393+ "```bash",
394+ "ls -al",
395+ "```",
396+ ]);
397+ });
398+ });
399+
400+ describe("filterEnglishLinesAtStart", () => {
401+ it("should skip initial empty line", async () => {
402+ const linesGenerator = await getLineGenerator([
403+ "",
404+ "const x = 5;",
405+ "let y = 10;",
406+ ]);
407+
408+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
409+ const filteredLines = await getFilteredLines(result);
410+
411+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
412+ });
413+
414+ it("should filter out English first line", async () => {
415+ const linesGenerator = await getLineGenerator([
416+ lineStream.ENGLISH_START_PHRASES[0],
417+ "let y = 10;",
418+ ]);
419+
420+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
421+ const filteredLines = await getFilteredLines(result);
422+
423+ expect(filteredLines).toEqual(["let y = 10;"]);
424+ });
425+
426+ it("should not filter out non-English first line", async () => {
427+ const linesGenerator = await getLineGenerator([
428+ "const x = 5;",
429+ "let y = 10;",
430+ ]);
431+
432+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
433+ const filteredLines = await getFilteredLines(result);
434+
435+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
436+ });
437+
438+ it("should filter out empty newline after first line english word", async () => {
439+ const linesGenerator = await getLineGenerator([
440+ lineStream.ENGLISH_START_PHRASES[0],
441+ "",
442+ "const x = 5;",
443+ ]);
444+
445+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
446+ const filteredLines = await getFilteredLines(result);
447+
448+ expect(filteredLines).toEqual(["const x = 5;"]);
449+ });
450+
451+ it("should filter out sentences ending in a semi-colon that are not code keywords", async () => {
452+ const linesGenerator = await getLineGenerator([
453+ "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":",
454+ "const x = 5;",
455+ ]);
456+
457+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
458+ const filteredLines = await getFilteredLines(result);
459+
460+ expect(filteredLines).toEqual(["const x = 5;"]);
461+ });
462+
463+ it("should not filter out sentences ending in a semi-colon that are code keywords", async () => {
464+ const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":";
465+
466+ const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]);
467+
468+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
469+ const filteredLines = await getFilteredLines(result);
470+
471+ expect(filteredLines).toEqual([keyword, "const x = 5;"]);
472+ });
473+ });
474+
475+ describe("filterEnglishLinesAtEnd", () => {
476+ it("should stop at English explanation after code block", async () => {
477+ const linesGenerator = await getLineGenerator([
478+ "const x = 5;",
479+ "```",
480+ lineStream.ENGLISH_POST_PHRASES[0],
481+ ]);
482+
483+ const result = lineStream.filterEnglishLinesAtEnd(linesGenerator);
484+ const filteredLines = await getFilteredLines(result);
485+
486+ expect(filteredLines).toEqual(["const x = 5;", "```"]);
487+ });
488+ });
489+
490+ describe("fixCodeLlamaFirstLineIndentation", () => {
491+ it("should fix indentation of the first line", async () => {
492+ const linesGenerator = await getLineGenerator([
493+ " const x = 5;",
494+ "let y = 10;",
495+ ]);
496+
497+ const result =
498+ lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator);
499+ const filteredLines = await getFilteredLines(result);
500+
501+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
502+ });
503+ });
504+
505+ describe("filterLeadingAndTrailingNewLineInsertion", () => {
506+ it("should ignore 'useless' new first lines", async () => {
507+ const linesGenerator = await getLineGenerator([
508+ { type: "new", line: lineStream.USELESS_LINES[0] },
509+ { type: "new", line: "const x = 5;" },
510+ ]);
511+
512+ const result =
513+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
514+ const filteredLines = await getFilteredLines(result);
515+
516+ expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]);
517+ });
518+
519+ it("should handle preserve newlines chars in old lines", async () => {
520+ const linesGenerator = await getLineGenerator([
521+ { type: "new", line: "const x = 5;" },
522+ { type: "old", line: "let y = 10;" },
523+ { type: "old", line: "" },
524+ { type: "new", line: "const z = 15;" },
525+ ]);
526+
527+ const result =
528+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
529+ const filteredLines = await getFilteredLines(result);
530+
531+ expect(filteredLines).toEqual([
532+ { type: "new", line: "const x = 5;" },
533+ { type: "old", line: "let y = 10;" },
534+ { type: "old", line: "" },
535+ { type: "new", line: "const z = 15;" },
536+ ]);
537+ });
538+
539+ it("should filter leading and trailing new line insertions", async () => {
540+ const linesGenerator = await getLineGenerator([
541+ { type: "new", line: "" },
542+ { type: "new", line: "const x = 5;" },
543+ { type: "new", line: "let y = 10;" },
544+ { type: "new", line: "" },
545+ ]);
546+
547+ const result =
548+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
549+ const filteredLines = await getFilteredLines(result);
550+
551+ expect(filteredLines).toEqual([
552+ { type: "new", line: "const x = 5;" },
553+ { type: "new", line: "let y = 10;" },
554+ ]);
555+ });
556+
557+ it("should buffer newline chars and then render them if we encounter another non-empty line", async () => {
558+ const linesGenerator = await getLineGenerator([
559+ { type: "new", line: "const x = 5;" },
560+ { type: "new", line: "" },
561+ { type: "new", line: "let y = 10;" },
562+ ]);
563+
564+ const result =
565+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
566+ const filteredLines = await getFilteredLines(result);
567+
568+ expect(filteredLines).toEqual([
569+ { type: "new", line: "const x = 5;" },
570+ { type: "new", line: "" },
571+ { type: "new", line: "let y = 10;" },
572+ ]);
573+ });
574+ });
575+
576+ describe("stopAtRepeatingLines", () => {
577+ it("should handle non-repeating lines correctly", async () => {
578+ const linesGenerator = await getLineGenerator([
579+ "const x = 5;",
580+ "let y = 10;",
581+ "const z = 15;",
582+ ]);
583+
584+ const result = lineStream.stopAtRepeatingLines(
585+ linesGenerator,
586+ mockFullStop,
587+ );
588+ const filteredLines = await getFilteredLines(result);
589+
590+ expect(filteredLines).toEqual([
591+ "const x = 5;",
592+ "let y = 10;",
593+ "const z = 15;",
594+ ]);
595+ });
596+
597+ it("should stop at repeating lines", async () => {
598+ const linesGenerator = await getLineGenerator([
599+ "const x = 5;",
600+ "let y = 10;",
601+ "let y = 10;",
602+ "let y = 10;",
603+ "const z = 15;",
604+ ]);
605+
606+ const result = lineStream.stopAtRepeatingLines(
607+ linesGenerator,
608+ mockFullStop,
609+ );
610+ const filteredLines = await getFilteredLines(result);
611+
612+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
613+ expect(mockFullStop).toHaveBeenCalledTimes(1);
614+ });
615+ });
616+});
deleted core/autocomplete/filtering/test/filter.test.ts +0 −48
@@ -1,48 +0,0 @@
1-import { setUpTestDir, tearDownTestDir } from "../../../test/testDir";
2-
3-import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
4-import {
5- AutocompleteFileringTestInput,
6- testAutocompleteFiltering,
7-} from "./util";
8-
9-const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
10- if (tests.some((test) => test.options?.only)) {
11- return tests.filter((test) => test.options?.only);
12- }
13-
14- return tests;
15-};
16-
17-describe("Autocomplete filtering tests", () => {
18- beforeAll(async () => {
19- tearDownTestDir();
20- setUpTestDir();
21- });
22-
23- afterAll(async () => {
24- tearDownTestDir();
25- });
26-
27- beforeEach(async () => {
28- await new Promise((resolve) => setTimeout(resolve, 50));
29- });
30-
31- describe("Should return unmodified LLM output", () => {
32- it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
33- "$description",
34- async (testCase) => {
35- await testAutocompleteFiltering(testCase);
36- },
37- );
38- });
39-
40- describe("Should return modified LLM output", () => {
41- it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
42- "$description",
43- async (testCase) => {
44- await testAutocompleteFiltering(testCase);
45- },
46- );
47- });
48-});
added core/autocomplete/filtering/test/filter.vitest.ts +54 −0
@@ -0,0 +1,54 @@
1+import { afterAll, beforeAll, beforeEach, describe, it } from "vitest";
2+import {
3+ addToTestDir,
4+ setUpTestDir,
5+ tearDownTestDir,
6+} from "../../../test/testDir";
7+
8+import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
9+import {
10+ AutocompleteFileringTestInput,
11+ testAutocompleteFiltering,
12+} from "./util";
13+
14+const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
15+ if (tests.some((test) => test.options?.only)) {
16+ return tests.filter((test) => test.options?.only);
17+ }
18+
19+ return tests;
20+};
21+
22+describe("Autocomplete filtering tests", () => {
23+ beforeAll(async () => {
24+ tearDownTestDir();
25+ setUpTestDir();
26+ addToTestDir([".continueignore"]);
27+ });
28+
29+ afterAll(async () => {
30+ tearDownTestDir();
31+ });
32+
33+ beforeEach(async () => {
34+ await new Promise((resolve) => setTimeout(resolve, 50));
35+ });
36+
37+ describe("Should return unmodified LLM output", () => {
38+ it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
39+ "$description",
40+ async (testCase) => {
41+ await testAutocompleteFiltering(testCase);
42+ },
43+ );
44+ });
45+
46+ describe("Should return modified LLM output", () => {
47+ it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
48+ "$description",
49+ async (testCase) => {
50+ await testAutocompleteFiltering(testCase);
51+ },
52+ );
53+ });
54+});
modified core/autocomplete/filtering/test/util.ts +1 −0
@@ -1,3 +1,4 @@
1+import { expect } from "vitest";
12 import MockLLM from "../../../llm/llms/Mock";
23 import { testConfigHandler, testIde } from "../../../test/fixtures";
34 import { joinPathsToUri } from "../../../util/uri";
deleted core/autocomplete/generation/GeneratorReuseManager.test.ts +0 −215
@@ -1,215 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { GeneratorReuseManager } from "./GeneratorReuseManager";
3-
4-function createMockGenerator(
5- data: string[],
6- delay: number = 0,
7-): (abortSignal: AbortSignal) => AsyncGenerator<string> {
8- const mockGenerator = async function* () {
9- for (const chunk of data) {
10- yield chunk;
11-
12- if (delay > 0) {
13- await new Promise((resolve) => setTimeout(resolve, delay));
14- }
15- }
16- };
17- const newGenerator = jest
18- .fn<() => AsyncGenerator<string>>()
19- .mockReturnValue(mockGenerator());
20-
21- return newGenerator;
22-}
23-
24-describe("GeneratorReuseManager", () => {
25- let reuseManager: GeneratorReuseManager;
26- let onErrorMock: jest.Mock;
27-
28- beforeEach(() => {
29- onErrorMock = jest.fn();
30- reuseManager = new GeneratorReuseManager(onErrorMock);
31- });
32-
33- afterEach(() => {
34- jest.clearAllMocks();
35- });
36-
37- test("creates new generator when there is no current generator", async () => {
38- const data = ["hello ", "world"];
39- const newGenerator = createMockGenerator(data);
40-
41- const prefix = "";
42-
43- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
44-
45- const output: string[] = [];
46- for await (const chunk of generator) {
47- output.push(chunk);
48- }
49-
50- expect(output).toEqual(data);
51- expect(newGenerator).toHaveBeenCalledTimes(1);
52- });
53-
54- test("reuses generator when prefix matches pending completion", async () => {
55- const newGenerator = createMockGenerator(["llo ", "world"]);
56-
57- // First call with initial prefix
58- const prefix1 = "he";
59- const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
60-
61- const output1: string[] = [];
62- for await (const chunk of generator1) {
63- output1.push(chunk);
64- }
65-
66- expect(output1).toEqual(["llo ", "world"]);
67-
68- // Second call with extended prefix that matches pending completion
69- const prefix2 = "hello ";
70- const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
71-
72- const output2: string[] = [];
73- for await (const chunk of generator2) {
74- output2.push(chunk);
75- }
76-
77- expect(output2).toEqual(["world"]);
78-
79- // Ensure generator was reused (newGenerator should be called only once)
80- expect(newGenerator).toHaveBeenCalledTimes(1);
81- });
82-
83- test("creates new generator when prefix does not match pending completion", async () => {
84- const data = ["goodbye ", "world"];
85- const newGenerator = createMockGenerator(data);
86-
87- // Initial generator with different prefix
88- reuseManager.pendingGeneratorPrefix = "hello ";
89- reuseManager.pendingCompletion = "world";
90-
91- const prefix = "good";
92- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
93-
94- const output: string[] = [];
95- for await (const chunk of generator) {
96- output.push(chunk);
97- }
98-
99- expect(output).toEqual(data);
100- // Ensure a new generator was created
101- expect(newGenerator).toHaveBeenCalledTimes(1);
102- });
103-
104- test("handles multiline=false by stopping at newline", async () => {
105- const data = ["first line\n", "second line"];
106- const newGenerator = createMockGenerator(data);
107-
108- const prefix = "";
109- const generator = reuseManager.getGenerator(prefix, newGenerator, false);
110-
111- const output: string[] = [];
112- for await (const chunk of generator) {
113- output.push(chunk);
114- }
115-
116- expect(output).toEqual(["first line"]);
117- // Ensure it stops after the first newline
118- });
119-
120- test("handles multiline=true by not stopping at newline", async () => {
121- const data = ["first line\n", "second line"];
122- const newGenerator = createMockGenerator(data);
123-
124- const prefix = "";
125- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
126-
127- const output: string[] = [];
128- for await (const chunk of generator) {
129- output.push(chunk);
130- }
131-
132- expect(output).toEqual(data);
133- });
134-
135- test("cancels previous generator when creating a new one", async () => {
136- const data1 = ["data from generator 1", "not generated"];
137- const data2 = ["data from generator 2"];
138-
139- const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
140- const newGenerator2 = createMockGenerator(data2);
141-
142- const prefix1 = "prefix1";
143- const prefix2 = "prefix2";
144-
145- // First generator
146- const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
147- const output1: string[] = [];
148- for await (const chunk of generator1) {
149- output1.push(chunk);
150- // Simulate the generator being canceled before completing
151- reuseManager.currentGenerator?.cancel();
152- }
153-
154- expect(output1.length).toEqual(1);
155- expect(output1[0]).toEqual(data1[0]);
156-
157- // Second generator
158- const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
159- const output2: string[] = [];
160- for await (const chunk of generator2) {
161- output2.push(chunk);
162- }
163-
164- expect(output2).toEqual(data2);
165- });
166-
167- test("calls onError when generator throws an error", async () => {
168- const error = new Error("Generator error");
169- const mockGenerator = async function* () {
170- throw error;
171- };
172- const newGenerator = jest
173- .fn<() => AsyncGenerator<string>>()
174- .mockReturnValue(mockGenerator());
175-
176- const prefix = "";
177- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
178-
179- const output: string[] = [];
180- await expect(async () => {
181- for await (const chunk of generator) {
182- output.push(chunk);
183- }
184- }).not.toThrow(); // getGenerator handles errors internally
185-
186- expect(onErrorMock).toHaveBeenCalledWith(error);
187- expect(output).toEqual([]);
188- });
189-
190- test("handles backspacing by creating new generator when prefix is shorter", async () => {
191- const data = ["hello world"];
192- const newGenerator1 = createMockGenerator(data);
193- const newGenerator2 = createMockGenerator(data);
194-
195- // First prefix
196- const prefix1 = "hello world";
197- const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
198- const output1: string[] = [];
199- for await (const chunk of generator1) {
200- output1.push(chunk);
201- }
202-
203- // Simulate backspace (prefix is shorter)
204- const prefix2 = "hello worl";
205- const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
206- const output2: string[] = [];
207- for await (const chunk of generator2) {
208- output2.push(chunk);
209- }
210-
211- // Ensure a new generator was created
212- expect(newGenerator1).toHaveBeenCalledTimes(1);
213- expect(newGenerator2).toHaveBeenCalledTimes(1);
214- });
215-});
added core/autocomplete/generation/GeneratorReuseManager.vitest.ts +223 −0
@@ -0,0 +1,223 @@
1+import {
2+ afterEach,
3+ beforeEach,
4+ describe,
5+ expect,
6+ Mock,
7+ test,
8+ vi,
9+} from "vitest";
10+import { GeneratorReuseManager } from "./GeneratorReuseManager";
11+
12+function createMockGenerator(
13+ data: string[],
14+ delay: number = 0,
15+): (abortSignal: AbortSignal) => AsyncGenerator<string> {
16+ const mockGenerator = async function* () {
17+ for (const chunk of data) {
18+ yield chunk;
19+
20+ if (delay > 0) {
21+ await new Promise((resolve) => setTimeout(resolve, delay));
22+ }
23+ }
24+ };
25+ const newGenerator = vi
26+ .fn<() => AsyncGenerator<string>>()
27+ .mockReturnValue(mockGenerator());
28+
29+ return newGenerator;
30+}
31+
32+describe("GeneratorReuseManager", () => {
33+ let reuseManager: GeneratorReuseManager;
34+ let onErrorMock: Mock;
35+
36+ beforeEach(() => {
37+ onErrorMock = vi.fn();
38+ reuseManager = new GeneratorReuseManager(onErrorMock);
39+ });
40+
41+ afterEach(() => {
42+ vi.clearAllMocks();
43+ });
44+
45+ test("creates new generator when there is no current generator", async () => {
46+ const data = ["hello ", "world"];
47+ const newGenerator = createMockGenerator(data);
48+
49+ const prefix = "";
50+
51+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
52+
53+ const output: string[] = [];
54+ for await (const chunk of generator) {
55+ output.push(chunk);
56+ }
57+
58+ expect(output).toEqual(data);
59+ expect(newGenerator).toHaveBeenCalledTimes(1);
60+ });
61+
62+ test("reuses generator when prefix matches pending completion", async () => {
63+ const newGenerator = createMockGenerator(["llo ", "world"]);
64+
65+ // First call with initial prefix
66+ const prefix1 = "he";
67+ const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
68+
69+ const output1: string[] = [];
70+ for await (const chunk of generator1) {
71+ output1.push(chunk);
72+ }
73+
74+ expect(output1).toEqual(["llo ", "world"]);
75+
76+ // Second call with extended prefix that matches pending completion
77+ const prefix2 = "hello ";
78+ const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
79+
80+ const output2: string[] = [];
81+ for await (const chunk of generator2) {
82+ output2.push(chunk);
83+ }
84+
85+ expect(output2).toEqual(["world"]);
86+
87+ // Ensure generator was reused (newGenerator should be called only once)
88+ expect(newGenerator).toHaveBeenCalledTimes(1);
89+ });
90+
91+ test("creates new generator when prefix does not match pending completion", async () => {
92+ const data = ["goodbye ", "world"];
93+ const newGenerator = createMockGenerator(data);
94+
95+ // Initial generator with different prefix
96+ reuseManager.pendingGeneratorPrefix = "hello ";
97+ reuseManager.pendingCompletion = "world";
98+
99+ const prefix = "good";
100+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
101+
102+ const output: string[] = [];
103+ for await (const chunk of generator) {
104+ output.push(chunk);
105+ }
106+
107+ expect(output).toEqual(data);
108+ // Ensure a new generator was created
109+ expect(newGenerator).toHaveBeenCalledTimes(1);
110+ });
111+
112+ test("handles multiline=false by stopping at newline", async () => {
113+ const data = ["first line\n", "second line"];
114+ const newGenerator = createMockGenerator(data);
115+
116+ const prefix = "";
117+ const generator = reuseManager.getGenerator(prefix, newGenerator, false);
118+
119+ const output: string[] = [];
120+ for await (const chunk of generator) {
121+ output.push(chunk);
122+ }
123+
124+ expect(output).toEqual(["first line"]);
125+ // Ensure it stops after the first newline
126+ });
127+
128+ test("handles multiline=true by not stopping at newline", async () => {
129+ const data = ["first line\n", "second line"];
130+ const newGenerator = createMockGenerator(data);
131+
132+ const prefix = "";
133+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
134+
135+ const output: string[] = [];
136+ for await (const chunk of generator) {
137+ output.push(chunk);
138+ }
139+
140+ expect(output).toEqual(data);
141+ });
142+
143+ test("cancels previous generator when creating a new one", async () => {
144+ const data1 = ["data from generator 1", "not generated"];
145+ const data2 = ["data from generator 2"];
146+
147+ const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
148+ const newGenerator2 = createMockGenerator(data2);
149+
150+ const prefix1 = "prefix1";
151+ const prefix2 = "prefix2";
152+
153+ // First generator
154+ const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
155+ const output1: string[] = [];
156+ for await (const chunk of generator1) {
157+ output1.push(chunk);
158+ // Simulate the generator being canceled before completing
159+ reuseManager.currentGenerator?.cancel();
160+ }
161+
162+ expect(output1.length).toEqual(1);
163+ expect(output1[0]).toEqual(data1[0]);
164+
165+ // Second generator
166+ const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
167+ const output2: string[] = [];
168+ for await (const chunk of generator2) {
169+ output2.push(chunk);
170+ }
171+
172+ expect(output2).toEqual(data2);
173+ });
174+
175+ test("calls onError when generator throws an error", async () => {
176+ const error = new Error("Generator error");
177+ const mockGenerator = async function* () {
178+ throw error;
179+ };
180+ const newGenerator = vi
181+ .fn<() => AsyncGenerator<string>>()
182+ .mockReturnValue(mockGenerator());
183+
184+ const prefix = "";
185+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
186+
187+ const output: string[] = [];
188+ await expect(async () => {
189+ for await (const chunk of generator) {
190+ output.push(chunk);
191+ }
192+ }).not.toThrow(); // getGenerator handles errors internally
193+
194+ expect(onErrorMock).toHaveBeenCalledWith(error);
195+ expect(output).toEqual([]);
196+ });
197+
198+ test("handles backspacing by creating new generator when prefix is shorter", async () => {
199+ const data = ["hello world"];
200+ const newGenerator1 = createMockGenerator(data);
201+ const newGenerator2 = createMockGenerator(data);
202+
203+ // First prefix
204+ const prefix1 = "hello world";
205+ const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
206+ const output1: string[] = [];
207+ for await (const chunk of generator1) {
208+ output1.push(chunk);
209+ }
210+
211+ // Simulate backspace (prefix is shorter)
212+ const prefix2 = "hello worl";
213+ const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
214+ const output2: string[] = [];
215+ for await (const chunk of generator2) {
216+ output2.push(chunk);
217+ }
218+
219+ // Ensure a new generator was created
220+ expect(newGenerator1).toHaveBeenCalledTimes(1);
221+ expect(newGenerator2).toHaveBeenCalledTimes(1);
222+ });
223+});
deleted core/autocomplete/generation/ListenableGenerator.test.ts +0 −174
@@ -1,174 +0,0 @@
1-import { jest } from "@jest/globals";
2-
3-import { ListenableGenerator } from "./ListenableGenerator";
4-
5-describe("ListenableGenerator", () => {
6- // Helper function to create an async generator
7- async function* asyncGenerator<T>(values: T[], delay = 0) {
8- for (const value of values) {
9- if (delay > 0) {
10- await new Promise((resolve) => setTimeout(resolve, delay));
11- }
12- yield value;
13- }
14- }
15-
16- it("should yield values from the source generator via tee()", async () => {
17- const values = [1, 2, 3];
18- const source = asyncGenerator(values);
19- const onError = jest.fn();
20-
21- const lg = new ListenableGenerator<number>(
22- source,
23- onError,
24- new AbortController(),
25- );
26-
27- const result: number[] = [];
28- for await (const value of lg.tee()) {
29- result.push(value);
30- }
31-
32- expect(result).toEqual(values);
33- expect(onError).not.toHaveBeenCalled();
34- });
35-
36- it("should allow listeners to receive values", async () => {
37- const values = [1, 2, 3];
38- const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
39- const onError = jest.fn();
40-
41- const lg = new ListenableGenerator<number>(
42- source,
43- onError,
44- new AbortController(),
45- );
46-
47- const listener = jest.fn();
48-
49- // Add listener after some delay to simulate late subscription
50- setTimeout(() => {
51- lg.listen(listener);
52- }, 15);
53-
54- // Wait for generator to finish
55- await new Promise((resolve) => setTimeout(resolve, 50));
56-
57- expect(listener).toHaveBeenCalledWith(1);
58- expect(listener).toHaveBeenCalledWith(2);
59- expect(listener).toHaveBeenCalledWith(3);
60- // Listener should receive null at the end
61- expect(listener).toHaveBeenCalledWith(null);
62- });
63-
64- it("should buffer values for listeners added after some values have been yielded", async () => {
65- const values = [1, 2, 3];
66- const source = asyncGenerator(values, 10);
67- const onError = jest.fn();
68-
69- const lg = new ListenableGenerator<number>(
70- source,
71- onError,
72- new AbortController(),
73- );
74-
75- const initialListener = jest.fn();
76-
77- lg.listen(initialListener);
78-
79- // Wait for the first value to be yielded
80- await new Promise((resolve) => setTimeout(resolve, 15));
81-
82- // Add a second listener
83- const newListener = jest.fn();
84- lg.listen(newListener);
85-
86- // Wait for generator to finish
87- await new Promise((resolve) => setTimeout(resolve, 50));
88-
89- // Both listeners should have received all values
90- [initialListener, newListener].forEach((listener) => {
91- expect(listener).toHaveBeenCalledWith(1);
92- expect(listener).toHaveBeenCalledWith(2);
93- expect(listener).toHaveBeenCalledWith(3);
94- expect(listener).toHaveBeenCalledWith(null);
95- });
96- });
97-
98- it("should handle cancellation", async () => {
99- const values = [1, 2, 3, 4, 5];
100- const source = asyncGenerator(values, 10);
101- const onError = jest.fn();
102-
103- const lg = new ListenableGenerator<number>(
104- source,
105- onError,
106- new AbortController(),
107- );
108-
109- const result: number[] = [];
110- const teeIterator = lg.tee();
111-
112- const consume = async () => {
113- for await (const value of teeIterator) {
114- result.push(value);
115- if (value === 3) {
116- lg.cancel();
117- }
118- }
119- };
120-
121- await consume();
122-
123- expect(result).toEqual([1, 2, 3]);
124- expect(lg["_isEnded"]).toBe(true);
125- });
126-
127- it("should call onError when the source generator throws an error", async () => {
128- async function* errorGenerator() {
129- yield 1;
130- throw new Error("Test error");
131- }
132-
133- const source = errorGenerator();
134- const onError = jest.fn();
135-
136- const lg = new ListenableGenerator<number>(
137- source,
138- onError,
139- new AbortController(),
140- );
141-
142- const result: number[] = [];
143- for await (const value of lg.tee()) {
144- result.push(value);
145- }
146-
147- expect(result).toEqual([1]);
148- expect(onError).toHaveBeenCalledTimes(1);
149- expect(onError).toHaveBeenCalledWith(new Error("Test error"));
150- });
151-
152- it("should notify listeners when the generator ends", async () => {
153- const values = [1, 2, 3];
154- const source = asyncGenerator(values);
155- const onError = jest.fn();
156-
157- const lg = new ListenableGenerator<number>(
158- source,
159- onError,
160- new AbortController(),
161- );
162-
163- const listener = jest.fn();
164- lg.listen(listener);
165-
166- // Wait for the generator to finish
167- await new Promise((resolve) => setTimeout(resolve, 10));
168-
169- expect(listener).toHaveBeenCalledWith(1);
170- expect(listener).toHaveBeenCalledWith(2);
171- expect(listener).toHaveBeenCalledWith(3);
172- expect(listener).toHaveBeenCalledWith(null);
173- });
174-});
added core/autocomplete/generation/ListenableGenerator.vitest.ts +174 −0
@@ -0,0 +1,174 @@
1+import { describe, expect, it, vi } from "vitest";
2+
3+import { ListenableGenerator } from "./ListenableGenerator";
4+
5+describe("ListenableGenerator", () => {
6+ // Helper function to create an async generator
7+ async function* asyncGenerator<T>(values: T[], delay = 0) {
8+ for (const value of values) {
9+ if (delay > 0) {
10+ await new Promise((resolve) => setTimeout(resolve, delay));
11+ }
12+ yield value;
13+ }
14+ }
15+
16+ it("should yield values from the source generator via tee()", async () => {
17+ const values = [1, 2, 3];
18+ const source = asyncGenerator(values);
19+ const onError = vi.fn();
20+
21+ const lg = new ListenableGenerator<number>(
22+ source,
23+ onError,
24+ new AbortController(),
25+ );
26+
27+ const result: number[] = [];
28+ for await (const value of lg.tee()) {
29+ result.push(value);
30+ }
31+
32+ expect(result).toEqual(values);
33+ expect(onError).not.toHaveBeenCalled();
34+ });
35+
36+ it("should allow listeners to receive values", async () => {
37+ const values = [1, 2, 3];
38+ const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
39+ const onError = vi.fn();
40+
41+ const lg = new ListenableGenerator<number>(
42+ source,
43+ onError,
44+ new AbortController(),
45+ );
46+
47+ const listener = vi.fn();
48+
49+ // Add listener after some delay to simulate late subscription
50+ setTimeout(() => {
51+ lg.listen(listener);
52+ }, 15);
53+
54+ // Wait for generator to finish
55+ await new Promise((resolve) => setTimeout(resolve, 50));
56+
57+ expect(listener).toHaveBeenCalledWith(1);
58+ expect(listener).toHaveBeenCalledWith(2);
59+ expect(listener).toHaveBeenCalledWith(3);
60+ // Listener should receive null at the end
61+ expect(listener).toHaveBeenCalledWith(null);
62+ });
63+
64+ it("should buffer values for listeners added after some values have been yielded", async () => {
65+ const values = [1, 2, 3];
66+ const source = asyncGenerator(values, 10);
67+ const onError = vi.fn();
68+
69+ const lg = new ListenableGenerator<number>(
70+ source,
71+ onError,
72+ new AbortController(),
73+ );
74+
75+ const initialListener = vi.fn();
76+
77+ lg.listen(initialListener);
78+
79+ // Wait for the first value to be yielded
80+ await new Promise((resolve) => setTimeout(resolve, 15));
81+
82+ // Add a second listener
83+ const newListener = vi.fn();
84+ lg.listen(newListener);
85+
86+ // Wait for generator to finish
87+ await new Promise((resolve) => setTimeout(resolve, 50));
88+
89+ // Both listeners should have received all values
90+ [initialListener, newListener].forEach((listener) => {
91+ expect(listener).toHaveBeenCalledWith(1);
92+ expect(listener).toHaveBeenCalledWith(2);
93+ expect(listener).toHaveBeenCalledWith(3);
94+ expect(listener).toHaveBeenCalledWith(null);
95+ });
96+ });
97+
98+ it("should handle cancellation", async () => {
99+ const values = [1, 2, 3, 4, 5];
100+ const source = asyncGenerator(values, 10);
101+ const onError = vi.fn();
102+
103+ const lg = new ListenableGenerator<number>(
104+ source,
105+ onError,
106+ new AbortController(),
107+ );
108+
109+ const result: number[] = [];
110+ const teeIterator = lg.tee();
111+
112+ const consume = async () => {
113+ for await (const value of teeIterator) {
114+ result.push(value);
115+ if (value === 3) {
116+ lg.cancel();
117+ }
118+ }
119+ };
120+
121+ await consume();
122+
123+ expect(result).toEqual([1, 2, 3]);
124+ expect(lg["_isEnded"]).toBe(true);
125+ });
126+
127+ it("should call onError when the source generator throws an error", async () => {
128+ async function* errorGenerator() {
129+ yield 1;
130+ throw new Error("Test error");
131+ }
132+
133+ const source = errorGenerator();
134+ const onError = vi.fn();
135+
136+ const lg = new ListenableGenerator<number>(
137+ source,
138+ onError,
139+ new AbortController(),
140+ );
141+
142+ const result: number[] = [];
143+ for await (const value of lg.tee()) {
144+ result.push(value);
145+ }
146+
147+ expect(result).toEqual([1]);
148+ expect(onError).toHaveBeenCalledTimes(1);
149+ expect(onError).toHaveBeenCalledWith(new Error("Test error"));
150+ });
151+
152+ it("should notify listeners when the generator ends", async () => {
153+ const values = [1, 2, 3];
154+ const source = asyncGenerator(values);
155+ const onError = vi.fn();
156+
157+ const lg = new ListenableGenerator<number>(
158+ source,
159+ onError,
160+ new AbortController(),
161+ );
162+
163+ const listener = vi.fn();
164+ lg.listen(listener);
165+
166+ // Wait for the generator to finish
167+ await new Promise((resolve) => setTimeout(resolve, 10));
168+
169+ expect(listener).toHaveBeenCalledWith(1);
170+ expect(listener).toHaveBeenCalledWith(2);
171+ expect(listener).toHaveBeenCalledWith(3);
172+ expect(listener).toHaveBeenCalledWith(null);
173+ });
174+});
deleted core/autocomplete/generation/utils.test.ts +0 −138
@@ -1,138 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { stopAfterMaxProcessingTime } from "./utils";
3-
4-describe("stopAfterMaxProcessingTime", () => {
5- beforeEach(() => {
6- jest.useFakeTimers();
7- });
8-
9- afterEach(() => {
10- jest.useRealTimers();
11- });
12-
13- async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
14- for (const chunk of chunks) {
15- yield chunk;
16- }
17- }
18-
19- async function streamToString(
20- stream: AsyncGenerator<string>,
21- ): Promise<string> {
22- let result = "";
23- for await (const chunk of stream) {
24- result += chunk;
25- }
26- return result;
27- }
28-
29- it("should yield all chunks when maxTimeMs is not reached", async () => {
30- const mockStream = createMockStream(["Hello", " world", "!"]);
31- const fullStop = jest.fn();
32- const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
33-
34- const output = await streamToString(result);
35-
36- expect(output).toBe("Hello world!");
37- expect(fullStop).not.toHaveBeenCalled();
38- });
39-
40- it.only("should stop processing after max time is reached", async () => {
41- // Mock implementation of Date.now
42- let currentTime = 0;
43- const originalDateNow = Date.now;
44- Date.now = jest.fn(() => currentTime);
45-
46- // Create a generator that we can control
47- async function* controlledGenerator(): AsyncGenerator<string> {
48- for (let i = 0; i < 100; i++) {
49- // After yielding 10 chunks, simulate time passing beyond our limit
50- if (i === 10) {
51- currentTime = 1000; // This exceeds our 500ms limit
52- }
53- yield `chunk-${i}`;
54- }
55- }
56-
57- const fullStop = jest.fn();
58- const maxTimeMs = 500;
59-
60- const transformedGenerator = stopAfterMaxProcessingTime(
61- controlledGenerator(),
62- maxTimeMs,
63- fullStop,
64- );
65-
66- // Consume the generator and collect outputs
67- const outputs: string[] = [];
68- for await (const chunk of transformedGenerator) {
69- outputs.push(chunk);
70- }
71-
72- // We expect:
73- // 1. Not all chunks were processed (less than 100)
74- // 2. fullStop was called
75- // 3. We processed at least the chunks before time was exceeded
76- expect(outputs.length).toBeLessThan(100);
77- expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
78- expect(fullStop).toHaveBeenCalled();
79-
80- // Restore Date.now
81- Date.now = originalDateNow;
82- });
83-
84- it("should check time only periodically based on checkInterval", async () => {
85- const chunks = Array(100).fill("x");
86- const mockStream = createMockStream(chunks);
87- const fullStop = jest.fn();
88-
89- // Spy on Date.now to count how many times it's called
90- const dateSpy = jest.spyOn(Date, "now");
91-
92- // Stream should complete normally (not hitting the timeout)
93- await streamToString(
94- stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
95- );
96-
97- // The first call is to set startTime, then once every checkInterval (10) chunks
98- // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
99- // We use a range because implementation details might vary slightly
100- expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
101- expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
102-
103- dateSpy.mockRestore();
104- });
105-
106- it("should handle empty stream gracefully", async () => {
107- const mockStream = createMockStream([]);
108- const fullStop = jest.fn();
109- const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
110-
111- const output = await streamToString(result);
112-
113- expect(output).toBe("");
114- expect(fullStop).not.toHaveBeenCalled();
115- });
116-
117- it("should pass through all chunks if there's no timeout", async () => {
118- const chunks = Array(100).fill("test chunk");
119- const mockStream = createMockStream(chunks);
120- const fullStop = jest.fn();
121-
122- // Use undefined as timeout to simulate no timeout
123- const result = stopAfterMaxProcessingTime(
124- mockStream,
125- undefined as any,
126- fullStop,
127- );
128-
129- // Process the stream
130- const processedChunks = [];
131- for await (const chunk of result) {
132- processedChunks.push(chunk);
133- }
134-
135- expect(processedChunks.length).toBe(chunks.length);
136- expect(fullStop).not.toHaveBeenCalled();
137- });
138-});
added core/autocomplete/generation/utils.vitest.ts +138 −0
@@ -0,0 +1,138 @@
1+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+import { stopAfterMaxProcessingTime } from "./utils";
3+
4+describe("stopAfterMaxProcessingTime", () => {
5+ beforeEach(() => {
6+ vi.useFakeTimers();
7+ });
8+
9+ afterEach(() => {
10+ vi.useRealTimers();
11+ });
12+
13+ async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
14+ for (const chunk of chunks) {
15+ yield chunk;
16+ }
17+ }
18+
19+ async function streamToString(
20+ stream: AsyncGenerator<string>,
21+ ): Promise<string> {
22+ let result = "";
23+ for await (const chunk of stream) {
24+ result += chunk;
25+ }
26+ return result;
27+ }
28+
29+ it("should yield all chunks when maxTimeMs is not reached", async () => {
30+ const mockStream = createMockStream(["Hello", " world", "!"]);
31+ const fullStop = vi.fn();
32+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
33+
34+ const output = await streamToString(result);
35+
36+ expect(output).toBe("Hello world!");
37+ expect(fullStop).not.toHaveBeenCalled();
38+ });
39+
40+ it("should stop processing after max time is reached", async () => {
41+ // Mock implementation of Date.now
42+ let currentTime = 0;
43+ const originalDateNow = Date.now;
44+ Date.now = vi.fn(() => currentTime);
45+
46+ // Create a generator that we can control
47+ async function* controlledGenerator(): AsyncGenerator<string> {
48+ for (let i = 0; i < 100; i++) {
49+ // After yielding 10 chunks, simulate time passing beyond our limit
50+ if (i === 10) {
51+ currentTime = 1000; // This exceeds our 500ms limit
52+ }
53+ yield `chunk-${i}`;
54+ }
55+ }
56+
57+ const fullStop = vi.fn();
58+ const maxTimeMs = 500;
59+
60+ const transformedGenerator = stopAfterMaxProcessingTime(
61+ controlledGenerator(),
62+ maxTimeMs,
63+ fullStop,
64+ );
65+
66+ // Consume the generator and collect outputs
67+ const outputs: string[] = [];
68+ for await (const chunk of transformedGenerator) {
69+ outputs.push(chunk);
70+ }
71+
72+ // We expect:
73+ // 1. Not all chunks were processed (less than 100)
74+ // 2. fullStop was called
75+ // 3. We processed at least the chunks before time was exceeded
76+ expect(outputs.length).toBeLessThan(100);
77+ expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
78+ expect(fullStop).toHaveBeenCalled();
79+
80+ // Restore Date.now
81+ Date.now = originalDateNow;
82+ });
83+
84+ it("should check time only periodically based on checkInterval", async () => {
85+ const chunks = Array(100).fill("x");
86+ const mockStream = createMockStream(chunks);
87+ const fullStop = vi.fn();
88+
89+ // Spy on Date.now to count how many times it's called
90+ const dateSpy = vi.spyOn(Date, "now");
91+
92+ // Stream should complete normally (not hitting the timeout)
93+ await streamToString(
94+ stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
95+ );
96+
97+ // The first call is to set startTime, then once every checkInterval (10) chunks
98+ // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
99+ // We use a range because implementation details might vary slightly
100+ expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
101+ expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
102+
103+ dateSpy.mockRestore();
104+ });
105+
106+ it("should handle empty stream gracefully", async () => {
107+ const mockStream = createMockStream([]);
108+ const fullStop = vi.fn();
109+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
110+
111+ const output = await streamToString(result);
112+
113+ expect(output).toBe("");
114+ expect(fullStop).not.toHaveBeenCalled();
115+ });
116+
117+ it("should pass through all chunks if there's no timeout", async () => {
118+ const chunks = Array(100).fill("test chunk");
119+ const mockStream = createMockStream(chunks);
120+ const fullStop = vi.fn();
121+
122+ // Use undefined as timeout to simulate no timeout
123+ const result = stopAfterMaxProcessingTime(
124+ mockStream,
125+ undefined as any,
126+ fullStop,
127+ );
128+
129+ // Process the stream
130+ const processedChunks = [];
131+ for await (const chunk of result) {
132+ processedChunks.push(chunk);
133+ }
134+
135+ expect(processedChunks.length).toBe(chunks.length);
136+ expect(fullStop).not.toHaveBeenCalled();
137+ });
138+});
deleted core/autocomplete/snippets/gitDiffCache.test.ts +0 −84
@@ -1,84 +0,0 @@
1-import { GitDiffCache } from "./gitDiffCache";
2-
3-beforeEach(() => {
4- // Add this line to GitDiffCache class to make instance accessible
5- (GitDiffCache as any).instance = null;
6-});
7-
8-test("GitDiffCache returns cached results within cache time", async () => {
9- const mockDiff = ["file1.ts", "file2.ts"];
10- const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
11- const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
12-
13- const result1 = await cache.get();
14- const result2 = await cache.get();
15-
16- expect(result1).toEqual(mockDiff);
17- expect(result2).toEqual(mockDiff);
18- expect(getDiffFn).toHaveBeenCalledTimes(1);
19-});
20-
21-test("GitDiffCache refreshes cache after expiration", async () => {
22- const mockDiff = ["file1.ts"];
23- const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
24- const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
25-
26- const result1 = await cache.get();
27- await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
28- const result2 = await cache.get();
29-
30- expect(getDiffFn).toHaveBeenCalledTimes(2);
31-});
32-
33-test("GitDiffCache returns empty array on error", async () => {
34- const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error"));
35- const cache = GitDiffCache.getInstance(getDiffFn);
36-
37- const result = await cache.get();
38- expect(result).toEqual([]);
39-});
40-
41-test("GitDiffCache reuses pending request", async () => {
42- const mockDiff = ["file1.ts"];
43- let resolvePromise: (value: string[]) => void;
44- const getDiffFn = jest.fn().mockImplementation(() => {
45- return new Promise((resolve) => {
46- resolvePromise = resolve;
47- });
48- });
49-
50- const cache = GitDiffCache.getInstance(getDiffFn);
51-
52- const promise1 = cache.get();
53- const promise2 = cache.get();
54-
55- resolvePromise!(mockDiff);
56-
57- const [result1, result2] = await Promise.all([promise1, promise2]);
58-
59- expect(result1).toEqual(mockDiff);
60- expect(result2).toEqual(mockDiff);
61- expect(getDiffFn).toHaveBeenCalledTimes(1);
62-});
63-
64-test("GitDiffCache invalidate clears cache", async () => {
65- const mockDiff = ["file1.ts"];
66- const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
67- const cache = GitDiffCache.getInstance(getDiffFn);
68-
69- await cache.get();
70- cache.invalidate();
71- await cache.get();
72-
73- expect(getDiffFn).toHaveBeenCalledTimes(2);
74-});
75-
76-test("GitDiffCache maintains singleton instance", () => {
77- const getDiffFn1 = jest.fn();
78- const getDiffFn2 = jest.fn();
79-
80- const instance1 = GitDiffCache.getInstance(getDiffFn1);
81- const instance2 = GitDiffCache.getInstance(getDiffFn2);
82-
83- expect(instance1).toBe(instance2);
84-});
added core/autocomplete/snippets/gitDiffCache.vitest.ts +85 −0
@@ -0,0 +1,85 @@
1+import { beforeEach, expect, test, vi } from "vitest";
2+import { GitDiffCache } from "./gitDiffCache";
3+
4+beforeEach(() => {
5+ // Add this line to GitDiffCache class to make instance accessible
6+ (GitDiffCache as any).instance = null;
7+});
8+
9+test("GitDiffCache returns cached results within cache time", async () => {
10+ const mockDiff = ["file1.ts", "file2.ts"];
11+ const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
12+ const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
13+
14+ const result1 = await cache.get();
15+ const result2 = await cache.get();
16+
17+ expect(result1).toEqual(mockDiff);
18+ expect(result2).toEqual(mockDiff);
19+ expect(getDiffFn).toHaveBeenCalledTimes(1);
20+});
21+
22+test("GitDiffCache refreshes cache after expiration", async () => {
23+ const mockDiff = ["file1.ts"];
24+ const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
25+ const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
26+
27+ const result1 = await cache.get();
28+ await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
29+ const result2 = await cache.get();
30+
31+ expect(getDiffFn).toHaveBeenCalledTimes(2);
32+});
33+
34+test("GitDiffCache returns empty array on error", async () => {
35+ const getDiffFn = vi.fn().mockRejectedValue(new Error("Git error"));
36+ const cache = GitDiffCache.getInstance(getDiffFn);
37+
38+ const result = await cache.get();
39+ expect(result).toEqual([]);
40+});
41+
42+test("GitDiffCache reuses pending request", async () => {
43+ const mockDiff = ["file1.ts"];
44+ let resolvePromise: (value: string[]) => void;
45+ const getDiffFn = vi.fn().mockImplementation(() => {
46+ return new Promise((resolve) => {
47+ resolvePromise = resolve;
48+ });
49+ });
50+
51+ const cache = GitDiffCache.getInstance(getDiffFn);
52+
53+ const promise1 = cache.get();
54+ const promise2 = cache.get();
55+
56+ resolvePromise!(mockDiff);
57+
58+ const [result1, result2] = await Promise.all([promise1, promise2]);
59+
60+ expect(result1).toEqual(mockDiff);
61+ expect(result2).toEqual(mockDiff);
62+ expect(getDiffFn).toHaveBeenCalledTimes(1);
63+});
64+
65+test("GitDiffCache invalidate clears cache", async () => {
66+ const mockDiff = ["file1.ts"];
67+ const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
68+ const cache = GitDiffCache.getInstance(getDiffFn);
69+
70+ await cache.get();
71+ cache.invalidate();
72+ await cache.get();
73+
74+ expect(getDiffFn).toHaveBeenCalledTimes(2);
75+});
76+
77+test("GitDiffCache maintains singleton instance", () => {
78+ const getDiffFn1 = vi.fn();
79+ const getDiffFn2 = vi.fn();
80+
81+ const instance1 = GitDiffCache.getInstance(getDiffFn1);
82+ const instance2 = GitDiffCache.getInstance(getDiffFn2);
83+
84+ expect(instance1).toBe(instance2);
85+});
deleted core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts +0 −434
@@ -1,434 +0,0 @@
1-/**
2- * Comprehensive tests for formatOpenedFilesContext.ts
3- *
4- */
5-
6-import {
7- AutocompleteCodeSnippet,
8- AutocompleteDiffSnippet,
9- AutocompleteSnippetType,
10-} from "../../snippets/types";
11-import { HelperVars } from "../../util/HelperVars";
12-import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
13-
14-// Import the now-exported internal functions
15-import {
16- getRecencyAndSizeScore,
17- rankByScore,
18- setLogStats,
19- trimSnippetForContext,
20-} from "../formatOpenedFilesContext";
21-
22-describe("formatOpenedFilesContext main function tests", () => {
23- const mockHelper = {
24- modelName: "test-model",
25- } as HelperVars;
26-
27- const TOKEN_BUFFER = 50;
28-
29- // Create sample code snippets with various sizes
30- const createCodeSnippet = (
31- filepath: string,
32- content: string,
33- ): AutocompleteCodeSnippet => ({
34- type: AutocompleteSnippetType.Code,
35- filepath,
36- content,
37- });
38-
39- const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
40- type: AutocompleteSnippetType.Diff,
41- content,
42- });
43-
44- test("should return empty array when no snippets are provided", () => {
45- const result = formatOpenedFilesContext(
46- [],
47- 1000,
48- mockHelper,
49- [],
50- TOKEN_BUFFER,
51- );
52- expect(result).toEqual([]);
53- });
54-
55- test("should handle zero remaining token count", () => {
56- const snippets = [
57- createCodeSnippet("file1.ts", "content of file 1"),
58- createCodeSnippet("file2.ts", "content of file 2"),
59- ];
60-
61- const result = formatOpenedFilesContext(
62- snippets,
63- 0,
64- mockHelper,
65- [],
66- TOKEN_BUFFER,
67- );
68-
69- expect(result).toEqual([]);
70- });
71-
72- test("should handle snippets with empty content", () => {
73- const emptySnippets = [
74- createCodeSnippet("empty1.ts", ""),
75- createCodeSnippet("empty2.ts", ""),
76- ];
77-
78- const result = formatOpenedFilesContext(
79- emptySnippets,
80- 1000,
81- mockHelper,
82- [],
83- TOKEN_BUFFER,
84- );
85-
86- expect(result.length).toBe(emptySnippets.length);
87- });
88-
89- test("should return all snippets when they all fit within token limit", () => {
90- const smallSnippets = [
91- createCodeSnippet("small1.ts", "a"),
92- createCodeSnippet("small2.ts", "b"),
93- createCodeSnippet("small3.ts", "c"),
94- ];
95-
96- const result = formatOpenedFilesContext(
97- smallSnippets,
98- 1000,
99- mockHelper,
100- [],
101- TOKEN_BUFFER,
102- );
103-
104- expect(result.length).toBe(smallSnippets.length);
105- });
106-
107- test("should handle limited token count", () => {
108- const snippets = Array(10)
109- .fill(0)
110- .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
111-
112- const result = formatOpenedFilesContext(
113- snippets,
114- 1, // Extremely small token count
115- mockHelper,
116- [],
117- TOKEN_BUFFER,
118- );
119-
120- expect(Array.isArray(result)).toBe(true);
121- });
122-
123- test("should accept valid inputs with adequate token count", () => {
124- const snippets = [
125- createCodeSnippet("file1.ts", "Some content here"),
126- createCodeSnippet("file2.ts", "More content here"),
127- ];
128-
129- const result = formatOpenedFilesContext(
130- snippets,
131- 1000,
132- mockHelper,
133- [],
134- TOKEN_BUFFER,
135- );
136-
137- expect(result.length).toBeGreaterThan(0);
138- });
139-
140- test("should handle already added snippets parameter", () => {
141- const snippets = [
142- createCodeSnippet("file1.ts", "content of file 1"),
143- createCodeSnippet("file2.ts", "content of file 2"),
144- ];
145-
146- const alreadyAddedSnippets = [createDiffSnippet("diff content")];
147-
148- const result = formatOpenedFilesContext(
149- snippets,
150- 1000,
151- mockHelper,
152- alreadyAddedSnippets,
153- TOKEN_BUFFER,
154- );
155-
156- expect(result.length).toBe(snippets.length);
157- });
158-
159- test("should handle large snippets by trimming them", () => {
160- const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
161-
162- const result = formatOpenedFilesContext(
163- [largeSnippet],
164- 200,
165- mockHelper,
166- [],
167- TOKEN_BUFFER,
168- );
169-
170- expect(result.length).toBe(1);
171- expect(result[0].filepath).toBe(largeSnippet.filepath);
172- expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
173- });
174-
175- test("should prioritize more recent snippets when not all fit", () => {
176- const snippets = [
177- createCodeSnippet("recent1.ts", "a".repeat(10)),
178- createCodeSnippet("recent2.ts", "b".repeat(10000)),
179- createCodeSnippet("recent3.ts", "c".repeat(10000)),
180- ];
181-
182- const result = formatOpenedFilesContext(
183- snippets,
184- 200,
185- mockHelper,
186- [],
187- TOKEN_BUFFER,
188- );
189-
190- expect(result.length).toBeGreaterThan(0);
191- expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
192- });
193-
194- test("should handle a mix of large and small snippets effectively", () => {
195- const mixedSnippets = [
196- createCodeSnippet("small1.ts", "a".repeat(10)),
197- createCodeSnippet("large1.ts", "b".repeat(5000)),
198- createCodeSnippet("small2.ts", "c".repeat(10)),
199- createCodeSnippet("large2.ts", "d".repeat(5000)),
200- ];
201-
202- const result = formatOpenedFilesContext(
203- mixedSnippets,
204- 500,
205- mockHelper,
206- [],
207- TOKEN_BUFFER,
208- );
209-
210- expect(result.length).toBeGreaterThan(0);
211- expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
212- });
213-
214- test("should respect minimum token threshold when trimming", () => {
215- const largeSnippets = [
216- createCodeSnippet("large1.ts", "a".repeat(5000)),
217- createCodeSnippet("large2.ts", "b".repeat(5000)),
218- ];
219-
220- const result = formatOpenedFilesContext(
221- largeSnippets,
222- 150,
223- mockHelper,
224- [],
225- TOKEN_BUFFER,
226- );
227-
228- expect(result.length).toBeLessThanOrEqual(1);
229-
230- if (result.length > 0) {
231- expect(result[0].content.length).toBeLessThan(
232- largeSnippets[0].content.length,
233- );
234- }
235- });
236-});
237-
238-// Tests for rankByScore function
239-describe("rankByScore function", () => {
240- const createCodeSnippet = (
241- filepath: string,
242- content: string,
243- ): AutocompleteCodeSnippet => ({
244- type: AutocompleteSnippetType.Code,
245- filepath,
246- content,
247- });
248-
249- test("should return empty array when given empty array", () => {
250- const result = rankByScore([]);
251- expect(result).toEqual([]);
252- });
253-
254- test("should rank snippets by score", () => {
255- // Initialize logMin and logMax by calling setLogStats first
256- const snippets = [
257- createCodeSnippet("file1.ts", "a".repeat(10)),
258- createCodeSnippet("file2.ts", "b".repeat(1000)),
259- createCodeSnippet("file3.ts", "c".repeat(100)),
260- ];
261- setLogStats(snippets);
262-
263- const result = rankByScore(snippets);
264-
265- expect(Array.isArray(result)).toBe(true);
266- expect(result.length).toBeGreaterThan(0);
267-
268- // The snippets should be ranked in some order, which may not match input order
269- expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
270- snippets.map((s) => s.filepath),
271- );
272- });
273-
274- test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
275- // Create more snippets than the default limit
276- const manySnippets = Array(10)
277- .fill(0)
278- .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
279- setLogStats(manySnippets);
280-
281- const result = rankByScore(manySnippets);
282-
283- // The function should limit the number of snippets (defaultNumFilesUsed is 5)
284- expect(result.length).toBeLessThanOrEqual(5);
285- });
286-});
287-
288-// Tests for getRecencyAndSizeScore function
289-describe("getRecencyAndSizeScore function", () => {
290- const createCodeSnippet = (
291- filepath: string,
292- content: string,
293- ): AutocompleteCodeSnippet => ({
294- type: AutocompleteSnippetType.Code,
295- filepath,
296- content,
297- });
298-
299- test("recency score should decrease with higher index", () => {
300- // Initialize log stats first
301- const snippets = [
302- createCodeSnippet("file1.ts", "a".repeat(100)),
303- createCodeSnippet("file2.ts", "b".repeat(100)),
304- ];
305- setLogStats(snippets);
306-
307- // Test that score decreases with increasing index
308- const score0 = getRecencyAndSizeScore(0, snippets[0]);
309- const score1 = getRecencyAndSizeScore(1, snippets[0]);
310- const score2 = getRecencyAndSizeScore(2, snippets[0]);
311-
312- expect(score0).toBeGreaterThan(score1);
313- expect(score1).toBeGreaterThan(score2);
314- });
315-
316- test("size score should be higher for smaller snippets", () => {
317- // Initialize log stats first
318- const snippets = [
319- createCodeSnippet("small.ts", "a".repeat(50)),
320- createCodeSnippet("medium.ts", "b".repeat(200)),
321- createCodeSnippet("large.ts", "c".repeat(1000)),
322- ];
323- setLogStats(snippets);
324-
325- // Test with same recency index but different sizes
326- const smallScore = getRecencyAndSizeScore(0, snippets[0]);
327- const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
328- const largeScore = getRecencyAndSizeScore(0, snippets[2]);
329-
330- // Scores should reflect preference for smaller snippets
331- expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
332- expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
333- });
334-
335- test("recency and size both affect the score with recency having more weight", () => {
336- // Initialize log stats first
337- const snippets = [
338- createCodeSnippet("recent_large.ts", "a".repeat(1000)),
339- createCodeSnippet("old_small.ts", "b".repeat(50)),
340- ];
341- setLogStats(snippets);
342-
343- // Test that recency and size both contribute to the score
344- const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
345- const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
346-
347- // We're not making a direct comparison, just verifying the scoring mechanism works
348- expect(recentLargeScore).toBeGreaterThan(0);
349- expect(oldSmallScore).toBeGreaterThan(0);
350- expect(oldSmallScore).toBeLessThan(1);
351- });
352-});
353-
354-// Tests for setLogStats function
355-describe("setLogStats function", () => {
356- const createCodeSnippet = (
357- filepath: string,
358- content: string,
359- ): AutocompleteCodeSnippet => ({
360- type: AutocompleteSnippetType.Code,
361- filepath,
362- content,
363- });
364-
365- test("should set logMin and logMax based on snippet sizes", () => {
366- const snippets = [
367- createCodeSnippet("small.ts", "a".repeat(50)),
368- createCodeSnippet("medium.ts", "b".repeat(200)),
369- createCodeSnippet("large.ts", "c".repeat(1000)),
370- ];
371-
372- // We can't directly test logMin and logMax as they're private
373- // but we can verify that the function runs without errors
374- expect(() => setLogStats(snippets)).not.toThrow();
375- });
376-
377- test("should handle empty snippets", () => {
378- const emptySnippets = [
379- createCodeSnippet("empty1.ts", ""),
380- createCodeSnippet("empty2.ts", ""),
381- ];
382-
383- expect(() => setLogStats(emptySnippets)).not.toThrow();
384- });
385-
386- test("should handle single snippet", () => {
387- const singleSnippet = [createCodeSnippet("single.ts", "content")];
388-
389- expect(() => setLogStats(singleSnippet)).not.toThrow();
390- });
391-});
392-
393-// Tests for trimSnippetForContext function
394-describe("trimSnippetForContext function", () => {
395- const createCodeSnippet = (
396- filepath: string,
397- content: string,
398- ): AutocompleteCodeSnippet => ({
399- type: AutocompleteSnippetType.Code,
400- filepath,
401- content,
402- });
403-
404- test("should return original snippet if it fits within token limit", () => {
405- const snippet = createCodeSnippet("small.ts", "small content");
406- const modelName = "test-model";
407- const maxTokens = 1000; // Large enough to fit the snippet
408-
409- const result = trimSnippetForContext(snippet, maxTokens, modelName);
410-
411- // Should return the original snippet with its token count
412- expect(result.newSnippet).toEqual(snippet);
413- expect(typeof result.newTokens).toBe("number");
414- expect(result.newTokens).toBeGreaterThan(0);
415- });
416-
417- test("should trim snippet content if it exceeds token limit", () => {
418- const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
419- const modelName = "test-model";
420- const maxTokens = 10; // Small enough to require trimming
421-
422- const result = trimSnippetForContext(snippet, maxTokens, modelName);
423-
424- // Should return a trimmed snippet
425- expect(result.newSnippet.filepath).toBe(snippet.filepath);
426- expect(result.newSnippet.type).toBe(snippet.type);
427- expect(result.newSnippet.content.length).toBeLessThanOrEqual(
428- snippet.content.length,
429- );
430-
431- // Token count should be less than or equal to maxTokens
432- expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
433- });
434-});
added core/autocomplete/templating/__tests__/formatOpenedFilesContext.vitest.ts +435 −0
@@ -0,0 +1,435 @@
1+/**
2+ * Comprehensive tests for formatOpenedFilesContext.ts
3+ *
4+ */
5+
6+import { describe, expect, test } from "vitest";
7+import {
8+ AutocompleteCodeSnippet,
9+ AutocompleteDiffSnippet,
10+ AutocompleteSnippetType,
11+} from "../../snippets/types";
12+import { HelperVars } from "../../util/HelperVars";
13+import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
14+
15+// Import the now-exported internal functions
16+import {
17+ getRecencyAndSizeScore,
18+ rankByScore,
19+ setLogStats,
20+ trimSnippetForContext,
21+} from "../formatOpenedFilesContext";
22+
23+describe("formatOpenedFilesContext main function tests", () => {
24+ const mockHelper = {
25+ modelName: "test-model",
26+ } as HelperVars;
27+
28+ const TOKEN_BUFFER = 50;
29+
30+ // Create sample code snippets with various sizes
31+ const createCodeSnippet = (
32+ filepath: string,
33+ content: string,
34+ ): AutocompleteCodeSnippet => ({
35+ type: AutocompleteSnippetType.Code,
36+ filepath,
37+ content,
38+ });
39+
40+ const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
41+ type: AutocompleteSnippetType.Diff,
42+ content,
43+ });
44+
45+ test("should return empty array when no snippets are provided", () => {
46+ const result = formatOpenedFilesContext(
47+ [],
48+ 1000,
49+ mockHelper,
50+ [],
51+ TOKEN_BUFFER,
52+ );
53+ expect(result).toEqual([]);
54+ });
55+
56+ test("should handle zero remaining token count", () => {
57+ const snippets = [
58+ createCodeSnippet("file1.ts", "content of file 1"),
59+ createCodeSnippet("file2.ts", "content of file 2"),
60+ ];
61+
62+ const result = formatOpenedFilesContext(
63+ snippets,
64+ 0,
65+ mockHelper,
66+ [],
67+ TOKEN_BUFFER,
68+ );
69+
70+ expect(result).toEqual([]);
71+ });
72+
73+ test("should handle snippets with empty content", () => {
74+ const emptySnippets = [
75+ createCodeSnippet("empty1.ts", ""),
76+ createCodeSnippet("empty2.ts", ""),
77+ ];
78+
79+ const result = formatOpenedFilesContext(
80+ emptySnippets,
81+ 1000,
82+ mockHelper,
83+ [],
84+ TOKEN_BUFFER,
85+ );
86+
87+ expect(result.length).toBe(emptySnippets.length);
88+ });
89+
90+ test("should return all snippets when they all fit within token limit", () => {
91+ const smallSnippets = [
92+ createCodeSnippet("small1.ts", "a"),
93+ createCodeSnippet("small2.ts", "b"),
94+ createCodeSnippet("small3.ts", "c"),
95+ ];
96+
97+ const result = formatOpenedFilesContext(
98+ smallSnippets,
99+ 1000,
100+ mockHelper,
101+ [],
102+ TOKEN_BUFFER,
103+ );
104+
105+ expect(result.length).toBe(smallSnippets.length);
106+ });
107+
108+ test("should handle limited token count", () => {
109+ const snippets = Array(10)
110+ .fill(0)
111+ .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
112+
113+ const result = formatOpenedFilesContext(
114+ snippets,
115+ 1, // Extremely small token count
116+ mockHelper,
117+ [],
118+ TOKEN_BUFFER,
119+ );
120+
121+ expect(Array.isArray(result)).toBe(true);
122+ });
123+
124+ test("should accept valid inputs with adequate token count", () => {
125+ const snippets = [
126+ createCodeSnippet("file1.ts", "Some content here"),
127+ createCodeSnippet("file2.ts", "More content here"),
128+ ];
129+
130+ const result = formatOpenedFilesContext(
131+ snippets,
132+ 1000,
133+ mockHelper,
134+ [],
135+ TOKEN_BUFFER,
136+ );
137+
138+ expect(result.length).toBeGreaterThan(0);
139+ });
140+
141+ test("should handle already added snippets parameter", () => {
142+ const snippets = [
143+ createCodeSnippet("file1.ts", "content of file 1"),
144+ createCodeSnippet("file2.ts", "content of file 2"),
145+ ];
146+
147+ const alreadyAddedSnippets = [createDiffSnippet("diff content")];
148+
149+ const result = formatOpenedFilesContext(
150+ snippets,
151+ 1000,
152+ mockHelper,
153+ alreadyAddedSnippets,
154+ TOKEN_BUFFER,
155+ );
156+
157+ expect(result.length).toBe(snippets.length);
158+ });
159+
160+ test("should handle large snippets by trimming them", () => {
161+ const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
162+
163+ const result = formatOpenedFilesContext(
164+ [largeSnippet],
165+ 200,
166+ mockHelper,
167+ [],
168+ TOKEN_BUFFER,
169+ );
170+
171+ expect(result.length).toBe(1);
172+ expect(result[0].filepath).toBe(largeSnippet.filepath);
173+ expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
174+ });
175+
176+ test("should prioritize more recent snippets when not all fit", () => {
177+ const snippets = [
178+ createCodeSnippet("recent1.ts", "a".repeat(10)),
179+ createCodeSnippet("recent2.ts", "b".repeat(10000)),
180+ createCodeSnippet("recent3.ts", "c".repeat(10000)),
181+ ];
182+
183+ const result = formatOpenedFilesContext(
184+ snippets,
185+ 200,
186+ mockHelper,
187+ [],
188+ TOKEN_BUFFER,
189+ );
190+
191+ expect(result.length).toBeGreaterThan(0);
192+ expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
193+ });
194+
195+ test("should handle a mix of large and small snippets effectively", () => {
196+ const mixedSnippets = [
197+ createCodeSnippet("small1.ts", "a".repeat(10)),
198+ createCodeSnippet("large1.ts", "b".repeat(5000)),
199+ createCodeSnippet("small2.ts", "c".repeat(10)),
200+ createCodeSnippet("large2.ts", "d".repeat(5000)),
201+ ];
202+
203+ const result = formatOpenedFilesContext(
204+ mixedSnippets,
205+ 500,
206+ mockHelper,
207+ [],
208+ TOKEN_BUFFER,
209+ );
210+
211+ expect(result.length).toBeGreaterThan(0);
212+ expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
213+ });
214+
215+ test("should respect minimum token threshold when trimming", () => {
216+ const largeSnippets = [
217+ createCodeSnippet("large1.ts", "a".repeat(5000)),
218+ createCodeSnippet("large2.ts", "b".repeat(5000)),
219+ ];
220+
221+ const result = formatOpenedFilesContext(
222+ largeSnippets,
223+ 150,
224+ mockHelper,
225+ [],
226+ TOKEN_BUFFER,
227+ );
228+
229+ expect(result.length).toBeLessThanOrEqual(1);
230+
231+ if (result.length > 0) {
232+ expect(result[0].content.length).toBeLessThan(
233+ largeSnippets[0].content.length,
234+ );
235+ }
236+ });
237+});
238+
239+// Tests for rankByScore function
240+describe("rankByScore function", () => {
241+ const createCodeSnippet = (
242+ filepath: string,
243+ content: string,
244+ ): AutocompleteCodeSnippet => ({
245+ type: AutocompleteSnippetType.Code,
246+ filepath,
247+ content,
248+ });
249+
250+ test("should return empty array when given empty array", () => {
251+ const result = rankByScore([]);
252+ expect(result).toEqual([]);
253+ });
254+
255+ test("should rank snippets by score", () => {
256+ // Initialize logMin and logMax by calling setLogStats first
257+ const snippets = [
258+ createCodeSnippet("file1.ts", "a".repeat(10)),
259+ createCodeSnippet("file2.ts", "b".repeat(1000)),
260+ createCodeSnippet("file3.ts", "c".repeat(100)),
261+ ];
262+ setLogStats(snippets);
263+
264+ const result = rankByScore(snippets);
265+
266+ expect(Array.isArray(result)).toBe(true);
267+ expect(result.length).toBeGreaterThan(0);
268+
269+ // The snippets should be ranked in some order, which may not match input order
270+ expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
271+ snippets.map((s) => s.filepath),
272+ );
273+ });
274+
275+ test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
276+ // Create more snippets than the default limit
277+ const manySnippets = Array(10)
278+ .fill(0)
279+ .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
280+ setLogStats(manySnippets);
281+
282+ const result = rankByScore(manySnippets);
283+
284+ // The function should limit the number of snippets (defaultNumFilesUsed is 5)
285+ expect(result.length).toBeLessThanOrEqual(5);
286+ });
287+});
288+
289+// Tests for getRecencyAndSizeScore function
290+describe("getRecencyAndSizeScore function", () => {
291+ const createCodeSnippet = (
292+ filepath: string,
293+ content: string,
294+ ): AutocompleteCodeSnippet => ({
295+ type: AutocompleteSnippetType.Code,
296+ filepath,
297+ content,
298+ });
299+
300+ test("recency score should decrease with higher index", () => {
301+ // Initialize log stats first
302+ const snippets = [
303+ createCodeSnippet("file1.ts", "a".repeat(100)),
304+ createCodeSnippet("file2.ts", "b".repeat(100)),
305+ ];
306+ setLogStats(snippets);
307+
308+ // Test that score decreases with increasing index
309+ const score0 = getRecencyAndSizeScore(0, snippets[0]);
310+ const score1 = getRecencyAndSizeScore(1, snippets[0]);
311+ const score2 = getRecencyAndSizeScore(2, snippets[0]);
312+
313+ expect(score0).toBeGreaterThan(score1);
314+ expect(score1).toBeGreaterThan(score2);
315+ });
316+
317+ test("size score should be higher for smaller snippets", () => {
318+ // Initialize log stats first
319+ const snippets = [
320+ createCodeSnippet("small.ts", "a".repeat(50)),
321+ createCodeSnippet("medium.ts", "b".repeat(200)),
322+ createCodeSnippet("large.ts", "c".repeat(1000)),
323+ ];
324+ setLogStats(snippets);
325+
326+ // Test with same recency index but different sizes
327+ const smallScore = getRecencyAndSizeScore(0, snippets[0]);
328+ const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
329+ const largeScore = getRecencyAndSizeScore(0, snippets[2]);
330+
331+ // Scores should reflect preference for smaller snippets
332+ expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
333+ expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
334+ });
335+
336+ test("recency and size both affect the score with recency having more weight", () => {
337+ // Initialize log stats first
338+ const snippets = [
339+ createCodeSnippet("recent_large.ts", "a".repeat(1000)),
340+ createCodeSnippet("old_small.ts", "b".repeat(50)),
341+ ];
342+ setLogStats(snippets);
343+
344+ // Test that recency and size both contribute to the score
345+ const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
346+ const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
347+
348+ // We're not making a direct comparison, just verifying the scoring mechanism works
349+ expect(recentLargeScore).toBeGreaterThan(0);
350+ expect(oldSmallScore).toBeGreaterThan(0);
351+ expect(oldSmallScore).toBeLessThan(1);
352+ });
353+});
354+
355+// Tests for setLogStats function
356+describe("setLogStats function", () => {
357+ const createCodeSnippet = (
358+ filepath: string,
359+ content: string,
360+ ): AutocompleteCodeSnippet => ({
361+ type: AutocompleteSnippetType.Code,
362+ filepath,
363+ content,
364+ });
365+
366+ test("should set logMin and logMax based on snippet sizes", () => {
367+ const snippets = [
368+ createCodeSnippet("small.ts", "a".repeat(50)),
369+ createCodeSnippet("medium.ts", "b".repeat(200)),
370+ createCodeSnippet("large.ts", "c".repeat(1000)),
371+ ];
372+
373+ // We can't directly test logMin and logMax as they're private
374+ // but we can verify that the function runs without errors
375+ expect(() => setLogStats(snippets)).not.toThrow();
376+ });
377+
378+ test("should handle empty snippets", () => {
379+ const emptySnippets = [
380+ createCodeSnippet("empty1.ts", ""),
381+ createCodeSnippet("empty2.ts", ""),
382+ ];
383+
384+ expect(() => setLogStats(emptySnippets)).not.toThrow();
385+ });
386+
387+ test("should handle single snippet", () => {
388+ const singleSnippet = [createCodeSnippet("single.ts", "content")];
389+
390+ expect(() => setLogStats(singleSnippet)).not.toThrow();
391+ });
392+});
393+
394+// Tests for trimSnippetForContext function
395+describe("trimSnippetForContext function", () => {
396+ const createCodeSnippet = (
397+ filepath: string,
398+ content: string,
399+ ): AutocompleteCodeSnippet => ({
400+ type: AutocompleteSnippetType.Code,
401+ filepath,
402+ content,
403+ });
404+
405+ test("should return original snippet if it fits within token limit", () => {
406+ const snippet = createCodeSnippet("small.ts", "small content");
407+ const modelName = "test-model";
408+ const maxTokens = 1000; // Large enough to fit the snippet
409+
410+ const result = trimSnippetForContext(snippet, maxTokens, modelName);
411+
412+ // Should return the original snippet with its token count
413+ expect(result.newSnippet).toEqual(snippet);
414+ expect(typeof result.newTokens).toBe("number");
415+ expect(result.newTokens).toBeGreaterThan(0);
416+ });
417+
418+ test("should trim snippet content if it exceeds token limit", () => {
419+ const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
420+ const modelName = "test-model";
421+ const maxTokens = 10; // Small enough to require trimming
422+
423+ const result = trimSnippetForContext(snippet, maxTokens, modelName);
424+
425+ // Should return a trimmed snippet
426+ expect(result.newSnippet.filepath).toBe(snippet.filepath);
427+ expect(result.newSnippet.type).toBe(snippet.type);
428+ expect(result.newSnippet.content.length).toBeLessThanOrEqual(
429+ snippet.content.length,
430+ );
431+
432+ // Token count should be less than or equal to maxTokens
433+ expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
434+ });
435+});
deleted core/autocomplete/util/completionTestUtils.test.ts +0 −65
@@ -1,65 +0,0 @@
1-import {
2- processTestCase,
3- type CompletionTestCase,
4-} from "./completionTestUtils";
5-
6-describe("processTestCase utility", () => {
7- it("processes simple console.log completion", () => {
8- const testCase: CompletionTestCase = {
9- original: "console.log(|cur||till|)",
10- completion: '"foo,", bar',
11- };
12-
13- expect(processTestCase(testCase)).toEqual({
14- input: {
15- lastLineOfCompletionText: '"foo,", bar',
16- currentText: ")",
17- cursorPosition: "console.log(".length,
18- },
19- expectedResult: {
20- completionText: '"foo,", bar',
21- },
22- });
23- });
24-
25- it("processes simple console.log completion with overwriting", () => {
26- const testCase: CompletionTestCase = {
27- original: "console.log(|cur|)|till|",
28- completion: '"foo,", bar);',
29- };
30-
31- expect(processTestCase(testCase)).toEqual({
32- input: {
33- lastLineOfCompletionText: '"foo,", bar);',
34- currentText: ")",
35- cursorPosition: "console.log(".length,
36- },
37- expectedResult: {
38- completionText: '"foo,", bar);',
39- range: {
40- start: "console.log(".length,
41- end: "console.log()".length,
42- },
43- },
44- });
45- });
46-
47- it("partially applying completion", () => {
48- const testCase: CompletionTestCase = {
49- original: '|cur||till|fetch("https://example.com");',
50- completion: 'await fetch("https://example.com");',
51- appliedCompletion: "await ",
52- };
53-
54- expect(processTestCase(testCase)).toEqual({
55- input: {
56- lastLineOfCompletionText: 'await fetch("https://example.com");',
57- currentText: 'fetch("https://example.com");',
58- cursorPosition: 0,
59- },
60- expectedResult: {
61- completionText: "await ",
62- },
63- });
64- });
65-});
added core/autocomplete/util/completionTestUtils.vitest.ts +66 −0
@@ -0,0 +1,66 @@
1+import { describe, expect, it } from "vitest";
2+import {
3+ processTestCase,
4+ type CompletionTestCase,
5+} from "./completionTestUtils";
6+
7+describe("processTestCase utility", () => {
8+ it("processes simple console.log completion", () => {
9+ const testCase: CompletionTestCase = {
10+ original: "console.log(|cur||till|)",
11+ completion: '"foo,", bar',
12+ };
13+
14+ expect(processTestCase(testCase)).toEqual({
15+ input: {
16+ lastLineOfCompletionText: '"foo,", bar',
17+ currentText: ")",
18+ cursorPosition: "console.log(".length,
19+ },
20+ expectedResult: {
21+ completionText: '"foo,", bar',
22+ },
23+ });
24+ });
25+
26+ it("processes simple console.log completion with overwriting", () => {
27+ const testCase: CompletionTestCase = {
28+ original: "console.log(|cur|)|till|",
29+ completion: '"foo,", bar);',
30+ };
31+
32+ expect(processTestCase(testCase)).toEqual({
33+ input: {
34+ lastLineOfCompletionText: '"foo,", bar);',
35+ currentText: ")",
36+ cursorPosition: "console.log(".length,
37+ },
38+ expectedResult: {
39+ completionText: '"foo,", bar);',
40+ range: {
41+ start: "console.log(".length,
42+ end: "console.log()".length,
43+ },
44+ },
45+ });
46+ });
47+
48+ it("partially applying completion", () => {
49+ const testCase: CompletionTestCase = {
50+ original: '|cur||till|fetch("https://example.com");',
51+ completion: 'await fetch("https://example.com");',
52+ appliedCompletion: "await ",
53+ };
54+
55+ expect(processTestCase(testCase)).toEqual({
56+ input: {
57+ lastLineOfCompletionText: 'await fetch("https://example.com");',
58+ currentText: 'fetch("https://example.com");',
59+ cursorPosition: 0,
60+ },
61+ expectedResult: {
62+ completionText: "await ",
63+ },
64+ });
65+ });
66+});
deleted core/autocomplete/util/processSingleLineCompletion.test.ts +0 −95
@@ -1,95 +0,0 @@
1-import { processTestCase } from "./completionTestUtils";
2-import { processSingleLineCompletion } from "./processSingleLineCompletion";
3-
4-describe("processSingleLineCompletion", () => {
5- it("should handle simple end of line completion", () => {
6- const testCase = processTestCase({
7- original: "console.log(|cur|",
8- completion: '"Hello, world!")',
9- });
10-
11- const result = processSingleLineCompletion(
12- testCase.input.lastLineOfCompletionText,
13- testCase.input.currentText,
14- testCase.input.cursorPosition,
15- );
16-
17- expect(result).toEqual(testCase.expectedResult);
18- });
19-
20- it("should handle midline insert repeating the end of line", () => {
21- const testCase = processTestCase({
22- original: "console.log(|cur|);|till|",
23- completion: '"Hello, world!");',
24- });
25-
26- const result = processSingleLineCompletion(
27- testCase.input.lastLineOfCompletionText,
28- testCase.input.currentText,
29- testCase.input.cursorPosition,
30- );
31-
32- expect(result).toEqual(testCase.expectedResult);
33- });
34-
35- it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
36- const testCase = processTestCase({
37- original: "console.log(|cur|)|till|",
38- completion: '"Hello, world!");',
39- });
40-
41- const result = processSingleLineCompletion(
42- testCase.input.lastLineOfCompletionText,
43- testCase.input.currentText,
44- testCase.input.cursorPosition,
45- );
46-
47- expect(result).toEqual(testCase.expectedResult);
48- });
49-
50- it("should handle simple midline insert", () => {
51- const testCase = processTestCase({
52- original: "console.log(|cur|)",
53- completion: '"Hello, world!"',
54- });
55-
56- const result = processSingleLineCompletion(
57- testCase.input.lastLineOfCompletionText,
58- testCase.input.currentText,
59- testCase.input.cursorPosition,
60- );
61-
62- expect(result).toEqual(testCase.expectedResult);
63- });
64-
65- it("should handle complex dif with addition in the beginning", () => {
66- const testCase = processTestCase({
67- original: 'console.log(|cur||till|, "param1", )', // TODO
68- completion: '"Hello world!", "param1", param1);',
69- appliedCompletion: '"Hello world!"',
70- });
71-
72- const result = processSingleLineCompletion(
73- testCase.input.lastLineOfCompletionText,
74- testCase.input.currentText,
75- testCase.input.cursorPosition,
76- );
77-
78- expect(result).toEqual(testCase.expectedResult);
79- });
80-
81- it("should handle simple insertion even with random equality", () => {
82- const testCase = processTestCase({
83- original: 'print(f"Foobar length: |cur||till|")',
84- completion: "{len(foobar)}",
85- });
86-
87- const result = processSingleLineCompletion(
88- testCase.input.lastLineOfCompletionText,
89- testCase.input.currentText,
90- testCase.input.cursorPosition,
91- );
92-
93- expect(result).toEqual(testCase.expectedResult);
94- });
95-});
added core/autocomplete/util/processSingleLineCompletion.vitest.ts +96 −0
@@ -0,0 +1,96 @@
1+import { describe, expect, it } from "vitest";
2+import { processTestCase } from "./completionTestUtils";
3+import { processSingleLineCompletion } from "./processSingleLineCompletion";
4+
5+describe("processSingleLineCompletion", () => {
6+ it("should handle simple end of line completion", () => {
7+ const testCase = processTestCase({
8+ original: "console.log(|cur|",
9+ completion: '"Hello, world!")',
10+ });
11+
12+ const result = processSingleLineCompletion(
13+ testCase.input.lastLineOfCompletionText,
14+ testCase.input.currentText,
15+ testCase.input.cursorPosition,
16+ );
17+
18+ expect(result).toEqual(testCase.expectedResult);
19+ });
20+
21+ it("should handle midline insert repeating the end of line", () => {
22+ const testCase = processTestCase({
23+ original: "console.log(|cur|);|till|",
24+ completion: '"Hello, world!");',
25+ });
26+
27+ const result = processSingleLineCompletion(
28+ testCase.input.lastLineOfCompletionText,
29+ testCase.input.currentText,
30+ testCase.input.cursorPosition,
31+ );
32+
33+ expect(result).toEqual(testCase.expectedResult);
34+ });
35+
36+ it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
37+ const testCase = processTestCase({
38+ original: "console.log(|cur|)|till|",
39+ completion: '"Hello, world!");',
40+ });
41+
42+ const result = processSingleLineCompletion(
43+ testCase.input.lastLineOfCompletionText,
44+ testCase.input.currentText,
45+ testCase.input.cursorPosition,
46+ );
47+
48+ expect(result).toEqual(testCase.expectedResult);
49+ });
50+
51+ it("should handle simple midline insert", () => {
52+ const testCase = processTestCase({
53+ original: "console.log(|cur|)",
54+ completion: '"Hello, world!"',
55+ });
56+
57+ const result = processSingleLineCompletion(
58+ testCase.input.lastLineOfCompletionText,
59+ testCase.input.currentText,
60+ testCase.input.cursorPosition,
61+ );
62+
63+ expect(result).toEqual(testCase.expectedResult);
64+ });
65+
66+ it("should handle complex dif with addition in the beginning", () => {
67+ const testCase = processTestCase({
68+ original: 'console.log(|cur||till|, "param1", )', // TODO
69+ completion: '"Hello world!", "param1", param1);',
70+ appliedCompletion: '"Hello world!"',
71+ });
72+
73+ const result = processSingleLineCompletion(
74+ testCase.input.lastLineOfCompletionText,
75+ testCase.input.currentText,
76+ testCase.input.cursorPosition,
77+ );
78+
79+ expect(result).toEqual(testCase.expectedResult);
80+ });
81+
82+ it("should handle simple insertion even with random equality", () => {
83+ const testCase = processTestCase({
84+ original: 'print(f"Foobar length: |cur||till|")',
85+ completion: "{len(foobar)}",
86+ });
87+
88+ const result = processSingleLineCompletion(
89+ testCase.input.lastLineOfCompletionText,
90+ testCase.input.currentText,
91+ testCase.input.cursorPosition,
92+ );
93+
94+ expect(result).toEqual(testCase.expectedResult);
95+ });
96+});
deleted core/config/markdown/createMarkdownRule.test.ts +0 −157
@@ -1,157 +0,0 @@
1-import {
2- createMarkdownWithFrontmatter,
3- createRuleFilePath,
4- createRuleMarkdown,
5- sanitizeRuleName,
6-} from "./createMarkdownRule";
7-import { parseMarkdownRule } from "./parseMarkdownRule";
8-
9-describe("sanitizeRuleName", () => {
10- it("should sanitize rule names for filenames", () => {
11- expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule");
12- expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars");
13- expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces");
14- expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule");
15- expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized");
16- });
17-
18- it("should handle empty and edge case inputs", () => {
19- expect(sanitizeRuleName("")).toBe("");
20- expect(sanitizeRuleName(" ")).toBe("");
21- expect(sanitizeRuleName("123")).toBe("123");
22- expect(sanitizeRuleName("rule-with-numbers-123")).toBe(
23- "rule-with-numbers-123",
24- );
25- });
26-});
27-
28-describe("createRuleFilePath", () => {
29- it("should create correct rule file path", () => {
30- const result = createRuleFilePath("/workspace", "My Test Rule");
31- expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
32- });
33-
34- it("should handle special characters in rule name", () => {
35- const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
36- expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
37- });
38-
39- it("should handle edge case rule names", () => {
40- const result = createRuleFilePath("/test", " Multiple Spaces ");
41- expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
42- });
43-});
44-
45-describe("createMarkdownWithFrontmatter", () => {
46- it("should create properly formatted markdown with frontmatter", () => {
47- const frontmatter = {
48- name: "Test Rule",
49- description: "A test rule",
50- globs: "*.ts",
51- };
52- const markdown = "# Test Rule\n\nThis is a test rule.";
53-
54- const result = createMarkdownWithFrontmatter(frontmatter, markdown);
55-
56- // The exact quote style doesn't matter as long as it parses correctly
57- expect(result).toContain("name: Test Rule");
58- expect(result).toContain("description: A test rule");
59- expect(result).toContain("globs:");
60- expect(result).toContain("*.ts");
61- expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule.");
62- });
63-
64- it("should handle empty frontmatter", () => {
65- const frontmatter = {};
66- const markdown = "# Simple Rule\n\nJust markdown content.";
67-
68- const result = createMarkdownWithFrontmatter(frontmatter, markdown);
69-
70- const expected = `---
71-{}
72----
73-
74-# Simple Rule
75-
76-Just markdown content.`;
77-
78- expect(result).toBe(expected);
79- });
80-
81- it("should create content that can be parsed back correctly", () => {
82- const originalFrontmatter = {
83- name: "Roundtrip Test",
84- description: "Testing roundtrip parsing",
85- globs: ["*.js", "*.ts"],
86- alwaysApply: true,
87- };
88- const originalMarkdown =
89- "# Roundtrip Test\n\nThis should parse back correctly.";
90-
91- const created = createMarkdownWithFrontmatter(
92- originalFrontmatter,
93- originalMarkdown,
94- );
95- const parsed = parseMarkdownRule(created);
96-
97- expect(parsed.frontmatter).toEqual(originalFrontmatter);
98- expect(parsed.markdown).toBe(originalMarkdown);
99- });
100-});
101-
102-describe("createRuleMarkdown", () => {
103- it("should create rule markdown with all options", () => {
104- const result = createRuleMarkdown("Test Rule", "This is the rule content", {
105- description: "Test description",
106- globs: ["*.ts", "*.js"],
107- alwaysApply: true,
108- });
109-
110- const parsed = parseMarkdownRule(result);
111-
112- expect(parsed.frontmatter.description).toBe("Test description");
113- expect(parsed.frontmatter.globs).toEqual(["*.ts", "*.js"]);
114- expect(parsed.frontmatter.alwaysApply).toBe(true);
115- expect(parsed.markdown).toBe("# Test Rule\n\nThis is the rule content");
116- });
117-
118- it("should create rule markdown with minimal options", () => {
119- const result = createRuleMarkdown("Simple Rule", "Simple content");
120-
121- const parsed = parseMarkdownRule(result);
122-
123- expect(parsed.frontmatter.description).toBeUndefined();
124- expect(parsed.frontmatter.globs).toBeUndefined();
125- expect(parsed.frontmatter.alwaysApply).toBeUndefined();
126- expect(parsed.markdown).toBe("# Simple Rule\n\nSimple content");
127- });
128-
129- it("should handle string globs", () => {
130- const result = createRuleMarkdown("String Glob Rule", "Content", {
131- globs: "*.py",
132- });
133-
134- const parsed = parseMarkdownRule(result);
135- expect(parsed.frontmatter.globs).toBe("*.py");
136- });
137-
138- it("should trim description and globs", () => {
139- const result = createRuleMarkdown("Trim Test", "Content", {
140- description: " spaced description ",
141- globs: " *.ts ",
142- });
143-
144- const parsed = parseMarkdownRule(result);
145- expect(parsed.frontmatter.description).toBe("spaced description");
146- expect(parsed.frontmatter.globs).toBe("*.ts");
147- });
148-
149- it("should handle alwaysApply false explicitly", () => {
150- const result = createRuleMarkdown("Always Apply False", "Content", {
151- alwaysApply: false,
152- });
153-
154- const parsed = parseMarkdownRule(result);
155- expect(parsed.frontmatter.alwaysApply).toBe(false);
156- });
157-});
deleted core/config/markdown/createMarkdownRule.ts +0 −75
@@ -1,75 +0,0 @@
1-import * as YAML from "yaml";
2-import { joinPathsToUri } from "../../util/uri";
3-import { RuleFrontmatter } from "./parseMarkdownRule";
4-
5-export const RULE_FILE_EXTENSION = "md";
6-
7-/**
8- * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes)
9- */
10-export function sanitizeRuleName(name: string): string {
11- return name
12- .toLowerCase()
13- .replace(/[^a-z0-9\s-]/g, "")
14- .replace(/\s+/g, "-")
15- .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes
16-}
17-
18-/**
19- * Creates the file path for a rule in the workspace .continue/rules directory
20- */
21-export function createRuleFilePath(
22- workspaceDir: string,
23- ruleName: string,
24-): string {
25- const safeRuleName = sanitizeRuleName(ruleName);
26- return joinPathsToUri(
27- workspaceDir,
28- ".continue",
29- "rules",
30- `${safeRuleName}.${RULE_FILE_EXTENSION}`,
31- );
32-}
33-
34-/**
35- * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule
36- */
37-export function createMarkdownWithFrontmatter(
38- frontmatter: RuleFrontmatter,
39- markdown: string,
40-): string {
41- const frontmatterStr = YAML.stringify(frontmatter).trim();
42- return `---\n${frontmatterStr}\n---\n\n${markdown}`;
43-}
44-
45-/**
46- * Creates a rule markdown file content from rule components
47- */
48-export function createRuleMarkdown(
49- name: string,
50- ruleContent: string,
51- options: {
52- description?: string;
53- globs?: string | string[];
54- alwaysApply?: boolean;
55- } = {},
56-): string {
57- const frontmatter: RuleFrontmatter = {};
58-
59- if (options.globs) {
60- frontmatter.globs =
61- typeof options.globs === "string" ? options.globs.trim() : options.globs;
62- }
63-
64- if (options.description) {
65- frontmatter.description = options.description.trim();
66- }
67-
68- if (options.alwaysApply !== undefined) {
69- frontmatter.alwaysApply = options.alwaysApply;
70- }
71-
72- const markdownBody = `# ${name}\n\n${ruleContent}`;
73-
74- return createMarkdownWithFrontmatter(frontmatter, markdownBody);
75-}
modified core/config/markdown/index.ts +0 −2
@@ -1,3 +1,1 @@
1-export * from "./createMarkdownRule";
21 export * from "./loadMarkdownRules";
3-export * from "./parseMarkdownRule";
modified core/config/markdown/loadCodebaseRules.ts +6 −4
@@ -1,9 +1,11 @@
1-import { ConfigValidationError } from "@continuedev/config-yaml";
1+import {
2+ ConfigValidationError,
3+ markdownToRule,
4+} from "@continuedev/config-yaml";
25 import { IDE, RuleWithSource } from "../..";
36 import { walkDirs } from "../../indexing/walkDir";
47 import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
58 import { getUriPathBasename } from "../../util/uri";
6-import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
79
810 /**
911 * Loads rules from rules.md files colocated in the codebase
@@ -29,9 +31,9 @@
2931 for (const filePath of rulesMdFiles) {
3032 try {
3133 const content = await ide.readFile(filePath);
32- const rule = convertMarkdownRuleToContinueRule(filePath, content);
34+ const rule = markdownToRule(content, { uriType: "file", filePath });
3335
34- rules.push(rule);
36+ rules.push({ ...rule, source: "rules-block" });
3537 } catch (e) {
3638 errors.push({
3739 fatal: false,
modified core/config/markdown/loadCodebaseRules.vitest.ts +8 −8
@@ -1,16 +1,16 @@
1+import { markdownToRule } from "@continuedev/config-yaml";
12 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23 import { IDE } from "../..";
34 import { walkDirs } from "../../indexing/walkDir";
45 import { loadCodebaseRules } from "./loadCodebaseRules";
5-import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
66
77 // Mock dependencies
88 vi.mock("../../indexing/walkDir", () => ({
99 walkDirs: vi.fn(),
1010 }));
1111
12-vi.mock("./parseMarkdownRule", () => ({
13- convertMarkdownRuleToContinueRule: vi.fn(),
12+vi.mock("@continuedev/config-yaml", () => ({
13+ markdownToRule: vi.fn(),
1414 }));
1515
1616 describe("loadCodebaseRules", () => {
@@ -82,10 +82,10 @@
8282 return Promise.resolve(mockRuleContent[path] || "");
8383 });
8484
85- // Mock convertMarkdownRuleToContinueRule to return converted rules
86- (convertMarkdownRuleToContinueRule as any).mockImplementation(
87- (path: string, content: string) => {
88- return mockConvertedRules[path];
85+ // Mock markdownToRule to return converted rules
86+ (markdownToRule as any).mockImplementation(
87+ (content: string, options: any) => {
88+ return mockConvertedRules[options.filePath];
8989 },
9090 );
9191 });
@@ -107,7 +107,7 @@
107107 expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
108108
109109 // Should convert all rules
110- expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4);
110+ expect(markdownToRule).toHaveBeenCalledTimes(4);
111111
112112 // Should return all rules
113113 expect(rules).toHaveLength(4);
modified core/config/markdown/loadMarkdownRules.ts +9 −4
@@ -1,7 +1,9 @@
1-import { ConfigValidationError } from "@continuedev/config-yaml";
1+import {
2+ ConfigValidationError,
3+ markdownToRule,
4+} from "@continuedev/config-yaml";
25 import { IDE, RuleWithSource } from "../..";
36 import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4-import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
57
68 /**
79 * Loads rules from markdown files in the .continue/rules directory
@@ -27,8 +29,11 @@
2729 // Process each markdown file
2830 for (const file of mdFiles) {
2931 try {
30- const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
31- rules.push(rule);
32+ const rule = markdownToRule(file.content, {
33+ uriType: "file",
34+ filePath: file.path,
35+ });
36+ rules.push({ ...rule, source: "rules-block" });
3237 } catch (e) {
3338 errors.push({
3439 fatal: false,
deleted core/config/markdown/parseMarkdownRule.test.ts +0 −192
@@ -1,192 +0,0 @@
1-import {
2- convertMarkdownRuleToContinueRule,
3- parseMarkdownRule,
4-} from "./parseMarkdownRule";
5-
6-describe("parseMarkdownRule", () => {
7- it("should correctly parse markdown with YAML frontmatter", () => {
8- const content = `---
9-globs: "**/test/**/*.kt"
10----
11-
12-# Test Rule
13-
14-This is a test rule.`;
15-
16- const result = parseMarkdownRule(content);
17- expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
18- expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
19- });
20-
21- it("should handle missing frontmatter", () => {
22- const content = `# Test Rule
23-
24-This is a test rule without frontmatter.`;
25-
26- const result = parseMarkdownRule(content);
27- expect(result.frontmatter).toEqual({});
28- expect(result.markdown).toBe(content);
29- });
30-
31- it("should handle empty frontmatter", () => {
32- const content = `---
33----
34-
35-# Test Rule
36-
37-This is a test rule with empty frontmatter.`;
38-
39- const result = parseMarkdownRule(content);
40-
41- // Log exact strings for debugging
42- console.log("Actual:", JSON.stringify(result.markdown));
43- console.log(
44- "Expected:",
45- JSON.stringify(
46- "# Test Rule\n\nThis is a test rule with empty frontmatter.",
47- ),
48- );
49-
50- expect(result.frontmatter).toEqual({});
51- expect(result.markdown).toBe(
52- "# Test Rule\n\nThis is a test rule with empty frontmatter.",
53- );
54- });
55-
56- it("should handle frontmatter with whitespace", () => {
57- const content = `---
58-globs: "**/test/**/*.kt"
59----
60-
61-# Test Rule
62-
63-This is a test rule.`;
64-
65- const result = parseMarkdownRule(content);
66- expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
67- expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
68- });
69-
70- it("should handle Windows line endings (CRLF)", () => {
71- // Using \r\n for CRLF line endings
72- const content = `---\r
73-globs: "**/test/**/*.kt"\r
74----\r
75-\r
76-# Test Rule\r
77-\r
78-This is a test rule.`;
79-
80- const result = parseMarkdownRule(content);
81- expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
82- // The result should be normalized to \n
83- expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
84- });
85-
86- it("should handle malformed frontmatter", () => {
87- const content = `---
88-globs: - "**/test/**/*.kt"
89-invalid: yaml: content
90----
91-
92-# Test Rule
93-
94-This is a test rule.`;
95-
96- // Should treat as only markdown when frontmatter is malformed
97- const result = parseMarkdownRule(content);
98- expect(result.frontmatter).toEqual({});
99- expect(result.markdown).toBe(content);
100- });
101-});
102-
103-describe("convertMarkdownRuleToContinueRule", () => {
104- it("should convert markdown with frontmatter to a rule", () => {
105- const content = `---
106-globs: "**/test/**/*.kt"
107-name: Custom Name
108----
109-
110-# Test Rule
111-
112-This is a test rule.`;
113-
114- const result = convertMarkdownRuleToContinueRule(
115- "/path/to/rule.md",
116- content,
117- );
118- expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
119- expect(result.globs).toBe("**/test/**/*.kt");
120- expect(result.name).toBe("Custom Name");
121- expect(result.source).toBe("rules-block");
122- expect(result.ruleFile).toBe("/path/to/rule.md");
123- });
124-
125- it("should use the first heading as name if not in frontmatter", () => {
126- const content = `---
127-globs: "**/test/**/*.kt"
128----
129-
130-# Test Rule Title
131-
132-This is a test rule.`;
133-
134- const result = convertMarkdownRuleToContinueRule(
135- "/path/to/rule.md",
136- content,
137- );
138- expect(result.name).toBe("Test Rule Title");
139- });
140-
141- it("should use filename as name if no heading or frontmatter name", () => {
142- const content = `---
143-globs: "**/test/**/*.kt"
144----
145-
146-This is a test rule without a heading.`;
147-
148- const result = convertMarkdownRuleToContinueRule(
149- "/path/to/custom-rule.md",
150- content,
151- );
152- expect(result.name).toBe("custom-rule");
153- });
154-
155- it("should include description from frontmatter", () => {
156- const content = `---
157-globs: "**/test/**/*.kt"
158-name: Test Rule
159-description: This is a rule description from frontmatter
160----
161-
162-# Test Rule
163-
164-This is the content of the rule.`;
165-
166- const result = convertMarkdownRuleToContinueRule(
167- "/path/to/rule.md",
168- content,
169- );
170- expect(result.description).toBe(
171- "This is a rule description from frontmatter",
172- );
173- });
174-
175- it("should include `alwaysApply` from frontmatter", () => {
176- const content = `---
177-globs: "**/test/**/*.kt"
178-name: Test Rule
179-alwaysApply: false
180----
181-
182-# Test Rule
183-
184-This is a rule with alwaysApply explicitly set to false.`;
185-
186- const result = convertMarkdownRuleToContinueRule(
187- "/path/to/rule.md",
188- content,
189- );
190- expect(result.alwaysApply).toBe(false);
191- });
192-});
deleted core/config/markdown/parseMarkdownRule.ts +0 −77
@@ -1,77 +0,0 @@
1-import { basename } from "path";
2-import * as YAML from "yaml";
3-import { RuleWithSource } from "../..";
4-
5-export interface RuleFrontmatter {
6- globs?: RuleWithSource["globs"];
7- name?: RuleWithSource["name"];
8- description?: RuleWithSource["description"];
9- alwaysApply?: RuleWithSource["alwaysApply"];
10-}
11-
12-/**
13- * Parses markdown content with YAML frontmatter
14- */
15-export function parseMarkdownRule(content: string): {
16- frontmatter: RuleFrontmatter;
17- markdown: string;
18-} {
19- // Normalize line endings to \n
20- const normalizedContent = content.replace(/\r\n/g, "\n");
21-
22- // More reliable frontmatter detection
23- const parts = normalizedContent.split(/^---\s*$/m);
24-
25- // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
26- if (parts.length >= 3) {
27- const frontmatterStr = parts[1];
28- // Join the remaining parts back together (in case there are more --- in the markdown)
29- const markdownContent = parts.slice(2).join("---");
30-
31- try {
32- // Parse YAML frontmatter
33- const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
34- return { frontmatter, markdown: markdownContent.trim() };
35- } catch (e) {
36- // Error parsing frontmatter, treat as markdown only
37- console.warn("Error parsing markdown frontmatter:", e);
38- return { frontmatter: {}, markdown: normalizedContent };
39- }
40- }
41-
42- // No frontmatter found
43- return { frontmatter: {}, markdown: normalizedContent };
44-}
45-
46-/**
47- * Converts a markdown file with YAML frontmatter to a RuleWithSource object
48- */
49-export function convertMarkdownRuleToContinueRule(
50- path: string,
51- content: string,
52-): RuleWithSource {
53- const { frontmatter, markdown } = parseMarkdownRule(content);
54-
55- // Try to extract title from first heading if no name in frontmatter
56- let name = frontmatter.name;
57- if (!name) {
58- // Look for a heading in the markdown
59- const headingMatch = markdown.match(/^#\s+(.+)$/m);
60- if (headingMatch) {
61- name = headingMatch[1].trim();
62- } else {
63- // Fall back to filename
64- name = basename(path).replace(/\.md$/, "");
65- }
66- }
67-
68- return {
69- name,
70- rule: markdown,
71- globs: frontmatter.globs,
72- description: frontmatter.description,
73- alwaysApply: frontmatter.alwaysApply,
74- source: "rules-block",
75- ruleFile: path,
76- };
77-}
added core/config/markdown/utils.ts +21 −0
@@ -0,0 +1,21 @@
1+import {
2+ RULE_FILE_EXTENSION,
3+ sanitizeRuleName,
4+} from "@continuedev/config-yaml";
5+import { joinPathsToUri } from "../../util/uri";
6+
7+/**
8+ * Creates the file path for a rule in the workspace .continue/rules directory
9+ */
10+export function createRuleFilePath(
11+ workspaceDir: string,
12+ ruleName: string,
13+): string {
14+ const safeRuleName = sanitizeRuleName(ruleName);
15+ return joinPathsToUri(
16+ workspaceDir,
17+ ".continue",
18+ "rules",
19+ `${safeRuleName}.${RULE_FILE_EXTENSION}`,
20+ );
21+}
added core/config/markdown/utils.vitest.ts +19 −0
@@ -0,0 +1,19 @@
1+import { describe, expect, it } from "vitest";
2+import { createRuleFilePath } from "./utils";
3+
4+describe("createRuleFilePath", () => {
5+ it("should create correct rule file path", () => {
6+ const result = createRuleFilePath("/workspace", "My Test Rule");
7+ expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
8+ });
9+
10+ it("should handle special characters in rule name", () => {
11+ const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
12+ expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
13+ });
14+
15+ it("should handle edge case rule names", () => {
16+ const result = createRuleFilePath("/test", " Multiple Spaces ");
17+ expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
18+ });
19+});
modified core/config/migrateSharedConfig.ts +1 −1
@@ -211,6 +211,6 @@
211211 new GlobalContext().updateSharedConfig(shareConfigUpdates);
212212 }
213213 } catch (e) {
214- throw new Error(`Migration: Failed to parse config.json: ${e}`);
214+ console.error(`Migration: Failed to parse config.json: ${e}`);
215215 }
216216 }
modified core/config/workspace/workspaceBlocks.test.ts +1 −3
@@ -1,12 +1,10 @@
1-import { BlockType } from "@continuedev/config-yaml";
1+import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
22 import { describe, expect, test } from "@jest/globals";
3-import { RULE_FILE_EXTENSION } from "../markdown";
43 import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
54
65 describe("getFileContent", () => {
76 test("returns markdown content for rules block type", () => {
87 const result = getFileContent("rules");
9- expect(result).toContain("# New Rule");
108 expect(result).toContain("Your rule content");
119 expect(result).toContain("A description of your rule");
1210 });
modified core/config/workspace/workspaceBlocks.ts +6 −2
@@ -1,8 +1,12 @@
1-import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
1+import {
2+ BlockType,
3+ ConfigYaml,
4+ createRuleMarkdown,
5+ RULE_FILE_EXTENSION,
6+} from "@continuedev/config-yaml";
27 import * as YAML from "yaml";
38 import { IDE } from "../..";
49 import { joinPathsToUri } from "../../util/uri";
5-import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown";
610
711 const BLOCK_TYPE_CONFIG: Record<
812 BlockType,
modified core/config/yaml/LocalPlatformClient.vitest.ts +0 −1
@@ -123,7 +123,6 @@
123123 expect(
124124 (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
125125 ).toBe(secretValue);
126- console.log("debug1 resolved fqsn", resolvedFQSNs);
127126 });
128127 });
129128
modified core/config/yaml/loadYaml.ts +1 −2
@@ -134,6 +134,7 @@
134134 rootPath,
135135 }),
136136 {
137+ renderSecrets: true,
137138 currentUserSlug: "",
138139 onPremProxyUrl: null,
139140 orgScopeId,
@@ -142,9 +143,7 @@
142143 controlPlaneClient,
143144 ide,
144145 ),
145- renderSecrets: true,
146146 injectBlocks: allLocalBlocks,
147- asConfigResult: true,
148147 },
149148 );
150149 config = unrollResult.config;
modified core/jest.config.js +1 −3
@@ -29,7 +29,5 @@
2929 globalSetup: "<rootDir>/test/jest.global-setup.ts",
3030 setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.js"],
3131 maxWorkers: 1, // equivalent to CLI --runInBand
32- modulePathIgnorePatterns: [
33- "<rootDir>/config/yaml/LocalPlatformClient.test.ts",
34- ],
32+ testMatch: ["**/*.test.ts"],
3533 };
modified core/llm/llm.test.ts +7 −21
@@ -161,12 +161,7 @@
161161 group: "Hello",
162162 },
163163 ],
164- toolChoice: {
165- type: "function",
166- function: {
167- name: "say_hello",
168- },
169- },
164+ toolChoice: { type: "function", function: { name: "say_hello" } },
170165 },
171166 )) {
172167 const typedChunk = chunk as AssistantChatMessage;
@@ -211,10 +206,7 @@
211206 model: "claude-3-5-sonnet-latest",
212207 apiKey: process.env.ANTHROPIC_API_KEY,
213208 }),
214- {
215- skip: false,
216- testToolCall: true,
217- },
209+ { skip: false, testToolCall: true },
218210 );
219211 testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), {
220212 skip: false,
@@ -240,12 +232,7 @@
240232 apiKey: process.env.MISTRAL_API_KEY,
241233 model: "codestral-latest",
242234 }),
243- {
244- testFim: true,
245- skip: false,
246- testToolCall: true,
247- timeout: 60000,
248- },
235+ { testFim: true, skip: false, testToolCall: true, timeout: 60000 },
249236 );
250237 testLLM(
251238 new Azure({
@@ -260,11 +247,10 @@
260247 );
261248 testLLM(
262249 new Azure({
263- apiKey: process.env.AZURE_FOUNDRY_API_KEY,
264- model: "codestral-latest",
265- apiBase:
266- "https://codestral-2501-continue-testing.eastus.models.ai.azure.com",
267- apiType: "azure-foundry",
250+ apiKey: process.env.AZURE_FOUNDRY_CODESTRAL_API_KEY,
251+ model: "Codestral-2501",
252+ apiBase: "https://continue-foundry-resource.services.ai.azure.com",
253+ env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" },
268254 }),
269255 { testFim: false, skip: false, timeout: 20000 },
270256 );
added core/test/vitest.global-setup.ts +11 −0
@@ -0,0 +1,11 @@
1+import fs from "fs";
2+import path from "path";
3+
4+// Sets up the GLOBAL directory for testing - equivalent to ~/.continue
5+// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths
6+export default async function () {
7+ process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
8+ if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
9+ fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
10+ }
11+}
added core/test/vitest.setup.ts +16 −0
@@ -0,0 +1,16 @@
1+import { TextDecoder, TextEncoder } from "util";
2+
3+import fetch, { Request, Response } from "node-fetch";
4+import { beforeAll } from "vitest";
5+
6+beforeAll(() => {
7+ // @ts-ignore
8+ globalThis.fetch = fetch;
9+ // @ts-ignore
10+ globalThis.Request = Request;
11+ // @ts-ignore
12+ globalThis.Response = Response;
13+ globalThis.TextEncoder = TextEncoder;
14+ // @ts-ignore
15+ globalThis.TextDecoder = TextDecoder;
16+});
modified core/tools/implementations/createRuleBlock.test.ts +1 −4
@@ -1,5 +1,5 @@
1+import { parseMarkdownRule } from "@continuedev/config-yaml";
12 import { jest } from "@jest/globals";
2-import { parseMarkdownRule } from "../../config/markdown";
33 import { createRuleBlockImpl } from "./createRuleBlock";
44
55 const mockIde = {
@@ -40,7 +40,6 @@
4040 globs: "**/*.{ts,tsx}",
4141 });
4242
43- expect(markdown).toContain("# TypeScript Rule");
4443 expect(markdown).toContain("Use interfaces for object shapes");
4544 });
4645
@@ -76,7 +75,6 @@
7675 description: "This is a detailed explanation of the rule",
7776 });
7877
79- expect(markdown).toContain("# Description Test");
8078 expect(markdown).toContain("This is the rule content");
8179 });
8280
@@ -100,7 +98,6 @@
10098 globs: "**/*.js",
10199 });
102100
103- expect(markdown).toContain("# Complete Rule");
104101 expect(markdown).toContain("Follow this standard");
105102 });
106103
modified core/tools/implementations/createRuleBlock.ts +2 −1
@@ -1,6 +1,7 @@
1+import { createRuleMarkdown } from "@continuedev/config-yaml";
12 import { ToolImpl } from ".";
23 import { RuleWithSource } from "../..";
3-import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown";
4+import { createRuleFilePath } from "../../config/markdown/utils";
45
56 export type CreateRuleBlockArgs = Pick<
67 Required<RuleWithSource>,
modified core/tools/implementations/requestRule.ts +3 −7
@@ -1,5 +1,4 @@
11 import { ToolImpl } from ".";
2-import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
32
43 export const requestRuleImpl: ToolImpl = async (args, extras) => {
54 // Find the rule by name in the config
@@ -11,14 +10,11 @@
1110 );
1211 }
1312
14- const fileContent = await extras.ide.readFile(rule.ruleFile);
15- const { markdown, frontmatter } = parseMarkdownRule(fileContent);
16-
1713 return [
1814 {
19- name: frontmatter.name ?? "",
20- description: frontmatter.description ?? "",
21- content: markdown,
15+ name: rule.name ?? "",
16+ description: rule.description ?? "",
17+ content: rule.rule,
2218 uri: {
2319 type: "file",
2420 value: rule.ruleFile,
modified core/util/shellPath.ts +3 −6
@@ -1,10 +1,6 @@
11 import { execSync } from "child_process";
2+import { homedir } from "os";
23
3-/**
4- * Gets the PATH env var from the user's login shell on non-Windows platforms.
5- * Windows is not implemented primarily because it is not needed at the moment.
6- * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined
7- */
84 export function getEnvPathFromUserShell(): string | undefined {
95 if (process.platform === "win32") {
106 console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`);
@@ -16,7 +12,8 @@
1612 }
1713
1814 try {
19- const command = `${process.env.SHELL} -l -c 'echo $PATH'`;
15+ // Source common profile files
16+ const command = `${process.env.SHELL} -l -c 'for f in ~/.zprofile ~/.zshrc ~/.bash_profile ~/.bashrc; do [ -f "$f" ] && source "$f" 2>/dev/null; done; echo $PATH'`;
2017
2118 const stdout = execSync(command, {
2219 encoding: "utf8",
modified core/util/treeSitter.ts +2 −2
@@ -181,7 +181,7 @@
181181 }
182182
183183 const sourcePath = path.join(
184- __dirname,
184+ process.env.NODE_ENV === "test" ? process.cwd() : __dirname,
185185 "..",
186186 ...(process.env.NODE_ENV === "test"
187187 ? ["extensions", "vscode", "tree-sitter"]
@@ -201,7 +201,7 @@
201201 fileExtension: string,
202202 ): Promise<Language> {
203203 const wasmPath = path.join(
204- __dirname,
204+ process.env.NODE_ENV === "test" ? process.cwd() : __dirname,
205205 ...(process.env.NODE_ENV === "test"
206206 ? ["node_modules", "tree-sitter-wasms", "out"]
207207 : ["tree-sitter-wasms"]),
modified core/vitest.config.ts +7 −0
@@ -2,6 +2,13 @@
22
33 export default defineConfig({
44 test: {
5+ testTransformMode: {
6+ web: ["/.[jt]s?$/"],
7+ ssr: ["/.[jt]s?$/"],
8+ },
9+ globalSetup: "./test/vitest.global-setup.ts",
10+ setupFiles: "./test/vitest.setup.ts",
11+ fileParallelism: false,
512 include: ["**/*.vitest.ts"],
613 },
714 });
modified docs/docs/customize/model-providers/more/vllm.mdx +2 −0
@@ -1,3 +1,5 @@
1+import TabItem from "@theme/TabItem";
2+import Tabs from "@theme/Tabs";
13
24 # vLLM
35
modified extensions/intellij/gradle.properties +1 −1
@@ -3,7 +3,7 @@
33 pluginName=continue-intellij-extension
44 pluginRepositoryUrl=https://github.com/continuedev/continue
55 # SemVer format -> https://semver.org
6-pluginVersion=1.0.23
6+pluginVersion=1.0.24
77 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
88 pluginSinceBuild=223
99 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/package.json +1 −1
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.48",
5+ "version": "1.1.49",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +0 −1
@@ -183,7 +183,6 @@
183183
184184 async refreshSessions() {
185185 try {
186- debugger;
187186 await this._refreshSessions();
188187 } catch (e) {
189188 console.error(`Error refreshing sessions: ${e}`);
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.88",
3+ "version": "1.0.92",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.88",
9+ "version": "1.0.92",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +8 −1
@@ -1,10 +1,17 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.88",
3+ "version": "1.0.92",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
77 "type": "module",
8+ "exports": {
9+ ".": {
10+ "browser": "./dist/browser.js",
11+ "node": "./dist/index.js",
12+ "default": "./dist/index.js"
13+ }
14+ },
815 "bin": {
916 "@continuedev/config-yaml": "./dist/cli.js"
1017 },
modified packages/config-yaml/src/__tests__/index.test.ts +16 −12
@@ -119,7 +119,7 @@
119119 },
120120 );
121121
122- expect(unrolledConfig.rules?.[0]).toBeNull();
122+ expect(unrolledConfig.config?.rules?.[0]).toBeNull();
123123 });
124124
125125 it("should correctly unroll assistant", async () => {
@@ -142,19 +142,21 @@
142142 },
143143 );
144144
145+ const config = unrolledConfig.config;
146+
145147 // Test that packages were correctly unrolled and params replaced
146- expect(unrolledConfig.models?.length).toBe(4);
148+ expect(config?.models?.length).toBe(4);
147149
148- const openAiModel = unrolledConfig.models?.[0]!;
150+ const openAiModel = config?.models?.[0]!;
149151 expect(openAiModel.apiKey).toBe("sk-123");
150152
151- const geminiModel = unrolledConfig.models?.[1]!;
153+ const geminiModel = config?.models?.[1]!;
152154 expect(geminiModel.provider).toBe("continue-proxy");
153155 expect(geminiModel.apiKey).toBeUndefined();
154156 const geminiSecretLocation = "organization:test-org/GEMINI_API_KEY";
155157 expect((geminiModel as any).apiKeyLocation).toBe(geminiSecretLocation);
156158
157- const anthropicModel = unrolledConfig.models?.[2]!;
159+ const anthropicModel = config?.models?.[2]!;
158160 expect(anthropicModel.provider).toBe("continue-proxy");
159161 expect(anthropicModel.apiKey).toBeUndefined();
160162 const anthropicSecretLocation =
@@ -163,15 +165,15 @@
163165 anthropicSecretLocation,
164166 );
165167
166- const proxyOllamaModel = unrolledConfig.models?.[3]!;
168+ const proxyOllamaModel = config?.models?.[3]!;
167169 expect(proxyOllamaModel.provider).toBe("ollama");
168170 expect(proxyOllamaModel.defaultCompletionOptions?.stream).toBe(false);
169171
170- expect(unrolledConfig.rules?.length).toBe(2);
171- expect(unrolledConfig.docs?.[0]?.startUrl).toBe(
172+ expect(config?.rules?.length).toBe(2);
173+ expect(config?.docs?.[0]?.startUrl).toBe(
172174 "https://docs.python.org/release/3.13.1",
173175 );
174- expect(unrolledConfig.docs?.[0]?.rootUrl).toBe(
176+ expect(config?.docs?.[0]?.rootUrl).toBe(
175177 "https://docs.python.org/release/3.13.1",
176178 );
177179
@@ -242,16 +244,18 @@
242244 },
243245 );
244246
247+ const config = unrolledConfig.config;
248+
245249 // The original rules array should have two items
246- expect(unrolledConfig.rules?.length).toBe(3); // Now 3 with the injected block
250+ expect(config?.rules?.length).toBe(3); // Now 3 with the injected block
247251
248252 // Check the original doc is still there
249- expect(unrolledConfig.docs?.[0]?.startUrl).toBe(
253+ expect(config?.docs?.[0]?.startUrl).toBe(
250254 "https://docs.python.org/release/3.13.1",
251255 );
252256
253257 // Check the injected doc block was added
254- expect(unrolledConfig.rules?.[2]).toBe("Be kind");
258+ expect(config?.rules?.[2]).toBe("Be kind");
255259 });
256260
257261 it.skip("should prioritize org over user / package secrets", () => {});
added packages/config-yaml/src/browser.ts +18 −0
@@ -0,0 +1,18 @@
1+// Browser-compatible exports (excludes RegistryClient which uses Node.js APIs)
2+export * from "./converter.js";
3+export * from "./interfaces/index.js";
4+export * from "./interfaces/SecretResult.js";
5+export * from "./interfaces/slugs.js";
6+export * from "./load/clientRender.js";
7+export * from "./load/getBlockType.js";
8+export * from "./load/merge.js";
9+export * from "./load/proxySecretResolution.js";
10+export * from "./load/typeGuards.js";
11+export * from "./load/unroll.js";
12+export * from "./markdown/index.js";
13+export * from "./modelName.js";
14+// Note: registryClient.js is excluded because it uses Node.js fs/path APIs
15+export * from "./schemas/data/index.js";
16+export * from "./schemas/index.js";
17+export * from "./schemas/models.js";
18+export * from "./validation.js";
modified packages/config-yaml/src/index.ts +1 −15
@@ -1,16 +1,2 @@
1-export * from "./converter.js";
2-export * from "./interfaces/index.js";
3-export * from "./interfaces/SecretResult.js";
4-export * from "./interfaces/slugs.js";
5-export * from "./load/clientRender.js";
6-export * from "./load/getBlockType.js";
7-export * from "./load/merge.js";
8-export * from "./load/proxySecretResolution.js";
9-export * from "./load/typeGuards.js";
10-export * from "./load/unroll.js";
11-export * from "./modelName.js";
1+export * from "./browser.js";
122 export * from "./registryClient.js";
13-export * from "./schemas/data/index.js";
14-export * from "./schemas/index.js";
15-export * from "./schemas/models.js";
16-export * from "./validation.js";
modified packages/config-yaml/src/interfaces/slugs.ts +9 −0
@@ -25,6 +25,15 @@
2525
2626 export type PackageIdentifier = FullSlugIdentifier | FileIdentifier;
2727
28+export function packageIdentifierToDisplayName(id: PackageIdentifier): string {
29+ switch (id.uriType) {
30+ case "file":
31+ return id.filePath;
32+ case "slug":
33+ return id.fullSlug.packageSlug;
34+ }
35+}
36+
2837 export function encodePackageIdentifier(identifier: PackageIdentifier): string {
2938 switch (identifier.uriType) {
3039 case "slug":
modified packages/config-yaml/src/load/unroll.ts +87 −56
@@ -9,6 +9,7 @@
99 FQSN,
1010 PackageIdentifier,
1111 } from "../interfaces/slugs.js";
12+import { markdownToRule } from "../markdown/index.js";
1213 import {
1314 AssistantUnrolled,
1415 assistantUnrolledSchema,
@@ -195,7 +196,6 @@
195196 export interface BaseUnrollAssistantOptions {
196197 renderSecrets: boolean;
197198 injectBlocks?: PackageIdentifier[];
198- asConfigResult?: true;
199199 }
200200
201201 export interface DoNotRenderSecretsUnrollAssistantOptions
@@ -217,24 +217,11 @@
217217 | DoNotRenderSecretsUnrollAssistantOptions
218218 | RenderSecretsUnrollAssistantOptions;
219219
220-// Overload to satisfy existing consumers of unrollAssistant.
221-export async function unrollAssistant(
222- id: PackageIdentifier,
223- registry: Registry,
224- options: UnrollAssistantOptions & { asConfigResult: true },
225-): Promise<ConfigResult<AssistantUnrolled>>;
226-
227-export async function unrollAssistant(
228- id: PackageIdentifier,
229- registry: Registry,
230- options: UnrollAssistantOptions,
231-): Promise<AssistantUnrolled>;
232-
233220 export async function unrollAssistant(
234221 id: PackageIdentifier,
235222 registry: Registry,
236223 options: UnrollAssistantOptions,
237-): Promise<AssistantUnrolled | ConfigResult<AssistantUnrolled>> {
224+): Promise<ConfigResult<AssistantUnrolled>> {
238225 // Request the content from the registry
239226 const rawContent = await registry.getContent(id);
240227
@@ -265,24 +252,19 @@
265252 rawYaml: string,
266253 registry: Registry,
267254 options: UnrollAssistantOptions,
268-): Promise<AssistantUnrolled | ConfigResult<AssistantUnrolled>> {
255+): Promise<ConfigResult<AssistantUnrolled>> {
269256 // Parse string to Zod-validated YAML
270257 let parsedYaml = parseConfigYaml(rawYaml);
271258
272259 // Unroll blocks and convert their secrets to FQSNs
273- const unrolledAssistant = await unrollBlocks(
274- parsedYaml,
275- registry,
276- options.injectBlocks,
277- options.asConfigResult ?? false,
278- );
260+ const {
261+ config: unrolledAssistant,
262+ configLoadInterrupted,
263+ errors,
264+ } = await unrollBlocks(parsedYaml, registry, options.injectBlocks);
279265
280266 // Back to a string so we can fill in template variables
281- const rawUnrolledYaml = options.asConfigResult
282- ? YAML.stringify(
283- (unrolledAssistant as ConfigResult<AssistantUnrolled>).config,
284- )
285- : YAML.stringify(unrolledAssistant);
267+ const rawUnrolledYaml = YAML.stringify(unrolledAssistant);
286268
287269 // Convert all of the template variables to FQSNs
288270 // Secrets from the block will have the assistant slug prepended to the FQSN
@@ -291,7 +273,11 @@
291273 });
292274
293275 if (!options.renderSecrets) {
294- return parseAssistantUnrolled(templatedYaml);
276+ return {
277+ config: parseAssistantUnrolled(templatedYaml),
278+ errors: [],
279+ configLoadInterrupted: false,
280+ };
295281 }
296282
297283 // Render secret values/locations for client
@@ -312,25 +298,18 @@
312298 options.onPremProxyUrl,
313299 );
314300
315- if (options.asConfigResult) {
316- return {
317- config: finalConfig,
318- errors: (unrolledAssistant as ConfigResult<AssistantUnrolled>).errors,
319- configLoadInterrupted: (
320- unrolledAssistant as ConfigResult<AssistantUnrolled>
321- ).configLoadInterrupted,
322- };
323- }
324-
325- return finalConfig;
301+ return {
302+ config: finalConfig,
303+ errors,
304+ configLoadInterrupted,
305+ };
326306 }
327307
328308 export async function unrollBlocks(
329309 assistant: ConfigYaml,
330310 registry: Registry,
331311 injectBlocks: PackageIdentifier[] | undefined,
332- asConfigError: boolean,
333-): Promise<AssistantUnrolled | ConfigResult<AssistantUnrolled>> {
312+): Promise<ConfigResult<AssistantUnrolled>> {
334313 const errors: ConfigValidationError[] = [];
335314
336315 const unrolledAssistant: AssistantUnrolled = {
@@ -432,7 +411,10 @@
432411 for (const injectBlock of injectBlocks ?? []) {
433412 try {
434413 const blockConfigYaml = await registry.getContent(injectBlock);
435- const parsedBlock = parseConfigYaml(blockConfigYaml);
414+ const parsedBlock = parseMarkdownRuleOrConfigYaml(
415+ blockConfigYaml,
416+ injectBlock,
417+ );
436418 const blockType = getBlockType(parsedBlock);
437419 const resolvedBlock = await resolveBlock(
438420 injectBlock,
@@ -466,20 +448,16 @@
466448 }
467449 }
468450
469- if (asConfigError) {
470- const configResult: ConfigResult<AssistantUnrolled> = {
471- config: undefined,
472- errors: undefined,
473- configLoadInterrupted: false,
474- };
475- configResult.config = unrolledAssistant;
476- if (errors.length > 0) {
477- configResult.errors = errors;
478- }
479- return configResult;
451+ const configResult: ConfigResult<AssistantUnrolled> = {
452+ config: undefined,
453+ errors: undefined,
454+ configLoadInterrupted: false,
455+ };
456+ configResult.config = unrolledAssistant;
457+ if (errors.length > 0) {
458+ configResult.errors = errors;
480459 }
481-
482- return unrolledAssistant;
460+ return configResult;
483461 }
484462
485463 export async function resolveBlock(
@@ -503,7 +481,60 @@
503481 secrets: extractFQSNMap(rawYaml, [id]),
504482 });
505483
506- const parsedYaml = parseBlock(templatedYaml);
484+ return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
485+}
486+
487+function parseMarkdownRuleOrAssistantUnrolled(
488+ content: string,
489+ id: PackageIdentifier,
490+): AssistantUnrolled {
491+ // Try to parse as YAML first, then as markdown rule if that fails
492+ let parsedYaml: AssistantUnrolled;
493+ try {
494+ parsedYaml = parseBlock(content);
495+ } catch (yamlError) {
496+ // If YAML parsing fails, try parsing as markdown rule
497+ try {
498+ const rule = markdownToRule(content, id);
499+ // Convert the rule object to the expected format
500+ parsedYaml = {
501+ name: rule.name,
502+ version: "1.0.0",
503+ rules: [rule],
504+ };
505+ } catch (markdownError) {
506+ // If both fail, throw the original YAML error
507+ throw yamlError;
508+ }
509+ }
510+
511+ return parsedYaml;
512+}
513+
514+function parseMarkdownRuleOrConfigYaml(
515+ content: string,
516+ id: PackageIdentifier,
517+): ConfigYaml {
518+ // Try to parse as YAML first, then as markdown rule if that fails
519+ let parsedYaml: ConfigYaml;
520+ try {
521+ parsedYaml = parseConfigYaml(content);
522+ } catch (yamlError) {
523+ // If YAML parsing fails, try parsing as markdown rule
524+ try {
525+ const rule = markdownToRule(content, id);
526+ // Convert the rule object to the expected format
527+ parsedYaml = {
528+ name: rule.name,
529+ version: "1.0.0",
530+ rules: [rule],
531+ };
532+ } catch (markdownError) {
533+ // If both fail, throw the original YAML error
534+ throw yamlError;
535+ }
536+ }
537+
507538 return parsedYaml;
508539 }
509540
added packages/config-yaml/src/markdown/createMarkdownRule.test.ts +149 −0
@@ -0,0 +1,149 @@
1+import { PackageIdentifier } from "../browser.js";
2+import {
3+ createMarkdownWithFrontmatter,
4+ createRuleMarkdown,
5+ sanitizeRuleName,
6+} from "./createMarkdownRule.js";
7+import { markdownToRule } from "./markdownToRule.js";
8+
9+// Mock package identifier for testing
10+const mockPackageId: PackageIdentifier = {
11+ uriType: "file",
12+ filePath: "/path/to/file",
13+};
14+
15+describe("sanitizeRuleName", () => {
16+ it("should sanitize rule names for filenames", () => {
17+ expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule");
18+ expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars");
19+ expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces");
20+ expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule");
21+ expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized");
22+ });
23+
24+ it("should handle empty and edge case inputs", () => {
25+ expect(sanitizeRuleName("")).toBe("");
26+ expect(sanitizeRuleName(" ")).toBe("");
27+ expect(sanitizeRuleName("123")).toBe("123");
28+ expect(sanitizeRuleName("rule-with-numbers-123")).toBe(
29+ "rule-with-numbers-123",
30+ );
31+ });
32+});
33+
34+describe("createMarkdownWithFrontmatter", () => {
35+ it("should create properly formatted markdown with frontmatter", () => {
36+ const frontmatter = {
37+ name: "Test Rule",
38+ description: "A test rule",
39+ globs: "*.ts",
40+ };
41+ const markdown = "# Test Rule\n\nThis is a test rule.";
42+
43+ const result = createMarkdownWithFrontmatter(frontmatter, markdown);
44+
45+ // The exact quote style doesn't matter as long as it parses correctly
46+ expect(result).toContain("name: Test Rule");
47+ expect(result).toContain("description: A test rule");
48+ expect(result).toContain("globs:");
49+ expect(result).toContain("*.ts");
50+ expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule.");
51+ });
52+
53+ it("should handle empty frontmatter", () => {
54+ const frontmatter = {};
55+ const markdown = "# Simple Rule\n\nJust markdown content.";
56+
57+ const result = createMarkdownWithFrontmatter(frontmatter, markdown);
58+
59+ const expected = `---
60+{}
61+---
62+
63+# Simple Rule
64+
65+Just markdown content.`;
66+
67+ expect(result).toBe(expected);
68+ });
69+
70+ it("should create content that can be parsed back correctly", () => {
71+ const originalFrontmatter = {
72+ name: "Roundtrip Test",
73+ description: "Testing roundtrip parsing",
74+ globs: ["*.js", "*.ts"],
75+ alwaysApply: true,
76+ };
77+ const originalMarkdown =
78+ "# Roundtrip Test\n\nThis should parse back correctly.";
79+
80+ const created = createMarkdownWithFrontmatter(
81+ originalFrontmatter,
82+ originalMarkdown,
83+ );
84+ const parsed = markdownToRule(created, mockPackageId);
85+
86+ expect(parsed.name).toBe(originalFrontmatter.name);
87+ expect(parsed.description).toBe(originalFrontmatter.description);
88+ expect(parsed.globs).toEqual(originalFrontmatter.globs);
89+ expect(parsed.alwaysApply).toBe(originalFrontmatter.alwaysApply);
90+ expect(parsed.rule).toBe(originalMarkdown);
91+ });
92+});
93+
94+describe("createRuleMarkdown", () => {
95+ it("should create rule markdown with all options", () => {
96+ const result = createRuleMarkdown("Test Rule", "This is the rule content", {
97+ description: "Test description",
98+ globs: ["*.ts", "*.js"],
99+ alwaysApply: true,
100+ });
101+
102+ const parsed = markdownToRule(result, mockPackageId);
103+
104+ expect(parsed.description).toBe("Test description");
105+ expect(parsed.globs).toEqual(["*.ts", "*.js"]);
106+ expect(parsed.alwaysApply).toBe(true);
107+ expect(parsed.rule).toBe("This is the rule content");
108+ });
109+
110+ it("should create rule markdown with minimal options", () => {
111+ const result = createRuleMarkdown("Simple Rule", "Simple content");
112+
113+ const parsed = markdownToRule(result, mockPackageId);
114+
115+ expect(parsed.description).toBeUndefined();
116+ expect(parsed.globs).toBeUndefined();
117+ expect(parsed.alwaysApply).toBeUndefined();
118+ expect(parsed.rule).toBe("Simple content");
119+ });
120+
121+ it("should handle string globs", () => {
122+ const result = createRuleMarkdown("String Glob Rule", "Content", {
123+ globs: "*.py",
124+ });
125+
126+ const parsed = markdownToRule(result, mockPackageId);
127+ expect(parsed.globs).toBe("*.py");
128+ });
129+
130+ it("should trim description and globs", () => {
131+ const result = createRuleMarkdown("Trim Test", "Content", {
132+ description: " spaced description ",
133+ globs: " *.ts ",
134+ });
135+
136+ const parsed = markdownToRule(result, mockPackageId);
137+ expect(parsed.description).toBe("spaced description");
138+ expect(parsed.globs).toBe("*.ts");
139+ });
140+
141+ it("should handle alwaysApply false explicitly", () => {
142+ const result = createRuleMarkdown("Always Apply False", "Content", {
143+ alwaysApply: false,
144+ });
145+
146+ const parsed = markdownToRule(result, mockPackageId);
147+ expect(parsed.alwaysApply).toBe(false);
148+ });
149+});
added packages/config-yaml/src/markdown/createMarkdownRule.ts +56 −0
@@ -0,0 +1,56 @@
1+import * as YAML from "yaml";
2+import { RuleFrontmatter } from "./markdownToRule.js";
3+
4+export const RULE_FILE_EXTENSION = "md";
5+
6+/**
7+ * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes)
8+ */
9+export function sanitizeRuleName(name: string): string {
10+ return name
11+ .toLowerCase()
12+ .replace(/[^a-z0-9\s-]/g, "")
13+ .replace(/\s+/g, "-")
14+ .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes
15+}
16+
17+/**
18+ * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule
19+ */
20+export function createMarkdownWithFrontmatter(
21+ frontmatter: RuleFrontmatter,
22+ markdown: string,
23+): string {
24+ const frontmatterStr = YAML.stringify(frontmatter).trim();
25+ return `---\n${frontmatterStr}\n---\n\n${markdown}`;
26+}
27+
28+/**
29+ * Creates a rule markdown file content from rule components
30+ */
31+export function createRuleMarkdown(
32+ name: string,
33+ ruleContent: string,
34+ options: {
35+ description?: string;
36+ globs?: string | string[];
37+ alwaysApply?: boolean;
38+ } = {},
39+): string {
40+ const frontmatter: RuleFrontmatter = {};
41+
42+ if (options.globs) {
43+ frontmatter.globs =
44+ typeof options.globs === "string" ? options.globs.trim() : options.globs;
45+ }
46+
47+ if (options.description) {
48+ frontmatter.description = options.description.trim();
49+ }
50+
51+ if (options.alwaysApply !== undefined) {
52+ frontmatter.alwaysApply = options.alwaysApply;
53+ }
54+
55+ return createMarkdownWithFrontmatter(frontmatter, ruleContent);
56+}
added packages/config-yaml/src/markdown/index.ts +2 −0
@@ -0,0 +1,2 @@
1+export * from "./createMarkdownRule.js";
2+export * from "./markdownToRule.js";
added packages/config-yaml/src/markdown/markdownToRule.test.ts +173 −0
@@ -0,0 +1,173 @@
1+import { PackageIdentifier } from "../browser.js";
2+import { markdownToRule } from "./markdownToRule.js";
3+
4+describe("markdownToRule", () => {
5+ // Use a mock PackageIdentifier for testing
6+ const mockId: PackageIdentifier = {
7+ uriType: "file",
8+ filePath: "/path/to/file",
9+ };
10+
11+ it("should convert markdown with frontmatter to a rule", () => {
12+ const content = `---
13+globs: "**/test/**/*.kt"
14+name: Custom Name
15+---
16+
17+# Test Rule
18+
19+This is a test rule.`;
20+
21+ const result = markdownToRule(content, mockId);
22+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
23+ expect(result.globs).toBe("**/test/**/*.kt");
24+ expect(result.name).toBe("Custom Name");
25+ });
26+
27+ it("should correctly parse markdown with YAML frontmatter", () => {
28+ const content = `---
29+globs: "**/test/**/*.kt"
30+---
31+
32+# Test Rule
33+
34+This is a test rule.`;
35+
36+ const result = markdownToRule(content, mockId);
37+ expect(result.globs).toBe("**/test/**/*.kt");
38+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
39+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
40+ });
41+
42+ it("should handle missing frontmatter", () => {
43+ const content = `# Test Rule
44+
45+This is a test rule without frontmatter.`;
46+
47+ const result = markdownToRule(content, mockId);
48+ expect(result.globs).toBeUndefined();
49+ expect(result.rule).toBe(content);
50+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
51+ });
52+
53+ it("should handle empty frontmatter", () => {
54+ const content = `---
55+---
56+
57+# Test Rule
58+
59+This is a test rule with empty frontmatter.`;
60+
61+ const result = markdownToRule(content, mockId);
62+ expect(result.globs).toBeUndefined();
63+ expect(result.rule).toBe(
64+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
65+ );
66+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
67+ });
68+
69+ it("should handle frontmatter with whitespace", () => {
70+ const content = `---
71+globs: "**/test/**/*.kt"
72+---
73+
74+# Test Rule
75+
76+This is a test rule.`;
77+
78+ const result = markdownToRule(content, mockId);
79+ expect(result.globs).toBe("**/test/**/*.kt");
80+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
81+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
82+ });
83+
84+ it("should handle Windows line endings (CRLF)", () => {
85+ // Using \r\n for CRLF line endings
86+ const content = `---\r
87+globs: "**/test/**/*.kt"\r
88+---\r
89+\r
90+# Test Rule\r
91+\r
92+This is a test rule.`;
93+
94+ const result = markdownToRule(content, mockId);
95+ expect(result.globs).toBe("**/test/**/*.kt");
96+ // The result should be normalized to \n
97+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
98+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
99+ });
100+
101+ it("should handle malformed frontmatter", () => {
102+ const content = `---
103+globs: - "**/test/**/*.kt"
104+invalid: yaml: content
105+---
106+
107+# Test Rule
108+
109+This is a test rule.`;
110+
111+ // Should treat as only markdown when frontmatter is malformed
112+ const result = markdownToRule(content, mockId);
113+ expect(result.globs).toBeUndefined();
114+ expect(result.rule).toBe(content);
115+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
116+ });
117+
118+ it("should use packageIdentifierToDisplayName if no heading or frontmatter name", () => {
119+ const content = `---
120+globs: "**/test/**/*.kt"
121+---
122+
123+# Test Rule Title
124+
125+This is a test rule.`;
126+
127+ const result = markdownToRule(content, mockId);
128+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
129+ });
130+
131+ it("should use packageIdentifierToDisplayName if no heading or frontmatter name (no heading)", () => {
132+ const content = `---
133+globs: "**/test/**/*.kt"
134+---
135+
136+This is a test rule without a heading.`;
137+
138+ const result = markdownToRule(content, mockId);
139+ expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
140+ });
141+
142+ it("should include description from frontmatter", () => {
143+ const content = `---
144+globs: "**/test/**/*.kt"
145+name: Test Rule
146+description: This is a rule description from frontmatter
147+---
148+
149+# Test Rule
150+
151+This is the content of the rule.`;
152+
153+ const result = markdownToRule(content, mockId);
154+ expect(result.description).toBe(
155+ "This is a rule description from frontmatter",
156+ );
157+ });
158+
159+ it("should include alwaysApply from frontmatter", () => {
160+ const content = `---
161+globs: "**/test/**/*.kt"
162+name: Test Rule
163+alwaysApply: false
164+---
165+
166+# Test Rule
167+
168+This is a rule with alwaysApply explicitly set to false.`;
169+
170+ const result = markdownToRule(content, mockId);
171+ expect(result.alwaysApply).toBe(false);
172+ });
173+});
added packages/config-yaml/src/markdown/markdownToRule.ts +62 −0
@@ -0,0 +1,62 @@
1+import * as YAML from "yaml";
2+import {
3+ PackageIdentifier,
4+ packageIdentifierToDisplayName,
5+} from "../browser.js";
6+import { RuleObject } from "../schemas/index.js";
7+
8+export interface RuleFrontmatter {
9+ globs?: RuleObject["globs"];
10+ name?: RuleObject["name"];
11+ description?: RuleObject["description"];
12+ alwaysApply?: RuleObject["alwaysApply"];
13+}
14+
15+/**
16+ * Parses markdown content with YAML frontmatter
17+ */
18+export function parseMarkdownRule(content: string): {
19+ frontmatter: RuleFrontmatter;
20+ markdown: string;
21+} {
22+ // Normalize line endings to \n
23+ const normalizedContent = content.replace(/\r\n/g, "\n");
24+
25+ // More reliable frontmatter detection
26+ const parts = normalizedContent.split(/^---\s*$/m);
27+
28+ // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
29+ if (parts.length >= 3) {
30+ const frontmatterStr = parts[1];
31+ // Join the remaining parts back together (in case there are more --- in the markdown)
32+ const markdownContent = parts.slice(2).join("---");
33+
34+ try {
35+ // Parse YAML frontmatter
36+ const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
37+ return { frontmatter, markdown: markdownContent.trim() };
38+ } catch (e) {
39+ // Error parsing frontmatter, treat as markdown only
40+ console.warn("Error parsing markdown frontmatter:", e);
41+ return { frontmatter: {}, markdown: normalizedContent };
42+ }
43+ }
44+
45+ // No frontmatter found
46+ return { frontmatter: {}, markdown: normalizedContent };
47+}
48+
49+export function markdownToRule(
50+ rule: string,
51+ id: PackageIdentifier,
52+): RuleObject {
53+ const { frontmatter, markdown } = parseMarkdownRule(rule);
54+
55+ return {
56+ name: frontmatter.name ?? packageIdentifierToDisplayName(id),
57+ rule: markdown,
58+ globs: frontmatter.globs,
59+ description: frontmatter.description,
60+ alwaysApply: frontmatter.alwaysApply,
61+ };
62+}
modified packages/config-yaml/src/schemas/index.ts +16 −0
@@ -39,6 +39,7 @@
3939 });
4040
4141 export type DocsConfig = z.infer<typeof docSchema>;
42+
4243 const ruleObjectSchema = z.object({
4344 name: z.string(),
4445 rule: z.string(),
@@ -48,8 +49,23 @@
4849 });
4950 const ruleSchema = z.union([z.string(), ruleObjectSchema]);
5051
52+/**
53+ * A schema for rules.json files
54+ */
55+export const rulesJsonSchema = z.object({
56+ name: z.string(),
57+ version: z.string(),
58+ author: z.string().optional(),
59+ license: z.string().optional(),
60+ rules: z.record(z.string(), z.string()).optional(),
61+});
62+
5163 export type Rule = z.infer<typeof ruleSchema>;
5264 export type RuleObject = z.infer<typeof ruleObjectSchema>;
65+/**
66+ * A schema for rules.json files
67+ */
68+export type RulesJson = z.infer<typeof rulesJsonSchema>;
5369
5470 const defaultUsesSchema = z.string();
5571
modified packages/continue-sdk/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.