Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into bdougie/docs-structure
Changesetc59237235e7eaa22ea744e509ae9c0125a0fdfe43c91f900e4e5840eac551933
AuthorBrian 'bdougie' Douglas <brian@opensauced.pizza> · 2025-07-01 17:57 -07:00
CommitterBrian 'bdougie' Douglas <brian@opensauced.pizza> · 2025-07-01 17:57 -07:00
Parents25bfc51fbbeb, 7485605fa121

Browse the files at this changeset

123 files changed

modified core/autocomplete/constants/AutocompleteLanguageInfo.ts +33 −1
@@ -6,12 +6,36 @@
66 } from "../filtering/streamTransforms/lineStream";
77
88 export interface AutocompleteLanguageInfo {
9+ /**
10+ * The display name of the language
11+ */
912 name: string;
13+ /**
14+ * Keywords that show up at the top-level of files. We often use these as stop words or soft breaks
15+ */
1016 topLevelKeywords: string[];
17+ /**
18+ * The character that prefixes a single line comment
19+ * We use this to format snippets from other files as large comment blocks
20+ */
1121 singleLineComment?: string;
22+ /**
23+ * Semi-colon or other end of line indicator that may be used as a stop char
24+ * or other parsing
25+ */
1226 endOfLine: string[];
27+ /**
28+ * Strings that indicate we should filter out a line from completion
29+ * Primarily currently used for .ipynb files
30+ */
1331 lineFilters?: LineFilter[];
32+ /**
33+ * Similar to line filters, but characters. I think.
34+ */
1435 charFilters?: CharacterFilter[];
36+ /**
37+ * Function that allows cusotmization of whether to use a multi-line completion on a per-language and completion basis
38+ */
1539 useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
1640 }
1741
@@ -23,6 +47,14 @@
2347 endOfLine: [";"],
2448 };
2549
50+// JavaScript
51+export const JavaScript = {
52+ name: "JavaScript",
53+ topLevelKeywords: ["function", "class", "module", "export", "import"],
54+ singleLineComment: "//",
55+ endOfLine: [";"],
56+};
57+
2658 // Python
2759 export const Python = {
2860 name: "Python",
@@ -336,7 +368,7 @@
336368
337369 export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
338370 ts: Typescript,
339- js: Typescript,
371+ js: JavaScript,
340372 tsx: Typescript,
341373 json: Json,
342374 jsx: Typescript,
modified core/autocomplete/context/ContextRetrievalService.ts +16 −0
@@ -70,4 +70,20 @@
7070 helper.treePath,
7171 );
7272 }
73+
74+ /**
75+ * Initialize the import definitions cache for a file.
76+ * This is normally done automatically when the active text editor changes,
77+ * but needs to be called manually when using context fetching outside the normal flow.
78+ */
79+ public async initializeForFile(filepath: string): Promise<void> {
80+ try {
81+ await (this.importDefinitionsService as any).cache.initKey(filepath);
82+ } catch (e) {
83+ console.warn(
84+ `Failed to initialize import definitions cache for ${filepath}:`,
85+ e,
86+ );
87+ }
88+ }
7389 }
modified core/autocomplete/snippets/getAllSnippets.ts +44 −0
@@ -209,3 +209,47 @@
209209 recentlyOpenedFileSnippets,
210210 };
211211 };
212+
213+export const getAllSnippetsWithoutRace = async ({
214+ helper,
215+ ide,
216+ getDefinitionsFromLsp,
217+ contextRetrievalService,
218+}: {
219+ helper: HelperVars;
220+ ide: IDE;
221+ getDefinitionsFromLsp: GetLspDefinitionsFunction;
222+ contextRetrievalService: ContextRetrievalService;
223+}): Promise<SnippetPayload> => {
224+ const recentlyEditedRangeSnippets =
225+ getSnippetsFromRecentlyEditedRanges(helper);
226+
227+ const [
228+ rootPathSnippets,
229+ importDefinitionSnippets,
230+ ideSnippets,
231+ diffSnippets,
232+ clipboardSnippets,
233+ recentlyOpenedFileSnippets,
234+ ] = await Promise.all([
235+ contextRetrievalService.getRootPathSnippets(helper),
236+ contextRetrievalService.getSnippetsFromImportDefinitions(helper),
237+ IDE_SNIPPETS_ENABLED
238+ ? getIdeSnippets(helper, ide, getDefinitionsFromLsp)
239+ : [],
240+ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
241+ getClipboardSnippets(ide),
242+ getSnippetsFromRecentlyOpenedFiles(helper, ide),
243+ ]);
244+
245+ return {
246+ rootPathSnippets,
247+ importDefinitionSnippets,
248+ ideSnippets,
249+ recentlyEditedRangeSnippets,
250+ diffSnippets,
251+ clipboardSnippets,
252+ recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
253+ recentlyOpenedFileSnippets,
254+ };
255+};
added core/codeRenderer/CodeRenderer.ts +272 −0
@@ -0,0 +1,272 @@
1+/**
2+ * CodeRenderer is a class that, when given a code string,
3+ * highlights the code string using shiki and
4+ * returns a svg representation of it.
5+ * We could technically just call shiki's methods to do a
6+ * one-liner syntax highlighting code, but
7+ * a separate class for this is useful because
8+ * we rarely ever need syntax highlighting outside of
9+ * creating a render of it.
10+ */
11+import { JSDOM } from "jsdom";
12+import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki";
13+import { escapeForSVG, kebabOfStr } from "../util/text";
14+
15+interface CodeRendererOptions {
16+ themesDir?: string;
17+ theme?: string;
18+}
19+
20+interface HTMLOptions {
21+ theme?: string;
22+ customCSS?: string;
23+ containerClass?: string;
24+}
25+
26+interface ConversionOptions extends HTMLOptions {
27+ transparent?: boolean;
28+ imageType: "svg";
29+}
30+
31+interface Dimensions {
32+ width: number;
33+ height: number;
34+}
35+
36+type DataUri = PngUri | SvgUri;
37+type PngUri = string;
38+type SvgUri = string;
39+
40+export class CodeRenderer {
41+ private static instance: CodeRenderer;
42+ private currentTheme: string = "dark-plus";
43+ private editorBackground: string = "#000000";
44+ private editorForeground: string = "#FFFFFF";
45+
46+ private constructor() {}
47+
48+ static getInstance(): CodeRenderer {
49+ if (!CodeRenderer.instance) {
50+ CodeRenderer.instance = new CodeRenderer();
51+ }
52+ return CodeRenderer.instance;
53+ }
54+
55+ public async setTheme(themeName: string): Promise<void> {
56+ if (
57+ this.themeExists(kebabOfStr(themeName)) ||
58+ themeName === "Default Dark Modern"
59+ ) {
60+ this.currentTheme =
61+ themeName === "Default Dark Modern"
62+ ? "dark-plus"
63+ : kebabOfStr(themeName);
64+
65+ const highlighter = await getSingletonHighlighter({
66+ themes: [this.currentTheme],
67+ });
68+
69+ const th = highlighter.getTheme(this.currentTheme);
70+ this.editorBackground = th.bg;
71+ this.editorForeground = th.fg;
72+ } else {
73+ this.currentTheme = "dark-plus";
74+ }
75+ }
76+
77+ async init(): Promise<void> {}
78+
79+ async close(): Promise<void> {}
80+
81+ themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
82+ const themeArray: BundledTheme[] = [
83+ "andromeeda",
84+ "aurora-x",
85+ "ayu-dark",
86+ "catppuccin-frappe",
87+ "catppuccin-latte",
88+ "catppuccin-macchiato",
89+ "catppuccin-mocha",
90+ "dark-plus",
91+ "dracula",
92+ "dracula-soft",
93+ "everforest-dark",
94+ "everforest-light",
95+ "github-dark",
96+ "github-dark-default",
97+ "github-dark-dimmed",
98+ "github-dark-high-contrast",
99+ "github-light",
100+ "github-light-default",
101+ "github-light-high-contrast",
102+ "gruvbox-dark-hard",
103+ "gruvbox-dark-medium",
104+ "gruvbox-dark-soft",
105+ "gruvbox-light-hard",
106+ "gruvbox-light-medium",
107+ "gruvbox-light-soft",
108+ "houston",
109+ "kanagawa-dragon",
110+ "kanagawa-lotus",
111+ "kanagawa-wave",
112+ "laserwave",
113+ "light-plus",
114+ "material-theme",
115+ "material-theme-darker",
116+ "material-theme-lighter",
117+ "material-theme-ocean",
118+ "material-theme-palenight",
119+ "min-dark",
120+ "min-light",
121+ "monokai",
122+ "night-owl",
123+ "nord",
124+ "one-dark-pro",
125+ "one-light",
126+ "plastic",
127+ "poimandres",
128+ "red",
129+ "rose-pine",
130+ "rose-pine-dawn",
131+ "rose-pine-moon",
132+ "slack-dark",
133+ "slack-ochin",
134+ "snazzy-light",
135+ "solarized-dark",
136+ "solarized-light",
137+ "synthwave-84",
138+ "tokyo-night",
139+ "vesper",
140+ "vitesse-black",
141+ "vitesse-dark",
142+ "vitesse-light",
143+ ];
144+
145+ return themeArray.includes(themeNameKebab as BundledTheme);
146+ }
147+
148+ async highlightCode(
149+ code: string,
150+ language: string = "javascript",
151+ ): Promise<string> {
152+ return await codeToHtml(code, {
153+ lang: language,
154+ theme: this.currentTheme,
155+ });
156+ }
157+
158+ async convertToSVG(
159+ code: string,
160+ language: string = "javascript",
161+ fontSize: number,
162+ fontFamily: string,
163+ dimensions: Dimensions,
164+ lineHeight: number,
165+ options: ConversionOptions,
166+ ): Promise<Buffer> {
167+ const highlightedCodeHtml = await this.highlightCode(code, language);
168+
169+ const guts = this.convertShikiHtmlToSvgGut(
170+ highlightedCodeHtml,
171+ fontSize,
172+ fontFamily,
173+ lineHeight,
174+ );
175+ const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
176+
177+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
178+ <g>
179+ <rect width="${dimensions.width}" height="${dimensions.height}" fill="${backgroundColor}" stroke="${this.editorForeground}" stroke-width="1" />
180+ ${guts}
181+ </g>
182+</svg>`;
183+
184+ return Buffer.from(svg, "utf8");
185+ }
186+
187+ convertShikiHtmlToSvgGut(
188+ shikiHtml: string,
189+ fontSize: number,
190+ fontFamily: string,
191+ lineHeight: number,
192+ ): string {
193+ const dom = new JSDOM(shikiHtml);
194+ const document = dom.window.document;
195+
196+ const lines = Array.from(document.querySelectorAll(".line"));
197+ const svgLines = lines.map((line, index) => {
198+ const spans = Array.from(line.childNodes)
199+ .map((node) => {
200+ if (node.nodeType === 3) {
201+ return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
202+ }
203+
204+ const el = node as HTMLElement;
205+ const style = el.getAttribute("style") || "";
206+ const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
207+ const fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
208+ const content = el.textContent || "";
209+ return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
210+ })
211+ .join("");
212+
213+ const y = (index + 1) * lineHeight;
214+ return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve">${spans}</text>`;
215+ });
216+
217+ return `
218+ ${svgLines.join("\n")}
219+ `.trim();
220+ }
221+
222+ getBackgroundColor(shikiHtml: string): string {
223+ const dom = new JSDOM(shikiHtml);
224+ const document = dom.window.document;
225+
226+ const preElement = document.querySelector("pre");
227+ let backgroundColor = "#333333"; // Default white background
228+ if (preElement) {
229+ const style = preElement.getAttribute("style") || "";
230+ const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
231+ if (bgColorMatch) {
232+ backgroundColor = bgColorMatch[1];
233+ }
234+ }
235+
236+ return backgroundColor;
237+ }
238+
239+ async getDataUri(
240+ code: string,
241+ language: string = "javascript",
242+ fontSize: number,
243+ fontFamily: string,
244+ dimensions: Dimensions,
245+ lineHeight: number,
246+ options: ConversionOptions,
247+ ): Promise<DataUri> {
248+ switch (options.imageType) {
249+ // case "png":
250+ // const pngBuffer = await this.convertToPNG(
251+ // code,
252+ // language,
253+ // fontSize,
254+ // dimensions,
255+ // lineHeight,
256+ // options,
257+ // );
258+ // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
259+ case "svg":
260+ const svgBuffer = await this.convertToSVG(
261+ code,
262+ language,
263+ fontSize,
264+ fontFamily,
265+ dimensions,
266+ lineHeight,
267+ options,
268+ );
269+ return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
270+ }
271+ }
272+}
deleted core/config/ConfigHandler.test.ts +0 −54
@@ -1,54 +0,0 @@
1-import fs from "node:fs";
2-import path from "node:path";
3-
4-import { testConfigHandler } from "../test/fixtures";
5-import { TEST_DIR } from "../test/testDir";
6-import { getConfigTsPath } from "../util/paths";
7-
8-import { defaultConfig } from "./default";
9-
10-describe.skip("Test the ConfigHandler and E2E config loading", () => {
11- test("should show only local profile", () => {
12- const profiles = testConfigHandler.currentOrg.profiles;
13- expect(profiles?.length).toBe(1);
14- expect(profiles?.[0].profileDescription.id).toBe("local");
15-
16- const currentProfile = testConfigHandler.currentProfile;
17- expect(currentProfile?.profileDescription.id).toBe("local");
18- });
19-
20- test("should load the default config successfully", async () => {
21- const result = await testConfigHandler.loadConfig();
22- expect(result.config!.modelsByRole.chat.length).toBe(
23- defaultConfig.models?.length,
24- );
25- });
26-
27- test.skip("should add a system message from config.ts", async () => {
28- const configTs = `export function modifyConfig(config: Config): Config {
29- config.systemMessage = "SYSTEM";
30- return config;
31-}`;
32- fs.writeFileSync(getConfigTsPath(), configTs);
33- await new Promise((resolve) => setTimeout(resolve, 1000));
34- const config = await testConfigHandler.reloadConfig();
35- /**
36- * @ts-ignore is applied because this test is skipped
37- */
38- // @ts-ignore
39- expect(config.systemMessage).toBe("SYSTEM");
40- });
41-
42- test.skip("should acknowledge override from .continuerc.json", async () => {
43- fs.writeFileSync(
44- path.join(TEST_DIR, ".continuerc.json"),
45- JSON.stringify({ systemMessage: "SYSTEM2" }),
46- );
47- const config = await testConfigHandler.reloadConfig();
48- /**
49- * @ts-ignore is applied because this test is skipped
50- */
51- // @ts-ignore
52- expect(config.systemMessage).toBe("SYSTEM2");
53- });
54-});
added core/config/ConfigHandler.vitest.ts +55 −0
@@ -0,0 +1,55 @@
1+import fs from "node:fs";
2+import path from "node:path";
3+
4+import { describe, expect, test } from "vitest";
5+import { testConfigHandler } from "../test/fixtures";
6+import { TEST_DIR } from "../test/testDir";
7+import { getConfigTsPath } from "../util/paths";
8+
9+import { defaultConfig } from "./default";
10+
11+describe.skip("Test the ConfigHandler and E2E config loading", () => {
12+ test("should show only local profile", () => {
13+ const profiles = testConfigHandler.currentOrg.profiles;
14+ expect(profiles?.length).toBe(1);
15+ expect(profiles?.[0].profileDescription.id).toBe("local");
16+
17+ const currentProfile = testConfigHandler.currentProfile;
18+ expect(currentProfile?.profileDescription.id).toBe("local");
19+ });
20+
21+ test("should load the default config successfully", async () => {
22+ const result = await testConfigHandler.loadConfig();
23+ expect(result.config!.modelsByRole.chat.length).toBe(
24+ defaultConfig.models?.length,
25+ );
26+ });
27+
28+ test("should add a system message from config.ts", async () => {
29+ const configTs = `export function modifyConfig(config: Config): Config {
30+ config.systemMessage = "SYSTEM";
31+ return config;
32+}`;
33+ fs.writeFileSync(getConfigTsPath(), configTs);
34+ await new Promise((resolve) => setTimeout(resolve, 1000));
35+ const config = await testConfigHandler.reloadConfig();
36+ /**
37+ * @ts-ignore is applied because this test is skipped
38+ */
39+ // @ts-ignore
40+ expect(config.systemMessage).toBe("SYSTEM");
41+ });
42+
43+ test("should acknowledge override from .continuerc.json", async () => {
44+ fs.writeFileSync(
45+ path.join(TEST_DIR, ".continuerc.json"),
46+ JSON.stringify({ systemMessage: "SYSTEM2" }),
47+ );
48+ const config = await testConfigHandler.reloadConfig();
49+ /**
50+ * @ts-ignore is applied because this test is skipped
51+ */
52+ // @ts-ignore
53+ expect(config.systemMessage).toBe("SYSTEM2");
54+ });
55+});
modified core/config/load.ts +1 −8
@@ -36,7 +36,6 @@
3636 import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
3737 import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
3838 import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
39-import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
4039 import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
4140 import CustomContextProviderClass from "../context/providers/CustomContextProvider";
4241 import FileContextProvider from "../context/providers/FileContextProvider";
@@ -398,13 +397,7 @@
398397 | undefined
399398 )?.params || {};
400399
401- const DEFAULT_CONTEXT_PROVIDERS = [
402- new FileContextProvider({}),
403- // Add codebase provider if indexing is enabled
404- ...(!config.disableIndexing
405- ? [new CodebaseContextProvider(codebaseContextParams)]
406- : []),
407- ];
400+ const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
408401
409402 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
410403 ({ description: { title } }) => title,
deleted core/config/loadLocalAssistants.test.ts +0 −241
@@ -1,241 +0,0 @@
1-import { walkDirCache } from "../indexing/walkDir";
2-import { testIde } from "../test/fixtures";
3-import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
4-import {
5- getAllDotContinueDefinitionFiles,
6- LoadAssistantFilesOptions,
7-} from "./loadLocalAssistants";
8-describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
9- beforeEach(() => {
10- setUpTestDir();
11- walkDirCache.invalidate();
12-
13- // Add test files to the test directory
14- addToTestDir([
15- ".continue/assistants/",
16- [".continue/assistants/assistant1.yaml", "yaml content 1"],
17- [".continue/assistants/assistant2.yml", "yaml content 2"],
18- [".continue/assistants/assistant3.md", "markdown content 1"],
19- [".continue/assistants/assistant4.txt", "txt content"],
20- ]);
21- });
22-
23- afterEach(() => {
24- tearDownTestDir();
25- walkDirCache.invalidate();
26- });
27-
28- it("should return only YAML files when fileExtType is 'yaml'", async () => {
29- const options: LoadAssistantFilesOptions = {
30- includeGlobal: false, // Only test workspace for simplicity
31- includeWorkspace: true,
32- fileExtType: "yaml",
33- };
34-
35- const result = await getAllDotContinueDefinitionFiles(
36- testIde,
37- options,
38- "assistants",
39- );
40- expect(result).toHaveLength(2);
41- expect(result.map((f) => f.path.split("/").pop())).toEqual(
42- expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
43- );
44- expect(result.map((f) => f.path.split("/").pop())).not.toContain(
45- "assistant3.md",
46- );
47- });
48-
49- it("should return only Markdown files when fileExtType is 'markdown'", async () => {
50- const options: LoadAssistantFilesOptions = {
51- includeGlobal: false,
52- includeWorkspace: true,
53- fileExtType: "markdown",
54- };
55-
56- const result = await getAllDotContinueDefinitionFiles(
57- testIde,
58- options,
59- "assistants",
60- );
61- expect(result).toHaveLength(1);
62- expect(result.map((f) => f.path.split("/").pop())).toEqual([
63- "assistant3.md",
64- ]);
65- expect(result.map((f) => f.path.split("/").pop())).not.toContain(
66- "assistant1.yaml",
67- );
68- expect(result.map((f) => f.path.split("/").pop())).not.toContain(
69- "assistant2.yml",
70- );
71- });
72-
73- it("should return all supported files when fileExtType is not specified", async () => {
74- const options: LoadAssistantFilesOptions = {
75- includeGlobal: false,
76- includeWorkspace: true,
77- // fileExtType not specified
78- };
79-
80- const result = await getAllDotContinueDefinitionFiles(
81- testIde,
82- options,
83- "assistants",
84- );
85- expect(result).toHaveLength(3);
86- expect(result.map((f) => f.path.split("/").pop())).toEqual(
87- expect.arrayContaining([
88- "assistant1.yaml",
89- "assistant2.yml",
90- "assistant3.md",
91- ]),
92- );
93- // Should not include .txt files
94- expect(result.map((f) => f.path.split("/").pop())).not.toContain(
95- "assistant4.txt",
96- );
97- });
98-
99- it("should respect includeWorkspace option with fileExtType", async () => {
100- // Test with includeWorkspace: false
101- const workspaceOffOptions: LoadAssistantFilesOptions = {
102- includeGlobal: false,
103- includeWorkspace: false,
104- fileExtType: "yaml",
105- };
106-
107- const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
108- testIde,
109- workspaceOffOptions,
110- "assistants",
111- );
112- expect(noWorkspaceResult).toHaveLength(0);
113-
114- // Test with includeWorkspace: true
115- const workspaceOnOptions: LoadAssistantFilesOptions = {
116- includeGlobal: false,
117- includeWorkspace: true,
118- fileExtType: "yaml",
119- };
120-
121- const workspaceResult = await getAllDotContinueDefinitionFiles(
122- testIde,
123- workspaceOnOptions,
124- "assistants",
125- );
126- expect(workspaceResult).toHaveLength(2);
127- expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
128- expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
129- );
130- });
131-
132- it("should return empty array when no files match the specified extension type", async () => {
133- // Create a test directory with only non-matching files
134- tearDownTestDir();
135- walkDirCache.invalidate();
136- setUpTestDir();
137- addToTestDir([
138- ".continue/assistants/",
139- [".continue/assistants/nonmatch1.txt", "txt content"],
140- [".continue/assistants/nonmatch2.json", "json content"],
141- ]);
142-
143- const options: LoadAssistantFilesOptions = {
144- includeGlobal: false,
145- includeWorkspace: true,
146-
147- fileExtType: "yaml",
148- };
149-
150- const result = await getAllDotContinueDefinitionFiles(
151- testIde,
152- options,
153- "assistants",
154- );
155- expect(result).toHaveLength(0);
156- });
157-
158- it("should handle directories that don't exist", async () => {
159- // Create a clean test directory without the assistants folder
160- tearDownTestDir();
161- setUpTestDir();
162-
163- const options: LoadAssistantFilesOptions = {
164- includeGlobal: false,
165- includeWorkspace: true,
166- fileExtType: "yaml",
167- };
168-
169- const result = await getAllDotContinueDefinitionFiles(
170- testIde,
171- options,
172- "assistants",
173- );
174- expect(result).toHaveLength(0);
175- });
176-
177- it("should return correct file content", async () => {
178- const options: LoadAssistantFilesOptions = {
179- includeGlobal: false,
180- includeWorkspace: true,
181- fileExtType: "yaml",
182- };
183-
184- const result = await getAllDotContinueDefinitionFiles(
185- testIde,
186- options,
187- "assistants",
188- );
189- expect(result).toHaveLength(2);
190- const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
191- expect(yamlFile?.content).toBe("yaml content 1");
192- });
193-
194- it("should filter by file extension case sensitively", async () => {
195- // Add files with uppercase extensions
196- addToTestDir([
197- [".continue/assistants/assistant5.YAML", "uppercase yaml"],
198- [".continue/assistants/assistant6.YML", "uppercase yml"],
199- [".continue/assistants/assistant7.MD", "uppercase md"],
200- ]);
201-
202- const yamlOptions: LoadAssistantFilesOptions = {
203- includeGlobal: false,
204- includeWorkspace: true,
205- fileExtType: "yaml",
206- };
207-
208- const yamlResult = await getAllDotContinueDefinitionFiles(
209- testIde,
210- yamlOptions,
211- "assistants",
212- );
213- // Should only get lowercase extensions (current implementation)
214- expect(yamlResult).toHaveLength(2);
215- expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
216- expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
217- );
218- expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
219- "assistant5.YAML",
220- );
221-
222- const markdownOptions: LoadAssistantFilesOptions = {
223- includeGlobal: false,
224- includeWorkspace: true,
225- fileExtType: "markdown",
226- };
227-
228- const markdownResult = await getAllDotContinueDefinitionFiles(
229- testIde,
230- markdownOptions,
231- "assistants",
232- );
233- expect(markdownResult).toHaveLength(1);
234- expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
235- "assistant3.md",
236- ]);
237- expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
238- "assistant7.MD",
239- );
240- });
241-});
added core/config/loadLocalAssistants.vitest.ts +242 −0
@@ -0,0 +1,242 @@
1+import { afterEach, beforeEach, describe, expect, it } from "vitest";
2+import { walkDirCache } from "../indexing/walkDir";
3+import { testIde } from "../test/fixtures";
4+import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
5+import {
6+ getAllDotContinueDefinitionFiles,
7+ LoadAssistantFilesOptions,
8+} from "./loadLocalAssistants";
9+describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
10+ beforeEach(() => {
11+ setUpTestDir();
12+ walkDirCache.invalidate();
13+
14+ // Add test files to the test directory
15+ addToTestDir([
16+ ".continue/assistants/",
17+ [".continue/assistants/assistant1.yaml", "yaml content 1"],
18+ [".continue/assistants/assistant2.yml", "yaml content 2"],
19+ [".continue/assistants/assistant3.md", "markdown content 1"],
20+ [".continue/assistants/assistant4.txt", "txt content"],
21+ ]);
22+ });
23+
24+ afterEach(() => {
25+ tearDownTestDir();
26+ walkDirCache.invalidate();
27+ });
28+
29+ it("should return only YAML files when fileExtType is 'yaml'", async () => {
30+ const options: LoadAssistantFilesOptions = {
31+ includeGlobal: false, // Only test workspace for simplicity
32+ includeWorkspace: true,
33+ fileExtType: "yaml",
34+ };
35+
36+ const result = await getAllDotContinueDefinitionFiles(
37+ testIde,
38+ options,
39+ "assistants",
40+ );
41+ expect(result).toHaveLength(2);
42+ expect(result.map((f) => f.path.split("/").pop())).toEqual(
43+ expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
44+ );
45+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
46+ "assistant3.md",
47+ );
48+ });
49+
50+ it("should return only Markdown files when fileExtType is 'markdown'", async () => {
51+ const options: LoadAssistantFilesOptions = {
52+ includeGlobal: false,
53+ includeWorkspace: true,
54+ fileExtType: "markdown",
55+ };
56+
57+ const result = await getAllDotContinueDefinitionFiles(
58+ testIde,
59+ options,
60+ "assistants",
61+ );
62+ expect(result).toHaveLength(1);
63+ expect(result.map((f) => f.path.split("/").pop())).toEqual([
64+ "assistant3.md",
65+ ]);
66+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
67+ "assistant1.yaml",
68+ );
69+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
70+ "assistant2.yml",
71+ );
72+ });
73+
74+ it("should return all supported files when fileExtType is not specified", async () => {
75+ const options: LoadAssistantFilesOptions = {
76+ includeGlobal: false,
77+ includeWorkspace: true,
78+ // fileExtType not specified
79+ };
80+
81+ const result = await getAllDotContinueDefinitionFiles(
82+ testIde,
83+ options,
84+ "assistants",
85+ );
86+ expect(result).toHaveLength(3);
87+ expect(result.map((f) => f.path.split("/").pop())).toEqual(
88+ expect.arrayContaining([
89+ "assistant1.yaml",
90+ "assistant2.yml",
91+ "assistant3.md",
92+ ]),
93+ );
94+ // Should not include .txt files
95+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
96+ "assistant4.txt",
97+ );
98+ });
99+
100+ it("should respect includeWorkspace option with fileExtType", async () => {
101+ // Test with includeWorkspace: false
102+ const workspaceOffOptions: LoadAssistantFilesOptions = {
103+ includeGlobal: false,
104+ includeWorkspace: false,
105+ fileExtType: "yaml",
106+ };
107+
108+ const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
109+ testIde,
110+ workspaceOffOptions,
111+ "assistants",
112+ );
113+ expect(noWorkspaceResult).toHaveLength(0);
114+
115+ // Test with includeWorkspace: true
116+ const workspaceOnOptions: LoadAssistantFilesOptions = {
117+ includeGlobal: false,
118+ includeWorkspace: true,
119+ fileExtType: "yaml",
120+ };
121+
122+ const workspaceResult = await getAllDotContinueDefinitionFiles(
123+ testIde,
124+ workspaceOnOptions,
125+ "assistants",
126+ );
127+ expect(workspaceResult).toHaveLength(2);
128+ expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
129+ expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
130+ );
131+ });
132+
133+ it("should return empty array when no files match the specified extension type", async () => {
134+ // Create a test directory with only non-matching files
135+ tearDownTestDir();
136+ walkDirCache.invalidate();
137+ setUpTestDir();
138+ addToTestDir([
139+ ".continue/assistants/",
140+ [".continue/assistants/nonmatch1.txt", "txt content"],
141+ [".continue/assistants/nonmatch2.json", "json content"],
142+ ]);
143+
144+ const options: LoadAssistantFilesOptions = {
145+ includeGlobal: false,
146+ includeWorkspace: true,
147+
148+ fileExtType: "yaml",
149+ };
150+
151+ const result = await getAllDotContinueDefinitionFiles(
152+ testIde,
153+ options,
154+ "assistants",
155+ );
156+ expect(result).toHaveLength(0);
157+ });
158+
159+ it("should handle directories that don't exist", async () => {
160+ // Create a clean test directory without the assistants folder
161+ tearDownTestDir();
162+ setUpTestDir();
163+
164+ const options: LoadAssistantFilesOptions = {
165+ includeGlobal: false,
166+ includeWorkspace: true,
167+ fileExtType: "yaml",
168+ };
169+
170+ const result = await getAllDotContinueDefinitionFiles(
171+ testIde,
172+ options,
173+ "assistants",
174+ );
175+ expect(result).toHaveLength(0);
176+ });
177+
178+ it("should return correct file content", async () => {
179+ const options: LoadAssistantFilesOptions = {
180+ includeGlobal: false,
181+ includeWorkspace: true,
182+ fileExtType: "yaml",
183+ };
184+
185+ const result = await getAllDotContinueDefinitionFiles(
186+ testIde,
187+ options,
188+ "assistants",
189+ );
190+ expect(result).toHaveLength(2);
191+ const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
192+ expect(yamlFile?.content).toBe("yaml content 1");
193+ });
194+
195+ it("should filter by file extension case sensitively", async () => {
196+ // Add files with uppercase extensions
197+ addToTestDir([
198+ [".continue/assistants/assistant5.YAML", "uppercase yaml"],
199+ [".continue/assistants/assistant6.YML", "uppercase yml"],
200+ [".continue/assistants/assistant7.MD", "uppercase md"],
201+ ]);
202+
203+ const yamlOptions: LoadAssistantFilesOptions = {
204+ includeGlobal: false,
205+ includeWorkspace: true,
206+ fileExtType: "yaml",
207+ };
208+
209+ const yamlResult = await getAllDotContinueDefinitionFiles(
210+ testIde,
211+ yamlOptions,
212+ "assistants",
213+ );
214+ // Should only get lowercase extensions (current implementation)
215+ expect(yamlResult).toHaveLength(2);
216+ expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
217+ expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
218+ );
219+ expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
220+ "assistant5.YAML",
221+ );
222+
223+ const markdownOptions: LoadAssistantFilesOptions = {
224+ includeGlobal: false,
225+ includeWorkspace: true,
226+ fileExtType: "markdown",
227+ };
228+
229+ const markdownResult = await getAllDotContinueDefinitionFiles(
230+ testIde,
231+ markdownOptions,
232+ "assistants",
233+ );
234+ expect(markdownResult).toHaveLength(1);
235+ expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
236+ "assistant3.md",
237+ ]);
238+ expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
239+ "assistant7.MD",
240+ );
241+ });
242+});
modified core/config/sharedConfig.ts +9 −0
@@ -19,6 +19,8 @@
1919 readResponseTTS: z.boolean(),
2020 promptPath: z.string(),
2121 useCurrentFileAsContext: z.boolean(),
22+ logEditingData: z.boolean(),
23+ optInNextEditFeature: z.boolean(),
2224 enableExperimentalTools: z.boolean(),
2325
2426 // `ui` in `ContinueConfig`
@@ -178,6 +180,13 @@
178180 configCopy.experimental.useCurrentFileAsContext =
179181 sharedConfig.useCurrentFileAsContext;
180182 }
183+ if (sharedConfig.logEditingData !== undefined) {
184+ configCopy.experimental.logEditingData = sharedConfig.logEditingData;
185+ }
186+ if (sharedConfig.optInNextEditFeature !== undefined) {
187+ configCopy.experimental.optInNextEditFeature =
188+ sharedConfig.optInNextEditFeature;
189+ }
181190
182191 return configCopy;
183192 }
deleted core/config/usesFreeTrialApiKey.test.ts +0 −344
@@ -1,344 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { BrowserSerializedContinueConfig } from "..";
3-
4-// Create the mock before importing anything else
5-const mockDecodeSecretLocation = jest.fn();
6-
7-// Mock the module
8-jest.unstable_mockModule("@continuedev/config-yaml", () => ({
9- SecretType: {
10- User: "user",
11- Organization: "organization",
12- FreeTrial: "free_trial",
13- },
14- decodeSecretLocation: mockDecodeSecretLocation,
15-}));
16-
17-// Import after mocking
18-const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
19-const { SecretType } = await import("@continuedev/config-yaml");
20-
21-beforeEach(() => {
22- mockDecodeSecretLocation.mockReset();
23-});
24-
25-test("usesFreeTrialApiKey should return false when config is null", () => {
26- const result = usesFreeTrialApiKey(null);
27- expect(result).toBe(false);
28-});
29-
30-test("usesFreeTrialApiKey should return false when config is undefined", () => {
31- const result = usesFreeTrialApiKey(undefined as any);
32- expect(result).toBe(false);
33-});
34-
35-test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
36- const config: BrowserSerializedContinueConfig = {
37- modelsByRole: {
38- chat: [
39- {
40- title: "Model 1",
41- provider: "test",
42- model: "test-model",
43- underlyingProviderName: "test",
44- },
45- {
46- title: "Model 2",
47- provider: "test",
48- model: "test-model-2",
49- underlyingProviderName: "test",
50- },
51- ],
52- edit: [],
53- apply: [],
54- summarize: [],
55- autocomplete: [],
56- rerank: [],
57- embed: [],
58- },
59- selectedModelByRole: {
60- chat: null,
61- edit: null,
62- apply: null,
63- summarize: null,
64- autocomplete: null,
65- rerank: null,
66- embed: null,
67- },
68- contextProviders: [],
69- slashCommands: [],
70- tools: [],
71- mcpServerStatuses: [],
72- usePlatform: false,
73- rules: [],
74- };
75-
76- const result = usesFreeTrialApiKey(config);
77- expect(result).toBe(false);
78-});
79-
80-test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
81- const config: BrowserSerializedContinueConfig = {
82- modelsByRole: {
83- chat: [
84- {
85- title: "Model 1",
86- provider: "test",
87- model: "test-model",
88- apiKeyLocation: "user:testuser/api-key",
89- underlyingProviderName: "test",
90- },
91- ],
92- edit: [
93- {
94- title: "Model 2",
95- provider: "test",
96- model: "test-model-2",
97- apiKeyLocation: "organization:testorg/api-key",
98- underlyingProviderName: "test",
99- },
100- ],
101- apply: [],
102- summarize: [],
103- autocomplete: [],
104- rerank: [],
105- embed: [],
106- },
107- selectedModelByRole: {
108- chat: null,
109- edit: null,
110- apply: null,
111- summarize: null,
112- autocomplete: null,
113- rerank: null,
114- embed: null,
115- },
116- contextProviders: [],
117- slashCommands: [],
118- tools: [],
119- mcpServerStatuses: [],
120- usePlatform: false,
121- rules: [],
122- };
123-
124- mockDecodeSecretLocation
125- .mockReturnValueOnce({
126- secretType: SecretType.User,
127- userSlug: "testuser",
128- secretName: "api-key",
129- })
130- .mockReturnValueOnce({
131- secretType: SecretType.Organization,
132- orgSlug: "testorg",
133- secretName: "api-key",
134- });
135-
136- const result = usesFreeTrialApiKey(config);
137- expect(result).toBe(false);
138- expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
139-});
140-
141-test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
142- const config: BrowserSerializedContinueConfig = {
143- modelsByRole: {
144- chat: [
145- {
146- title: "Model 1",
147- provider: "test",
148- model: "test-model",
149- apiKeyLocation: "user:testuser/api-key",
150- underlyingProviderName: "test",
151- },
152- {
153- title: "Free Trial Model",
154- provider: "test",
155- model: "free-trial-model",
156- apiKeyLocation: "free_trial:owner/package/api-key",
157- underlyingProviderName: "test",
158- },
159- ],
160- edit: [],
161- apply: [],
162- summarize: [],
163- autocomplete: [],
164- rerank: [],
165- embed: [],
166- },
167- selectedModelByRole: {
168- chat: null,
169- edit: null,
170- apply: null,
171- summarize: null,
172- autocomplete: null,
173- rerank: null,
174- embed: null,
175- },
176- contextProviders: [],
177- slashCommands: [],
178- tools: [],
179- mcpServerStatuses: [],
180- usePlatform: false,
181- rules: [],
182- };
183-
184- mockDecodeSecretLocation
185- .mockReturnValueOnce({
186- secretType: SecretType.User,
187- userSlug: "testuser",
188- secretName: "api-key",
189- })
190- .mockReturnValueOnce({
191- secretType: SecretType.FreeTrial,
192- blockSlug: { ownerSlug: "owner", packageSlug: "package" },
193- secretName: "api-key",
194- });
195-
196- const result = usesFreeTrialApiKey(config);
197- expect(result).toBe(true);
198- expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
199-});
200-
201-test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
202- const config: BrowserSerializedContinueConfig = {
203- modelsByRole: {
204- chat: [
205- {
206- title: "Model 1",
207- provider: "test",
208- model: "test-model",
209- apiKeyLocation: "user:testuser/api-key",
210- underlyingProviderName: "test",
211- },
212- ],
213- edit: [
214- {
215- title: "Free Trial Edit Model",
216- provider: "test",
217- model: "free-trial-edit-model",
218- apiKeyLocation: "free_trial:owner/package/api-key",
219- underlyingProviderName: "test",
220- },
221- ],
222- apply: [],
223- summarize: [],
224- autocomplete: [],
225- rerank: [],
226- embed: [],
227- },
228- selectedModelByRole: {
229- chat: null,
230- edit: null,
231- apply: null,
232- summarize: null,
233- autocomplete: null,
234- rerank: null,
235- embed: null,
236- },
237- contextProviders: [],
238- slashCommands: [],
239- tools: [],
240- mcpServerStatuses: [],
241- usePlatform: false,
242- rules: [],
243- };
244-
245- mockDecodeSecretLocation
246- .mockReturnValueOnce({
247- secretType: SecretType.User,
248- userSlug: "testuser",
249- secretName: "api-key",
250- })
251- .mockReturnValueOnce({
252- secretType: SecretType.FreeTrial,
253- blockSlug: { ownerSlug: "owner", packageSlug: "package" },
254- secretName: "api-key",
255- });
256-
257- const result = usesFreeTrialApiKey(config);
258- expect(result).toBe(true);
259-});
260-
261-test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
262- const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
263-
264- const config: BrowserSerializedContinueConfig = {
265- modelsByRole: {
266- chat: [
267- {
268- title: "Model 1",
269- provider: "test",
270- model: "test-model",
271- apiKeyLocation: "invalid-secret-location",
272- underlyingProviderName: "test",
273- },
274- ],
275- edit: [],
276- apply: [],
277- summarize: [],
278- autocomplete: [],
279- rerank: [],
280- embed: [],
281- },
282- selectedModelByRole: {
283- chat: null,
284- edit: null,
285- apply: null,
286- summarize: null,
287- autocomplete: null,
288- rerank: null,
289- embed: null,
290- },
291- contextProviders: [],
292- slashCommands: [],
293- tools: [],
294- mcpServerStatuses: [],
295- usePlatform: false,
296- rules: [],
297- };
298-
299- mockDecodeSecretLocation.mockImplementation(() => {
300- throw new Error("Invalid secret location format");
301- });
302-
303- const result = usesFreeTrialApiKey(config);
304- expect(result).toBe(false);
305- expect(consoleSpy).toHaveBeenCalledWith(
306- "Error checking for free trial API key:",
307- expect.any(Error),
308- );
309-
310- consoleSpy.mockRestore();
311-});
312-
313-test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
314- const config: BrowserSerializedContinueConfig = {
315- modelsByRole: {
316- chat: [],
317- edit: [],
318- apply: [],
319- summarize: [],
320- autocomplete: [],
321- rerank: [],
322- embed: [],
323- },
324- selectedModelByRole: {
325- chat: null,
326- edit: null,
327- apply: null,
328- summarize: null,
329- autocomplete: null,
330- rerank: null,
331- embed: null,
332- },
333- contextProviders: [],
334- slashCommands: [],
335- tools: [],
336- mcpServerStatuses: [],
337- usePlatform: false,
338- rules: [],
339- };
340-
341- const result = usesFreeTrialApiKey(config);
342- expect(result).toBe(false);
343- expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
344-});
added core/config/usesFreeTrialApiKey.vitest.ts +348 −0
@@ -0,0 +1,348 @@
1+import { beforeEach, describe, expect, test, vi } from "vitest";
2+import { BrowserSerializedContinueConfig } from "..";
3+
4+// Create the mock before importing anything else
5+const mockDecodeSecretLocation = vi.fn();
6+
7+// Mock the module
8+vi.mock("@continuedev/config-yaml", () => ({
9+ SecretType: {
10+ User: "user",
11+ Organization: "organization",
12+ FreeTrial: "free_trial",
13+ },
14+ decodeSecretLocation: mockDecodeSecretLocation,
15+}));
16+
17+describe("usesFreeTrialApiKey", () => {
18+ let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
19+ let SecretType: typeof import("@continuedev/config-yaml").SecretType;
20+
21+ beforeEach(async () => {
22+ mockDecodeSecretLocation.mockReset();
23+ usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
24+ .usesFreeTrialApiKey;
25+ SecretType = (await import("@continuedev/config-yaml")).SecretType;
26+ });
27+
28+ test("usesFreeTrialApiKey should return false when config is null", () => {
29+ const result = usesFreeTrialApiKey(null);
30+ expect(result).toBe(false);
31+ });
32+
33+ test("usesFreeTrialApiKey should return false when config is undefined", () => {
34+ const result = usesFreeTrialApiKey(undefined as any);
35+ expect(result).toBe(false);
36+ });
37+
38+ test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
39+ const config: BrowserSerializedContinueConfig = {
40+ modelsByRole: {
41+ chat: [
42+ {
43+ title: "Model 1",
44+ provider: "test",
45+ model: "test-model",
46+ underlyingProviderName: "test",
47+ },
48+ {
49+ title: "Model 2",
50+ provider: "test",
51+ model: "test-model-2",
52+ underlyingProviderName: "test",
53+ },
54+ ],
55+ edit: [],
56+ apply: [],
57+ summarize: [],
58+ autocomplete: [],
59+ rerank: [],
60+ embed: [],
61+ },
62+ selectedModelByRole: {
63+ chat: null,
64+ edit: null,
65+ apply: null,
66+ summarize: null,
67+ autocomplete: null,
68+ rerank: null,
69+ embed: null,
70+ },
71+ contextProviders: [],
72+ slashCommands: [],
73+ tools: [],
74+ mcpServerStatuses: [],
75+ usePlatform: false,
76+ rules: [],
77+ };
78+
79+ const result = usesFreeTrialApiKey(config);
80+ expect(result).toBe(false);
81+ });
82+
83+ test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
84+ const config: BrowserSerializedContinueConfig = {
85+ modelsByRole: {
86+ chat: [
87+ {
88+ title: "Model 1",
89+ provider: "test",
90+ model: "test-model",
91+ apiKeyLocation: "user:testuser/api-key",
92+ underlyingProviderName: "test",
93+ },
94+ ],
95+ edit: [
96+ {
97+ title: "Model 2",
98+ provider: "test",
99+ model: "test-model-2",
100+ apiKeyLocation: "organization:testorg/api-key",
101+ underlyingProviderName: "test",
102+ },
103+ ],
104+ apply: [],
105+ summarize: [],
106+ autocomplete: [],
107+ rerank: [],
108+ embed: [],
109+ },
110+ selectedModelByRole: {
111+ chat: null,
112+ edit: null,
113+ apply: null,
114+ summarize: null,
115+ autocomplete: null,
116+ rerank: null,
117+ embed: null,
118+ },
119+ contextProviders: [],
120+ slashCommands: [],
121+ tools: [],
122+ mcpServerStatuses: [],
123+ usePlatform: false,
124+ rules: [],
125+ };
126+
127+ mockDecodeSecretLocation
128+ .mockReturnValueOnce({
129+ secretType: SecretType.User,
130+ userSlug: "testuser",
131+ secretName: "api-key",
132+ })
133+ .mockReturnValueOnce({
134+ secretType: SecretType.Organization,
135+ orgSlug: "testorg",
136+ secretName: "api-key",
137+ });
138+
139+ const result = usesFreeTrialApiKey(config);
140+ expect(result).toBe(false);
141+ expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
142+ });
143+
144+ test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
145+ const config: BrowserSerializedContinueConfig = {
146+ modelsByRole: {
147+ chat: [
148+ {
149+ title: "Model 1",
150+ provider: "test",
151+ model: "test-model",
152+ apiKeyLocation: "user:testuser/api-key",
153+ underlyingProviderName: "test",
154+ },
155+ {
156+ title: "Free Trial Model",
157+ provider: "test",
158+ model: "free-trial-model",
159+ apiKeyLocation: "free_trial:owner/package/api-key",
160+ underlyingProviderName: "test",
161+ },
162+ ],
163+ edit: [],
164+ apply: [],
165+ summarize: [],
166+ autocomplete: [],
167+ rerank: [],
168+ embed: [],
169+ },
170+ selectedModelByRole: {
171+ chat: null,
172+ edit: null,
173+ apply: null,
174+ summarize: null,
175+ autocomplete: null,
176+ rerank: null,
177+ embed: null,
178+ },
179+ contextProviders: [],
180+ slashCommands: [],
181+ tools: [],
182+ mcpServerStatuses: [],
183+ usePlatform: false,
184+ rules: [],
185+ };
186+
187+ mockDecodeSecretLocation
188+ .mockReturnValueOnce({
189+ secretType: SecretType.User,
190+ userSlug: "testuser",
191+ secretName: "api-key",
192+ })
193+ .mockReturnValueOnce({
194+ secretType: SecretType.FreeTrial,
195+ blockSlug: { ownerSlug: "owner", packageSlug: "package" },
196+ secretName: "api-key",
197+ });
198+
199+ const result = usesFreeTrialApiKey(config);
200+ expect(result).toBe(true);
201+ expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
202+ });
203+
204+ test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
205+ const config: BrowserSerializedContinueConfig = {
206+ modelsByRole: {
207+ chat: [
208+ {
209+ title: "Model 1",
210+ provider: "test",
211+ model: "test-model",
212+ apiKeyLocation: "user:testuser/api-key",
213+ underlyingProviderName: "test",
214+ },
215+ ],
216+ edit: [
217+ {
218+ title: "Free Trial Edit Model",
219+ provider: "test",
220+ model: "free-trial-edit-model",
221+ apiKeyLocation: "free_trial:owner/package/api-key",
222+ underlyingProviderName: "test",
223+ },
224+ ],
225+ apply: [],
226+ summarize: [],
227+ autocomplete: [],
228+ rerank: [],
229+ embed: [],
230+ },
231+ selectedModelByRole: {
232+ chat: null,
233+ edit: null,
234+ apply: null,
235+ summarize: null,
236+ autocomplete: null,
237+ rerank: null,
238+ embed: null,
239+ },
240+ contextProviders: [],
241+ slashCommands: [],
242+ tools: [],
243+ mcpServerStatuses: [],
244+ usePlatform: false,
245+ rules: [],
246+ };
247+
248+ mockDecodeSecretLocation
249+ .mockReturnValueOnce({
250+ secretType: SecretType.User,
251+ userSlug: "testuser",
252+ secretName: "api-key",
253+ })
254+ .mockReturnValueOnce({
255+ secretType: SecretType.FreeTrial,
256+ blockSlug: { ownerSlug: "owner", packageSlug: "package" },
257+ secretName: "api-key",
258+ });
259+
260+ const result = usesFreeTrialApiKey(config);
261+ expect(result).toBe(true);
262+ });
263+
264+ test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
265+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
266+
267+ const config: BrowserSerializedContinueConfig = {
268+ modelsByRole: {
269+ chat: [
270+ {
271+ title: "Model 1",
272+ provider: "test",
273+ model: "test-model",
274+ apiKeyLocation: "invalid-secret-location",
275+ underlyingProviderName: "test",
276+ },
277+ ],
278+ edit: [],
279+ apply: [],
280+ summarize: [],
281+ autocomplete: [],
282+ rerank: [],
283+ embed: [],
284+ },
285+ selectedModelByRole: {
286+ chat: null,
287+ edit: null,
288+ apply: null,
289+ summarize: null,
290+ autocomplete: null,
291+ rerank: null,
292+ embed: null,
293+ },
294+ contextProviders: [],
295+ slashCommands: [],
296+ tools: [],
297+ mcpServerStatuses: [],
298+ usePlatform: false,
299+ rules: [],
300+ };
301+
302+ mockDecodeSecretLocation.mockImplementation(() => {
303+ throw new Error("Invalid secret location format");
304+ });
305+
306+ const result = usesFreeTrialApiKey(config);
307+ expect(result).toBe(false);
308+ expect(consoleSpy).toHaveBeenCalledWith(
309+ "Error checking for free trial API key:",
310+ expect.any(Error),
311+ );
312+
313+ consoleSpy.mockRestore();
314+ });
315+
316+ test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
317+ const config: BrowserSerializedContinueConfig = {
318+ modelsByRole: {
319+ chat: [],
320+ edit: [],
321+ apply: [],
322+ summarize: [],
323+ autocomplete: [],
324+ rerank: [],
325+ embed: [],
326+ },
327+ selectedModelByRole: {
328+ chat: null,
329+ edit: null,
330+ apply: null,
331+ summarize: null,
332+ autocomplete: null,
333+ rerank: null,
334+ embed: null,
335+ },
336+ contextProviders: [],
337+ slashCommands: [],
338+ tools: [],
339+ mcpServerStatuses: [],
340+ usePlatform: false,
341+ rules: [],
342+ };
343+
344+ const result = usesFreeTrialApiKey(config);
345+ expect(result).toBe(false);
346+ expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
347+ });
348+});
deleted core/config/util.test.ts +0 −45
@@ -1,45 +0,0 @@
1-import { PromptTemplate } from "..";
2-import { serializePromptTemplates } from "./util";
3-
4-describe("serializePromptTemplates", () => {
5- it("should return undefined for undefined input", () => {
6- expect(serializePromptTemplates(undefined)).toBeUndefined();
7- });
8-
9- it("should convert function templates to empty strings", () => {
10- const functionTemplate: PromptTemplate = () => "Generated template";
11- const templates: Record<string, PromptTemplate> = {
12- template1: functionTemplate,
13- };
14-
15- const result = serializePromptTemplates(templates);
16-
17- expect(result).toEqual({ template1: "" });
18- });
19-
20- it("should pass through string templates unchanged", () => {
21- const templates: Record<string, PromptTemplate> = {
22- template1: "This is a static template",
23- template2: "Another static template",
24- };
25-
26- const result = serializePromptTemplates(templates);
27-
28- expect(result).toEqual(templates);
29- });
30-
31- it("should handle mixed template types", () => {
32- const functionTemplate: PromptTemplate = () => "Generated template";
33- const templates: Record<string, PromptTemplate> = {
34- function: functionTemplate,
35- string: "This is a static template",
36- };
37-
38- const result = serializePromptTemplates(templates);
39-
40- expect(result).toEqual({
41- function: "",
42- string: "This is a static template",
43- });
44- });
45-});
added core/config/util.vitest.ts +46 −0
@@ -0,0 +1,46 @@
1+import { describe, expect, it } from "vitest";
2+import { PromptTemplate } from "..";
3+import { serializePromptTemplates } from "./util";
4+
5+describe("serializePromptTemplates", () => {
6+ it("should return undefined for undefined input", () => {
7+ expect(serializePromptTemplates(undefined)).toBeUndefined();
8+ });
9+
10+ it("should convert function templates to empty strings", () => {
11+ const functionTemplate: PromptTemplate = () => "Generated template";
12+ const templates: Record<string, PromptTemplate> = {
13+ template1: functionTemplate,
14+ };
15+
16+ const result = serializePromptTemplates(templates);
17+
18+ expect(result).toEqual({ template1: "" });
19+ });
20+
21+ it("should pass through string templates unchanged", () => {
22+ const templates: Record<string, PromptTemplate> = {
23+ template1: "This is a static template",
24+ template2: "Another static template",
25+ };
26+
27+ const result = serializePromptTemplates(templates);
28+
29+ expect(result).toEqual(templates);
30+ });
31+
32+ it("should handle mixed template types", () => {
33+ const functionTemplate: PromptTemplate = () => "Generated template";
34+ const templates: Record<string, PromptTemplate> = {
35+ function: functionTemplate,
36+ string: "This is a static template",
37+ };
38+
39+ const result = serializePromptTemplates(templates);
40+
41+ expect(result).toEqual({
42+ function: "",
43+ string: "This is a static template",
44+ });
45+ });
46+});
deleted core/config/workspace/workspaceBlocks.test.ts +0 −168
@@ -1,168 +0,0 @@
1-import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
2-import { describe, expect, test } from "@jest/globals";
3-import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
4-
5-describe("getFileContent", () => {
6- test("returns markdown content for rules block type", () => {
7- const result = getFileContent("rules");
8- expect(result).toContain("Your rule content");
9- expect(result).toContain("A description of your rule");
10- });
11-
12- test("returns YAML content for non-rules block types", () => {
13- const result = getFileContent("models");
14- expect(result).toContain("name: New model");
15- expect(result).toContain("version: 0.0.1");
16- expect(result).toContain("schema: v1");
17- expect(result).toContain("models:");
18- expect(result).toContain("provider: anthropic");
19- });
20-
21- test("generates correct YAML for different block types", () => {
22- const contextResult = getFileContent("context");
23- expect(contextResult).toContain("name: New context");
24- expect(contextResult).toContain("context:");
25- expect(contextResult).toContain("provider: file");
26-
27- const docsResult = getFileContent("docs");
28- expect(docsResult).toContain("name: New doc");
29- expect(docsResult).toContain("docs:");
30- expect(docsResult).toContain("startUrl: https://docs.continue.dev");
31-
32- const promptsResult = getFileContent("prompts");
33- expect(promptsResult).toContain("name: New prompt");
34- expect(promptsResult).toContain("prompts:");
35- expect(promptsResult).toContain("thorough suite of unit tests");
36-
37- const mcpResult = getFileContent("mcpServers");
38- expect(mcpResult).toContain("name: New MCP server");
39- expect(mcpResult).toContain("mcpServers:");
40- expect(mcpResult).toContain("command: npx");
41- });
42-});
43-
44-describe("findAvailableFilename", () => {
45- test("returns base filename when it doesn't exist", async () => {
46- const mockFileExists = async (uri: string) => false;
47-
48- const result = await findAvailableFilename(
49- "/workspace/.continue/models",
50- "models",
51- mockFileExists,
52- );
53-
54- expect(result).toBe("/workspace/.continue/models/new-model.yaml");
55- });
56-
57- test("returns filename with counter when base exists", async () => {
58- const mockFileExists = async (uri: string) => {
59- return uri === "/workspace/.continue/models/new-model.yaml";
60- };
61-
62- const result = await findAvailableFilename(
63- "/workspace/.continue/models",
64- "models",
65- mockFileExists,
66- );
67-
68- expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
69- });
70-
71- test("increments counter until available filename is found", async () => {
72- const existingFiles = new Set([
73- "/workspace/.continue/context/new-context.yaml",
74- "/workspace/.continue/context/new-context-1.yaml",
75- "/workspace/.continue/context/new-context-2.yaml",
76- ]);
77-
78- const mockFileExists = async (uri: string) => {
79- return existingFiles.has(uri);
80- };
81-
82- const result = await findAvailableFilename(
83- "/workspace/.continue/context",
84- "context",
85- mockFileExists,
86- );
87-
88- expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
89- });
90-
91- test("handles different block types correctly with proper extensions", async () => {
92- const mockFileExists = async (uri: string) => false;
93-
94- const testCases: Array<{ blockType: BlockType; expected: string }> = [
95- { blockType: "models", expected: "/test/new-model.yaml" },
96- { blockType: "context", expected: "/test/new-context.yaml" },
97- { blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
98- { blockType: "docs", expected: "/test/new-doc.yaml" },
99- { blockType: "prompts", expected: "/test/new-prompt.yaml" },
100- { blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
101- ];
102-
103- for (const { blockType, expected } of testCases) {
104- const result = await findAvailableFilename(
105- "/test",
106- blockType,
107- mockFileExists,
108- );
109- expect(result).toBe(expected);
110- }
111- });
112-
113- test("respects custom extension parameter", async () => {
114- const mockFileExists = async (uri: string) => false;
115-
116- const result = await findAvailableFilename(
117- "/test",
118- "models",
119- mockFileExists,
120- "json",
121- );
122-
123- expect(result).toBe("/test/new-model.json");
124- });
125-
126- test("handles rules markdown files with counter", async () => {
127- const existingFiles = new Set([
128- `/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
129- `/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
130- ]);
131-
132- const mockFileExists = async (uri: string) => {
133- return existingFiles.has(uri);
134- };
135-
136- const result = await findAvailableFilename(
137- "/workspace/.continue/rules",
138- "rules",
139- mockFileExists,
140- );
141-
142- expect(result).toBe(
143- `/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
144- );
145- });
146-
147- test("handles large counter values", async () => {
148- const existingFiles = new Set(
149- Array.from({ length: 100 }, (_, i) =>
150- i === 0
151- ? "/workspace/.continue/prompts/new-prompt.yaml"
152- : `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
153- ),
154- );
155-
156- const mockFileExists = async (uri: string) => {
157- return existingFiles.has(uri);
158- };
159-
160- const result = await findAvailableFilename(
161- "/workspace/.continue/prompts",
162- "prompts",
163- mockFileExists,
164- );
165-
166- expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
167- });
168-});
added core/config/workspace/workspaceBlocks.vitest.ts +168 −0
@@ -0,0 +1,168 @@
1+import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
2+import { describe, expect, test } from "vitest";
3+import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
4+
5+describe("getFileContent", () => {
6+ test("returns markdown content for rules block type", () => {
7+ const result = getFileContent("rules");
8+ expect(result).toContain("Your rule content");
9+ expect(result).toContain("A description of your rule");
10+ });
11+
12+ test("returns YAML content for non-rules block types", () => {
13+ const result = getFileContent("models");
14+ expect(result).toContain("name: New model");
15+ expect(result).toContain("version: 0.0.1");
16+ expect(result).toContain("schema: v1");
17+ expect(result).toContain("models:");
18+ expect(result).toContain("provider: anthropic");
19+ });
20+
21+ test("generates correct YAML for different block types", () => {
22+ const contextResult = getFileContent("context");
23+ expect(contextResult).toContain("name: New context");
24+ expect(contextResult).toContain("context:");
25+ expect(contextResult).toContain("provider: file");
26+
27+ const docsResult = getFileContent("docs");
28+ expect(docsResult).toContain("name: New doc");
29+ expect(docsResult).toContain("docs:");
30+ expect(docsResult).toContain("startUrl: https://docs.continue.dev");
31+
32+ const promptsResult = getFileContent("prompts");
33+ expect(promptsResult).toContain("name: New prompt");
34+ expect(promptsResult).toContain("prompts:");
35+ expect(promptsResult).toContain("thorough suite of unit tests");
36+
37+ const mcpResult = getFileContent("mcpServers");
38+ expect(mcpResult).toContain("name: New MCP server");
39+ expect(mcpResult).toContain("mcpServers:");
40+ expect(mcpResult).toContain("command: npx");
41+ });
42+});
43+
44+describe("findAvailableFilename", () => {
45+ test("returns base filename when it doesn't exist", async () => {
46+ const mockFileExists = async (uri: string) => false;
47+
48+ const result = await findAvailableFilename(
49+ "/workspace/.continue/models",
50+ "models",
51+ mockFileExists,
52+ );
53+
54+ expect(result).toBe("/workspace/.continue/models/new-model.yaml");
55+ });
56+
57+ test("returns filename with counter when base exists", async () => {
58+ const mockFileExists = async (uri: string) => {
59+ return uri === "/workspace/.continue/models/new-model.yaml";
60+ };
61+
62+ const result = await findAvailableFilename(
63+ "/workspace/.continue/models",
64+ "models",
65+ mockFileExists,
66+ );
67+
68+ expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
69+ });
70+
71+ test("increments counter until available filename is found", async () => {
72+ const existingFiles = new Set([
73+ "/workspace/.continue/context/new-context.yaml",
74+ "/workspace/.continue/context/new-context-1.yaml",
75+ "/workspace/.continue/context/new-context-2.yaml",
76+ ]);
77+
78+ const mockFileExists = async (uri: string) => {
79+ return existingFiles.has(uri);
80+ };
81+
82+ const result = await findAvailableFilename(
83+ "/workspace/.continue/context",
84+ "context",
85+ mockFileExists,
86+ );
87+
88+ expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
89+ });
90+
91+ test("handles different block types correctly with proper extensions", async () => {
92+ const mockFileExists = async (uri: string) => false;
93+
94+ const testCases: Array<{ blockType: BlockType; expected: string }> = [
95+ { blockType: "models", expected: "/test/new-model.yaml" },
96+ { blockType: "context", expected: "/test/new-context.yaml" },
97+ { blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
98+ { blockType: "docs", expected: "/test/new-doc.yaml" },
99+ { blockType: "prompts", expected: "/test/new-prompt.yaml" },
100+ { blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
101+ ];
102+
103+ for (const { blockType, expected } of testCases) {
104+ const result = await findAvailableFilename(
105+ "/test",
106+ blockType,
107+ mockFileExists,
108+ );
109+ expect(result).toBe(expected);
110+ }
111+ });
112+
113+ test("respects custom extension parameter", async () => {
114+ const mockFileExists = async (uri: string) => false;
115+
116+ const result = await findAvailableFilename(
117+ "/test",
118+ "models",
119+ mockFileExists,
120+ "json",
121+ );
122+
123+ expect(result).toBe("/test/new-model.json");
124+ });
125+
126+ test("handles rules markdown files with counter", async () => {
127+ const existingFiles = new Set([
128+ `/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
129+ `/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
130+ ]);
131+
132+ const mockFileExists = async (uri: string) => {
133+ return existingFiles.has(uri);
134+ };
135+
136+ const result = await findAvailableFilename(
137+ "/workspace/.continue/rules",
138+ "rules",
139+ mockFileExists,
140+ );
141+
142+ expect(result).toBe(
143+ `/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
144+ );
145+ });
146+
147+ test("handles large counter values", async () => {
148+ const existingFiles = new Set(
149+ Array.from({ length: 100 }, (_, i) =>
150+ i === 0
151+ ? "/workspace/.continue/prompts/new-prompt.yaml"
152+ : `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
153+ ),
154+ );
155+
156+ const mockFileExists = async (uri: string) => {
157+ return existingFiles.has(uri);
158+ };
159+
160+ const result = await findAvailableFilename(
161+ "/workspace/.continue/prompts",
162+ "prompts",
163+ mockFileExists,
164+ );
165+
166+ expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
167+ });
168+});
modified core/config/yaml/loadYaml.ts +1 −8
@@ -26,7 +26,6 @@
2626 RuleWithSource,
2727 } from "../..";
2828 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
29-import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
3029 import DocsContextProvider from "../../context/providers/DocsContextProvider";
3130 import FileContextProvider from "../../context/providers/FileContextProvider";
3231 import { contextProviderClassFromName } from "../../context/providers/index";
@@ -385,13 +384,7 @@
385384 }
386385
387386 // Context providers
388- const codebaseContextParams: IContextProvider[] =
389- (config.context || []).find((cp) => cp.provider === "codebase")?.params ||
390- {};
391- const DEFAULT_CONTEXT_PROVIDERS = [
392- new FileContextProvider({}),
393- new CodebaseContextProvider(codebaseContextParams),
394- ];
387+ const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
395388
396389 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
397390 ({ description: { title } }) => title,
deleted core/context/mcp/MCPConnection.test.ts +0 −288
@@ -1,288 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3-import MCPConnection from "./MCPConnection";
4-
5-describe("MCPConnection", () => {
6- beforeEach(() => {
7- jest.restoreAllMocks();
8- });
9-
10- describe("constructor", () => {
11- it("should create instance with stdio transport", () => {
12- const options = {
13- name: "test-mcp",
14- id: "test-id",
15- transport: {
16- type: "stdio" as const,
17- command: "test-cmd",
18- args: ["--test"],
19- env: { TEST: "true" },
20- },
21- };
22-
23- const conn = new MCPConnection(options);
24- expect(conn).toBeInstanceOf(MCPConnection);
25- expect(conn.status).toBe("not-connected");
26- });
27-
28- it("should create instance with websocket transport", () => {
29- const options = {
30- name: "test-mcp",
31- id: "test-id",
32- transport: {
33- type: "websocket" as const,
34- url: "ws://test.com",
35- },
36- };
37-
38- const conn = new MCPConnection(options);
39- expect(conn).toBeInstanceOf(MCPConnection);
40- expect(conn.status).toBe("not-connected");
41- });
42-
43- it("should create instance with SSE transport", () => {
44- const options = {
45- name: "test-mcp",
46- id: "test-id",
47- transport: {
48- type: "sse" as const,
49- url: "http://test.com/events",
50- },
51- };
52-
53- const conn = new MCPConnection(options);
54- expect(conn).toBeInstanceOf(MCPConnection);
55- expect(conn.status).toBe("not-connected");
56- });
57-
58- it("should create instance with SSE transport and custom headers", () => {
59- const options = {
60- name: "test-mcp",
61- id: "test-id",
62- transport: {
63- type: "sse" as const,
64- url: "http://test.com/events",
65- requestOptions: {
66- headers: {
67- Authorization: "Bearer token123",
68- "X-Custom-Header": "custom-value",
69- },
70- },
71- },
72- };
73-
74- const conn = new MCPConnection(options);
75- expect(conn).toBeInstanceOf(MCPConnection);
76- expect(conn.status).toBe("not-connected");
77- });
78-
79- it("should throw on invalid transport type", () => {
80- const options = {
81- name: "test-mcp",
82- id: "test-id",
83- transport: {
84- type: "invalid",
85- } as any,
86- };
87-
88- expect(() => new MCPConnection(options)).toThrow(
89- "Unsupported transport type: invalid",
90- );
91- });
92- });
93-
94- describe("getStatus", () => {
95- it("should return current status", () => {
96- const options = {
97- name: "test-mcp",
98- id: "test-id",
99- transport: {
100- type: "stdio" as const,
101- command: "test",
102- args: [],
103- },
104- };
105-
106- const conn = new MCPConnection(options);
107- const status = conn.getStatus();
108-
109- expect(status).toEqual({
110- ...options,
111- errors: [],
112- prompts: [],
113- resources: [],
114- resourceTemplates: [],
115- tools: [],
116- status: "not-connected",
117- });
118- });
119- });
120-
121- describe("connectClient", () => {
122- const options = {
123- name: "test-mcp",
124- id: "test-id",
125- transport: {
126- type: "stdio" as const,
127- command: "test-cmd",
128- args: [],
129- },
130- };
131-
132- it("should connect successfully", async () => {
133- const conn = new MCPConnection(options);
134- const mockConnect = jest
135- .spyOn(Client.prototype, "connect")
136- .mockResolvedValue(undefined);
137- const mockGetServerCapabilities = jest
138- .spyOn(Client.prototype, "getServerCapabilities")
139- .mockReturnValue({
140- resources: {},
141- tools: {},
142- prompts: {},
143- });
144-
145- const mockListResources = jest
146- .spyOn(Client.prototype, "listResources")
147- .mockResolvedValue({
148- resources: [{ name: "test-resource", uri: "test-uri" }],
149- });
150- const mockListTools = jest
151- .spyOn(Client.prototype, "listTools")
152- .mockResolvedValue({
153- tools: [
154- {
155- name: "test-tool",
156- inputSchema: {
157- type: "object",
158- },
159- },
160- ],
161- });
162- const mockListPrompts = jest
163- .spyOn(Client.prototype, "listPrompts")
164- .mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
165-
166- const abortController = new AbortController();
167- await conn.connectClient(false, abortController.signal);
168-
169- expect(conn.status).toBe("connected");
170- expect(conn.resources).toHaveLength(1);
171- expect(conn.tools).toHaveLength(1);
172- expect(conn.prompts).toHaveLength(1);
173- expect(mockConnect).toHaveBeenCalled();
174- });
175-
176- it("should handle custom connection timeout", async () => {
177- const conn = new MCPConnection({ ...options, timeout: 1500 });
178- const mockConnect = jest
179- .spyOn(Client.prototype, "connect")
180- .mockImplementation(
181- () => new Promise((resolve) => setTimeout(resolve, 1000)),
182- );
183-
184- const abortController = new AbortController();
185- await conn.connectClient(false, abortController.signal);
186-
187- expect(conn.status).toBe("connected");
188- expect(mockConnect).toHaveBeenCalled();
189- });
190-
191- it("should handle connection timeout", async () => {
192- const conn = new MCPConnection({ ...options, timeout: 1 });
193- const mockConnect = jest
194- .spyOn(Client.prototype, "connect")
195- .mockImplementation(
196- () => new Promise((resolve) => setTimeout(resolve, 100)),
197- );
198-
199- const abortController = new AbortController();
200- await conn.connectClient(false, abortController.signal);
201-
202- expect(conn.status).toBe("error");
203- expect(conn.errors[0]).toContain("Failed to connect");
204- expect(mockConnect).toHaveBeenCalled();
205- });
206-
207- it("should handle already connected state", async () => {
208- const conn = new MCPConnection(options);
209- conn.status = "connected";
210-
211- const mockConnect = jest.spyOn(Client.prototype, "connect");
212- const abortController = new AbortController();
213-
214- await conn.connectClient(false, abortController.signal);
215-
216- expect(mockConnect).not.toHaveBeenCalled();
217- expect(conn.status).toBe("connected");
218- });
219-
220- it("should handle transport errors", async () => {
221- const conn = new MCPConnection(options);
222- const mockConnect = jest
223- .spyOn(Client.prototype, "connect")
224- .mockRejectedValue(new Error("spawn test-cmd ENOENT"));
225-
226- const abortController = new AbortController();
227- await conn.connectClient(false, abortController.signal);
228-
229- expect(conn.status).toBe("error");
230- expect(conn.errors[0]).toContain('command "test-cmd" not found');
231- expect(mockConnect).toHaveBeenCalled();
232- });
233-
234- it.skip("should include stderr output in error message when stdio command fails", async () => {
235- // Clear any existing mocks to ensure we get real behavior
236- jest.restoreAllMocks();
237-
238- // Use a command that will definitely fail and produce stderr output
239- const failingOptions = {
240- name: "failing-mcp",
241- id: "failing-id",
242- transport: {
243- type: "stdio" as const,
244- command: "node",
245- args: [
246- "-e",
247- "console.error('Custom error message from stderr'); process.exit(1);",
248- ],
249- },
250- timeout: 5000, // Give enough time for the command to run and fail
251- };
252-
253- const conn = new MCPConnection(failingOptions);
254- const abortController = new AbortController();
255-
256- await conn.connectClient(false, abortController.signal);
257-
258- expect(conn.status).toBe("error");
259- expect(conn.errors).toHaveLength(1);
260- expect(conn.errors[0]).toContain("Failed to connect");
261- expect(conn.errors[0]).toContain("Process output:");
262- expect(conn.errors[0]).toContain("STDERR:");
263- expect(conn.errors[0]).toContain("Custom error message from stderr");
264- });
265- });
266-
267- describe.skip("actually connect to Filesystem MCP", () => {
268- it("should connect and include correct tools", async () => {
269- const conn = new MCPConnection({
270- id: "filesystem",
271- name: "Filesystem",
272- transport: {
273- type: "stdio" as const,
274- command: "npx",
275- args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
276- },
277- });
278-
279- try {
280- const abortController = new AbortController();
281- await conn.connectClient(false, abortController.signal);
282- expect(conn.status).toBe("connected");
283- } finally {
284- await conn.disconnect();
285- }
286- });
287- });
288-});
added core/context/mcp/MCPConnection.vitest.ts +288 −0
@@ -0,0 +1,288 @@
1+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2+import { beforeEach, describe, expect, it, vi } from "vitest";
3+import MCPConnection from "./MCPConnection";
4+
5+describe("MCPConnection", () => {
6+ beforeEach(() => {
7+ vi.restoreAllMocks();
8+ });
9+
10+ describe("constructor", () => {
11+ it("should create instance with stdio transport", () => {
12+ const options = {
13+ name: "test-mcp",
14+ id: "test-id",
15+ transport: {
16+ type: "stdio" as const,
17+ command: "test-cmd",
18+ args: ["--test"],
19+ env: { TEST: "true" },
20+ },
21+ };
22+
23+ const conn = new MCPConnection(options);
24+ expect(conn).toBeInstanceOf(MCPConnection);
25+ expect(conn.status).toBe("not-connected");
26+ });
27+
28+ it("should create instance with websocket transport", () => {
29+ const options = {
30+ name: "test-mcp",
31+ id: "test-id",
32+ transport: {
33+ type: "websocket" as const,
34+ url: "ws://test.com",
35+ },
36+ };
37+
38+ const conn = new MCPConnection(options);
39+ expect(conn).toBeInstanceOf(MCPConnection);
40+ expect(conn.status).toBe("not-connected");
41+ });
42+
43+ it("should create instance with SSE transport", () => {
44+ const options = {
45+ name: "test-mcp",
46+ id: "test-id",
47+ transport: {
48+ type: "sse" as const,
49+ url: "http://test.com/events",
50+ },
51+ };
52+
53+ const conn = new MCPConnection(options);
54+ expect(conn).toBeInstanceOf(MCPConnection);
55+ expect(conn.status).toBe("not-connected");
56+ });
57+
58+ it("should create instance with SSE transport and custom headers", () => {
59+ const options = {
60+ name: "test-mcp",
61+ id: "test-id",
62+ transport: {
63+ type: "sse" as const,
64+ url: "http://test.com/events",
65+ requestOptions: {
66+ headers: {
67+ Authorization: "Bearer token123",
68+ "X-Custom-Header": "custom-value",
69+ },
70+ },
71+ },
72+ };
73+
74+ const conn = new MCPConnection(options);
75+ expect(conn).toBeInstanceOf(MCPConnection);
76+ expect(conn.status).toBe("not-connected");
77+ });
78+
79+ it("should throw on invalid transport type", () => {
80+ const options = {
81+ name: "test-mcp",
82+ id: "test-id",
83+ transport: {
84+ type: "invalid",
85+ } as any,
86+ };
87+
88+ expect(() => new MCPConnection(options)).toThrow(
89+ "Unsupported transport type: invalid",
90+ );
91+ });
92+ });
93+
94+ describe("getStatus", () => {
95+ it("should return current status", () => {
96+ const options = {
97+ name: "test-mcp",
98+ id: "test-id",
99+ transport: {
100+ type: "stdio" as const,
101+ command: "test",
102+ args: [],
103+ },
104+ };
105+
106+ const conn = new MCPConnection(options);
107+ const status = conn.getStatus();
108+
109+ expect(status).toEqual({
110+ ...options,
111+ errors: [],
112+ prompts: [],
113+ resources: [],
114+ resourceTemplates: [],
115+ tools: [],
116+ status: "not-connected",
117+ });
118+ });
119+ });
120+
121+ describe("connectClient", () => {
122+ const options = {
123+ name: "test-mcp",
124+ id: "test-id",
125+ transport: {
126+ type: "stdio" as const,
127+ command: "test-cmd",
128+ args: [],
129+ },
130+ };
131+
132+ it("should connect successfully", async () => {
133+ const conn = new MCPConnection(options);
134+ const mockConnect = vi
135+ .spyOn(Client.prototype, "connect")
136+ .mockResolvedValue(undefined);
137+ const mockGetServerCapabilities = vi
138+ .spyOn(Client.prototype, "getServerCapabilities")
139+ .mockReturnValue({
140+ resources: {},
141+ tools: {},
142+ prompts: {},
143+ });
144+
145+ const mockListResources = vi
146+ .spyOn(Client.prototype, "listResources")
147+ .mockResolvedValue({
148+ resources: [{ name: "test-resource", uri: "test-uri" }],
149+ });
150+ const mockListTools = vi
151+ .spyOn(Client.prototype, "listTools")
152+ .mockResolvedValue({
153+ tools: [
154+ {
155+ name: "test-tool",
156+ inputSchema: {
157+ type: "object",
158+ },
159+ },
160+ ],
161+ });
162+ const mockListPrompts = vi
163+ .spyOn(Client.prototype, "listPrompts")
164+ .mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
165+
166+ const abortController = new AbortController();
167+ await conn.connectClient(false, abortController.signal);
168+
169+ expect(conn.status).toBe("connected");
170+ expect(conn.resources).toHaveLength(1);
171+ expect(conn.tools).toHaveLength(1);
172+ expect(conn.prompts).toHaveLength(1);
173+ expect(mockConnect).toHaveBeenCalled();
174+ });
175+
176+ it("should handle custom connection timeout", async () => {
177+ const conn = new MCPConnection({ ...options, timeout: 1500 });
178+ const mockConnect = vi
179+ .spyOn(Client.prototype, "connect")
180+ .mockImplementation(
181+ () => new Promise((resolve) => setTimeout(resolve, 1000)),
182+ );
183+
184+ const abortController = new AbortController();
185+ await conn.connectClient(false, abortController.signal);
186+
187+ expect(conn.status).toBe("connected");
188+ expect(mockConnect).toHaveBeenCalled();
189+ });
190+
191+ it("should handle connection timeout", async () => {
192+ const conn = new MCPConnection({ ...options, timeout: 1 });
193+ const mockConnect = vi
194+ .spyOn(Client.prototype, "connect")
195+ .mockImplementation(
196+ () => new Promise((resolve) => setTimeout(resolve, 100)),
197+ );
198+
199+ const abortController = new AbortController();
200+ await conn.connectClient(false, abortController.signal);
201+
202+ expect(conn.status).toBe("error");
203+ expect(conn.errors[0]).toContain("Failed to connect");
204+ expect(mockConnect).toHaveBeenCalled();
205+ });
206+
207+ it("should handle already connected state", async () => {
208+ const conn = new MCPConnection(options);
209+ conn.status = "connected";
210+
211+ const mockConnect = vi.spyOn(Client.prototype, "connect");
212+ const abortController = new AbortController();
213+
214+ await conn.connectClient(false, abortController.signal);
215+
216+ expect(mockConnect).not.toHaveBeenCalled();
217+ expect(conn.status).toBe("connected");
218+ });
219+
220+ it("should handle transport errors", async () => {
221+ const conn = new MCPConnection(options);
222+ const mockConnect = vi
223+ .spyOn(Client.prototype, "connect")
224+ .mockRejectedValue(new Error("spawn test-cmd ENOENT"));
225+
226+ const abortController = new AbortController();
227+ await conn.connectClient(false, abortController.signal);
228+
229+ expect(conn.status).toBe("error");
230+ expect(conn.errors[0]).toContain('command "test-cmd" not found');
231+ expect(mockConnect).toHaveBeenCalled();
232+ });
233+
234+ it.skip("should include stderr output in error message when stdio command fails", async () => {
235+ // Clear any existing mocks to ensure we get real behavior
236+ vi.restoreAllMocks();
237+
238+ // Use a command that will definitely fail and produce stderr output
239+ const failingOptions = {
240+ name: "failing-mcp",
241+ id: "failing-id",
242+ transport: {
243+ type: "stdio" as const,
244+ command: "node",
245+ args: [
246+ "-e",
247+ "console.error('Custom error message from stderr'); process.exit(1);",
248+ ],
249+ },
250+ timeout: 5000, // Give enough time for the command to run and fail
251+ };
252+
253+ const conn = new MCPConnection(failingOptions);
254+ const abortController = new AbortController();
255+
256+ await conn.connectClient(false, abortController.signal);
257+
258+ expect(conn.status).toBe("error");
259+ expect(conn.errors).toHaveLength(1);
260+ expect(conn.errors[0]).toContain("Failed to connect");
261+ expect(conn.errors[0]).toContain("Process output:");
262+ expect(conn.errors[0]).toContain("STDERR:");
263+ expect(conn.errors[0]).toContain("Custom error message from stderr");
264+ });
265+ });
266+
267+ describe.skip("actually connect to Filesystem MCP", () => {
268+ it("should connect and include correct tools", async () => {
269+ const conn = new MCPConnection({
270+ id: "filesystem",
271+ name: "Filesystem",
272+ transport: {
273+ type: "stdio" as const,
274+ command: "npx",
275+ args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
276+ },
277+ });
278+
279+ try {
280+ const abortController = new AbortController();
281+ await conn.connectClient(false, abortController.signal);
282+ expect(conn.status).toBe("connected");
283+ } finally {
284+ await conn.disconnect();
285+ }
286+ });
287+ });
288+});
deleted core/context/mcp/MCPManagerSingleton.test.ts +0 −219
@@ -1,219 +0,0 @@
1-import { MCPOptions } from "../..";
2-import MCPConnection from "./MCPConnection";
3-import { MCPManagerSingleton } from "./MCPManagerSingleton";
4-
5-// Create test versions with stubbed behavior
6-class TestMCPConnection extends MCPConnection {
7- constructor(options: MCPOptions) {
8- super(options);
9-
10- // Override with test implementations
11- this.client = {
12- close: async () => {},
13- connect: async () => {},
14- getServerCapabilities: () => ({}),
15- listResources: async () => ({ resources: [] }),
16- listTools: async () => ({ tools: [] }),
17- listPrompts: async () => ({ prompts: [] }),
18- } as any;
19-
20- this.abortController = new AbortController();
21- this.connectClient = jest.fn().mockResolvedValue(undefined);
22- this.getStatus = jest
23- .fn()
24- .mockReturnValue({ status: "connected", errors: [] });
25- }
26-}
27-
28-describe("MCPManagerSingleton", () => {
29- let manager: MCPManagerSingleton;
30- const testOptions: MCPOptions = {
31- name: "test-mcp",
32- id: "test-id",
33- transport: {
34- type: "stdio",
35- command: "test-command",
36- args: [],
37- },
38- };
39-
40- beforeEach(() => {
41- // Reset singleton
42- (MCPManagerSingleton as any).instance = undefined;
43- manager = MCPManagerSingleton.getInstance();
44-
45- // Replace the connections map with our own that will use TestMCPConnection
46- const connectionsMap = new Map<string, MCPConnection>();
47- Object.defineProperty(manager, "connections", {
48- value: connectionsMap,
49- writable: true,
50- });
51-
52- // Override createConnection to use our TestMCPConnection
53- manager.createConnection = function (
54- id: string,
55- options: MCPOptions,
56- ): MCPConnection {
57- if (!this.connections.has(id)) {
58- const connection = new TestMCPConnection(options);
59- this.connections.set(id, connection);
60- return connection;
61- } else {
62- return this.connections.get(id)!;
63- }
64- };
65- });
66-
67- describe("getInstance", () => {
68- it("should create singleton instance", () => {
69- const instance1 = MCPManagerSingleton.getInstance();
70- const instance2 = MCPManagerSingleton.getInstance();
71- expect(instance1).toBe(instance2);
72- });
73- });
74-
75- describe("createConnection", () => {
76- it("should create new connection if none exists", () => {
77- const connection = manager.createConnection("test-id", testOptions);
78- expect(connection).toBeInstanceOf(MCPConnection);
79- });
80-
81- it("should return existing connection if exists", () => {
82- const connection1 = manager.createConnection("test-id", testOptions);
83- const connection2 = manager.createConnection("test-id", testOptions);
84- expect(connection1).toBe(connection2);
85- });
86- });
87-
88- describe("getConnection", () => {
89- it("should return undefined for non-existent connection", () => {
90- expect(manager.getConnection("non-existent")).toBeUndefined();
91- });
92-
93- it("should return existing connection", () => {
94- const connection = manager.createConnection("test-id", testOptions);
95- expect(manager.getConnection("test-id")).toBe(connection);
96- });
97- });
98-
99- describe("removeConnection", () => {
100- it("should remove connection and close client", async () => {
101- // Create a spy on the close method
102- const connection = manager.createConnection(
103- "test-id",
104- testOptions,
105- ) as TestMCPConnection;
106- const closeSpy = jest.spyOn(connection.client, "close");
107-
108- await manager.removeConnection("test-id");
109-
110- expect(closeSpy).toHaveBeenCalled();
111- expect(manager.getConnection("test-id")).toBeUndefined();
112- });
113-
114- it("should handle non-existent connection", async () => {
115- await expect(
116- manager.removeConnection("non-existent"),
117- ).resolves.toBeUndefined();
118- });
119- });
120-
121- describe("setConnections", () => {
122- it("should add new connections", () => {
123- const servers = [testOptions];
124- manager.setConnections(servers, false);
125- expect(manager.getConnection(testOptions.id)).toBeInstanceOf(
126- MCPConnection,
127- );
128- });
129-
130- it("should remove old connections", () => {
131- // Create initial connection
132- const connection = manager.createConnection(
133- "test-id",
134- testOptions,
135- ) as TestMCPConnection;
136- const abortSpy = jest.spyOn(connection.abortController, "abort");
137- const closeSpy = jest.spyOn(connection.client, "close");
138-
139- // Remove it by setting empty server list
140- manager.setConnections([], false);
141-
142- expect(abortSpy).toHaveBeenCalled();
143- expect(closeSpy).toHaveBeenCalled();
144- expect(manager.getConnection("test-id")).toBeUndefined();
145- });
146- });
147-
148- describe("refreshConnection", () => {
149- it("should refresh specific connection", async () => {
150- const connection = manager.createConnection(
151- "test-id",
152- testOptions,
153- ) as TestMCPConnection;
154-
155- await manager.refreshConnection("test-id");
156-
157- expect(connection.connectClient).toHaveBeenCalledWith(
158- true,
159- expect.any(AbortSignal),
160- );
161- });
162-
163- it("should throw error for non-existent connection", async () => {
164- await expect(manager.refreshConnection("non-existent")).rejects.toThrow(
165- "MCP Connection non-existent not found",
166- );
167- });
168- });
169-
170- describe("refreshConnections", () => {
171- it("should refresh all connections", async () => {
172- const connection1 = manager.createConnection("test-id-1", {
173- ...testOptions,
174- id: "test-id-1",
175- }) as TestMCPConnection;
176-
177- const connection2 = manager.createConnection("test-id-2", {
178- ...testOptions,
179- id: "test-id-2",
180- }) as TestMCPConnection;
181-
182- await manager.refreshConnections(true);
183-
184- expect(connection1.connectClient).toHaveBeenCalledWith(
185- true,
186- expect.any(AbortSignal),
187- );
188- expect(connection2.connectClient).toHaveBeenCalledWith(
189- true,
190- expect.any(AbortSignal),
191- );
192- });
193-
194- it("should call onConnectionsRefreshed if defined", async () => {
195- const mockCallback = jest.fn();
196- manager.onConnectionsRefreshed = mockCallback;
197- manager.createConnection("test-id", testOptions);
198-
199- await manager.refreshConnections(true);
200-
201- expect(mockCallback).toHaveBeenCalled();
202- });
203- });
204-
205- describe("getStatuses", () => {
206- it("should return statuses for all connections", () => {
207- const connection = manager.createConnection(
208- "test-id",
209- testOptions,
210- ) as TestMCPConnection;
211- const mockStatus = { status: "connected", errors: [] };
212- connection.getStatus = jest.fn().mockReturnValue(mockStatus);
213-
214- const statuses = manager.getStatuses();
215- expect(statuses).toHaveLength(1);
216- expect(statuses[0]).toEqual({ ...mockStatus, client: connection.client });
217- });
218- });
219-});
added core/context/mcp/MCPManagerSingleton.vitest.ts +219 −0
@@ -0,0 +1,219 @@
1+import { beforeEach, describe, expect, it, vi } from "vitest";
2+import { MCPOptions } from "../..";
3+import MCPConnection from "./MCPConnection";
4+import { MCPManagerSingleton } from "./MCPManagerSingleton";
5+
6+// Create test versions with stubbed behavior
7+class TestMCPConnection extends MCPConnection {
8+ constructor(options: MCPOptions) {
9+ super(options);
10+
11+ // Override with test implementations
12+ this.client = {
13+ close: async () => {},
14+ connect: async () => {},
15+ getServerCapabilities: () => ({}),
16+ listResources: async () => ({ resources: [] }),
17+ listTools: async () => ({ tools: [] }),
18+ listPrompts: async () => ({ prompts: [] }),
19+ } as any;
20+
21+ this.abortController = new AbortController();
22+ this.connectClient = vi.fn().mockResolvedValue(undefined);
23+ this.getStatus = vi
24+ .fn()
25+ .mockReturnValue({ status: "connected", errors: [] });
26+ }
27+}
28+
29+describe("MCPManagerSingleton", () => {
30+ let manager: MCPManagerSingleton;
31+ const testOptions: MCPOptions = {
32+ name: "test-mcp",
33+ id: "test-id",
34+ transport: {
35+ type: "stdio",
36+ command: "test-command",
37+ args: [],
38+ },
39+ };
40+
41+ beforeEach(() => {
42+ // Reset singleton
43+ (MCPManagerSingleton as any).instance = undefined;
44+ manager = MCPManagerSingleton.getInstance();
45+
46+ // Replace the connections map with our own that will use TestMCPConnection
47+ const connectionsMap = new Map<string, MCPConnection>();
48+ Object.defineProperty(manager, "connections", {
49+ value: connectionsMap,
50+ writable: true,
51+ });
52+
53+ // Override createConnection to use our TestMCPConnection
54+ manager.createConnection = function (
55+ id: string,
56+ options: MCPOptions,
57+ ): MCPConnection {
58+ if (this.connections.has(id)) {
59+ return this.connections.get(id)!;
60+ }
61+ const connection = new TestMCPConnection(options);
62+ this.connections.set(id, connection);
63+ return connection;
64+ };
65+ });
66+
67+ describe("getInstance", () => {
68+ it("should create singleton instance", () => {
69+ const instance1 = MCPManagerSingleton.getInstance();
70+ const instance2 = MCPManagerSingleton.getInstance();
71+ expect(instance1).toBe(instance2);
72+ });
73+ });
74+
75+ describe("createConnection", () => {
76+ it("should create new connection if none exists", () => {
77+ const connection = manager.createConnection("test-id", testOptions);
78+ expect(connection).toBeInstanceOf(MCPConnection);
79+ });
80+
81+ it("should return existing connection if exists", () => {
82+ const connection1 = manager.createConnection("test-id", testOptions);
83+ const connection2 = manager.createConnection("test-id", testOptions);
84+ expect(connection1).toBe(connection2);
85+ });
86+ });
87+
88+ describe("getConnection", () => {
89+ it("should return undefined for non-existent connection", () => {
90+ expect(manager.getConnection("non-existent")).toBeUndefined();
91+ });
92+
93+ it("should return existing connection", () => {
94+ const connection = manager.createConnection("test-id", testOptions);
95+ expect(manager.getConnection("test-id")).toBe(connection);
96+ });
97+ });
98+
99+ describe("removeConnection", () => {
100+ it("should remove connection and close client", async () => {
101+ // Create a spy on the close method
102+ const connection = manager.createConnection(
103+ "test-id",
104+ testOptions,
105+ ) as TestMCPConnection;
106+ const closeSpy = vi.spyOn(connection.client, "close");
107+
108+ await manager.removeConnection("test-id");
109+
110+ expect(closeSpy).toHaveBeenCalled();
111+ expect(manager.getConnection("test-id")).toBeUndefined();
112+ });
113+
114+ it("should handle non-existent connection", async () => {
115+ await expect(
116+ manager.removeConnection("non-existent"),
117+ ).resolves.toBeUndefined();
118+ });
119+ });
120+
121+ describe("setConnections", () => {
122+ it("should add new connections", () => {
123+ const servers = [testOptions];
124+ manager.setConnections(servers, false);
125+ expect(manager.getConnection(testOptions.id)).toBeInstanceOf(
126+ MCPConnection,
127+ );
128+ });
129+
130+ it("should remove old connections", () => {
131+ // Create initial connection
132+ const connection = manager.createConnection(
133+ "test-id",
134+ testOptions,
135+ ) as TestMCPConnection;
136+ const abortSpy = vi.spyOn(connection.abortController, "abort");
137+ const closeSpy = vi.spyOn(connection.client, "close");
138+
139+ // Remove it by setting empty server list
140+ manager.setConnections([], false);
141+
142+ expect(abortSpy).toHaveBeenCalled();
143+ expect(closeSpy).toHaveBeenCalled();
144+ expect(manager.getConnection("test-id")).toBeUndefined();
145+ });
146+ });
147+
148+ describe("refreshConnection", () => {
149+ it("should refresh specific connection", async () => {
150+ const connection = manager.createConnection(
151+ "test-id",
152+ testOptions,
153+ ) as TestMCPConnection;
154+
155+ await manager.refreshConnection("test-id");
156+
157+ expect(connection.connectClient).toHaveBeenCalledWith(
158+ true,
159+ expect.any(AbortSignal),
160+ );
161+ });
162+
163+ it("should throw error for non-existent connection", async () => {
164+ await expect(manager.refreshConnection("non-existent")).rejects.toThrow(
165+ "MCP Connection non-existent not found",
166+ );
167+ });
168+ });
169+
170+ describe("refreshConnections", () => {
171+ it("should refresh all connections", async () => {
172+ const connection1 = manager.createConnection("test-id-1", {
173+ ...testOptions,
174+ id: "test-id-1",
175+ }) as TestMCPConnection;
176+
177+ const connection2 = manager.createConnection("test-id-2", {
178+ ...testOptions,
179+ id: "test-id-2",
180+ }) as TestMCPConnection;
181+
182+ await manager.refreshConnections(true);
183+
184+ expect(connection1.connectClient).toHaveBeenCalledWith(
185+ true,
186+ expect.any(AbortSignal),
187+ );
188+ expect(connection2.connectClient).toHaveBeenCalledWith(
189+ true,
190+ expect.any(AbortSignal),
191+ );
192+ });
193+
194+ it("should call onConnectionsRefreshed if defined", async () => {
195+ const mockCallback = vi.fn();
196+ manager.onConnectionsRefreshed = mockCallback;
197+ manager.createConnection("test-id", testOptions);
198+
199+ await manager.refreshConnections(true);
200+
201+ expect(mockCallback).toHaveBeenCalled();
202+ });
203+ });
204+
205+ describe("getStatuses", () => {
206+ it("should return statuses for all connections", () => {
207+ const connection = manager.createConnection(
208+ "test-id",
209+ testOptions,
210+ ) as TestMCPConnection;
211+ const mockStatus = { status: "connected", errors: [] };
212+ connection.getStatus = vi.fn().mockReturnValue(mockStatus);
213+
214+ const statuses = manager.getStatuses();
215+ expect(statuses).toHaveLength(1);
216+ expect(statuses[0]).toEqual({ ...mockStatus, client: connection.client });
217+ });
218+ });
219+});
deleted core/context/providers/_context-providers.test.ts +0 −69
@@ -1,69 +0,0 @@
1-import fetch from "node-fetch";
2-
3-import { contextProviderClassFromName } from ".";
4-import {
5- ContextProviderExtras,
6- ContextProviderWithParams,
7- IContextProvider,
8-} from "../..";
9-import { ConfigHandler } from "../../config/ConfigHandler";
10-import { LLMLogger } from "../../llm/logger";
11-import { TEST_DIR } from "../../test/testDir";
12-import FileSystemIde from "../../util/filesystem";
13-
14-const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
15- { name: "diff", params: {} },
16- { name: "currentFile", params: {} },
17- { name: "debugger", params: {} },
18- { name: "open", params: {} },
19- { name: "os", params: {} },
20- { name: "problems", params: {} },
21- { name: "terminal", params: {} },
22- { name: "tree", params: {} },
23-];
24-
25-async function getContextProviderExtras(
26- fullInput: string,
27-): Promise<ContextProviderExtras> {
28- const ide = new FileSystemIde(TEST_DIR);
29- const ideSettingsPromise = ide.getIdeSettings();
30- const llmLogger = new LLMLogger();
31- const configHandler = new ConfigHandler(
32- ide,
33- ideSettingsPromise,
34- llmLogger,
35- Promise.resolve(undefined),
36- );
37- const { config } = await configHandler.loadConfig();
38- if (!config) {
39- throw new Error("Config not found");
40- }
41-
42- return {
43- fullInput,
44- ide,
45- config,
46- embeddingsProvider: config.selectedModelByRole.embed,
47- fetch: fetch,
48- llm: config.modelsByRole.chat[0],
49- reranker: config.selectedModelByRole.rerank,
50- selectedCode: [],
51- };
52-}
53-
54-describe.skip("Should successfully run all context providers", () => {
55- const extrasPromise = getContextProviderExtras("Test");
56-
57- CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {
58- test(`should successfully run ${provider.name} context provider`, async () => {
59- const cls = contextProviderClassFromName(provider.name) as any;
60- const instance: IContextProvider = new cls(provider.params);
61-
62- expect(instance.description.title).toBe(provider.name);
63-
64- const items = await instance.getContextItems("test", await extrasPromise);
65-
66- expect(Array.isArray(items)).toBe(true);
67- });
68- });
69-});
added core/context/providers/_context-providers.vitest.ts +75 −0
@@ -0,0 +1,75 @@
1+import fetch from "node-fetch";
2+
3+import { afterAll, describe, expect, test } from "vitest";
4+import { contextProviderClassFromName } from ".";
5+import {
6+ ContextProviderExtras,
7+ ContextProviderWithParams,
8+ IContextProvider,
9+} from "../..";
10+import { ConfigHandler } from "../../config/ConfigHandler";
11+import { LLMLogger } from "../../llm/logger";
12+import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir";
13+import FileSystemIde from "../../util/filesystem";
14+
15+const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
16+ { name: "diff", params: {} },
17+ { name: "currentFile", params: {} },
18+ { name: "debugger", params: {} },
19+ { name: "open", params: {} },
20+ { name: "os", params: {} },
21+ { name: "problems", params: {} },
22+ { name: "terminal", params: {} },
23+ { name: "tree", params: {} },
24+];
25+
26+async function getContextProviderExtras(
27+ fullInput: string,
28+): Promise<ContextProviderExtras> {
29+ setUpTestDir();
30+ const ide = new FileSystemIde(TEST_DIR);
31+ const ideSettingsPromise = ide.getIdeSettings();
32+ const llmLogger = new LLMLogger();
33+ const configHandler = new ConfigHandler(
34+ ide,
35+ ideSettingsPromise,
36+ llmLogger,
37+ Promise.resolve(undefined),
38+ );
39+ const { config } = await configHandler.loadConfig();
40+ if (!config) {
41+ throw new Error("Config not found");
42+ }
43+
44+ return {
45+ fullInput,
46+ ide,
47+ config,
48+ embeddingsProvider: config.selectedModelByRole.embed,
49+ fetch: fetch,
50+ llm: config.modelsByRole.chat[0],
51+ reranker: config.selectedModelByRole.rerank,
52+ selectedCode: [],
53+ };
54+}
55+
56+describe.skip("Should successfully run all context providers", () => {
57+ afterAll(() => {
58+ tearDownTestDir();
59+ });
60+
61+ const extrasPromise = getContextProviderExtras("Test");
62+
63+ CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {
64+ test(`should successfully run ${provider.name} context provider`, async () => {
65+ const cls = contextProviderClassFromName(provider.name) as any;
66+ const instance: IContextProvider = new cls(provider.params);
67+
68+ expect(instance.description.title).toBe(provider.name);
69+
70+ const items = await instance.getContextItems("test", await extrasPromise);
71+
72+ expect(Array.isArray(items)).toBe(true);
73+ });
74+ });
75+});
modified core/context/providers/index.ts +11 −1
@@ -1,7 +1,9 @@
11 import { BaseContextProvider } from "../";
22 import { ContextProviderName } from "../../";
3+import { Telemetry } from "../../util/posthog";
34
45 import ClipboardContextProvider from "./ClipboardContextProvider";
6+import CodebaseContextProvider from "./CodebaseContextProvider";
57 import CodeContextProvider from "./CodeContextProvider";
68 import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
79 import CurrentFileContextProvider from "./CurrentFileContextProvider";
@@ -56,6 +58,7 @@
5658 JiraIssuesContextProvider,
5759 PostgresContextProvider,
5860 DatabaseContextProvider,
61+ CodebaseContextProvider,
5962 CodeContextProvider,
6063 CurrentFileContextProvider,
6164 URLContextProvider,
@@ -73,5 +76,12 @@
7376 export function contextProviderClassFromName(
7477 name: ContextProviderName,
7578 ): typeof BaseContextProvider | undefined {
76- return Providers.find((cls) => cls.description.title === name);
79+ const provider = Providers.find((cls) => cls.description.title === name);
80+
81+ void Telemetry.capture("context_provider_load", {
82+ providerName: name,
83+ found: !!provider, // also capture those which user expected to be present
84+ });
85+
86+ return provider;
7787 }
modified core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +1 −1
@@ -107,7 +107,7 @@
107107 chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
108108
109109 results.sort(
110- (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
110+ (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
111111 );
112112 results = results.slice(-this.options.nFinal);
113113 return results;
deleted core/context/retrieval/utils.test.ts +0 −117
@@ -1,117 +0,0 @@
1-// Generated by Continue
2-import { Chunk } from "../../index";
3-
4-import { deduplicateChunks } from "./util";
5-
6-describe("deduplicateChunks", () => {
7- it("returns an empty array when given an empty array", () => {
8- const chunks: Chunk[] = [];
9- const result = deduplicateChunks(chunks);
10- expect(result).toEqual([]);
11- });
12-
13- it("returns the same array when given an array with no duplicates", () => {
14- const chunks: Chunk[] = [
15- {
16- filepath: "file1.ts",
17- startLine: 0,
18- endLine: 1,
19- content: "chunk 1",
20- digest: "",
21- index: 0,
22- },
23- {
24- filepath: "file2.ts",
25- startLine: 2,
26- endLine: 3,
27- content: "chunk 2",
28- digest: "",
29- index: 1,
30- },
31- ];
32- const result = deduplicateChunks(chunks);
33- expect(result).toEqual(chunks);
34- });
35-
36- it("removes duplicate chunks", () => {
37- const chunks: Chunk[] = [
38- {
39- filepath: "file1.ts",
40- startLine: 0,
41- endLine: 1,
42- content: "chunk 1",
43- digest: "",
44- index: 0,
45- },
46- {
47- filepath: "file1.ts",
48- startLine: 0,
49- endLine: 1,
50- content: "chunk 1 duplicate",
51- digest: "",
52- index: 0,
53- },
54- {
55- filepath: "file2.ts",
56- startLine: 2,
57- endLine: 3,
58- content: "chunk 2",
59- digest: "",
60- index: 1,
61- },
62- ];
63- const result = deduplicateChunks(chunks);
64-
65- expect(result).toEqual([
66- {
67- filepath: "file1.ts",
68- startLine: 0,
69- endLine: 1,
70- content: "chunk 1",
71- digest: "",
72- index: 0,
73- },
74- {
75- filepath: "file2.ts",
76- startLine: 2,
77- endLine: 3,
78- content: "chunk 2",
79- digest: "",
80- index: 1,
81- },
82- ]);
83- });
84-
85- it("handles chunks with different contents but the same file lines as duplicates", () => {
86- const chunks: Chunk[] = [
87- {
88- filepath: "file1.ts",
89- startLine: 0,
90- endLine: 1,
91- content: "chunk 1",
92- digest: "",
93- index: 0,
94- },
95- {
96- filepath: "file1.ts",
97- startLine: 0,
98- endLine: 1,
99- content: "chunk 1 different content",
100- digest: "",
101- index: 0,
102- },
103- ];
104- const result = deduplicateChunks(chunks);
105-
106- expect(result).toEqual([
107- {
108- filepath: "file1.ts",
109- startLine: 0,
110- endLine: 1,
111- content: "chunk 1",
112- digest: "",
113- index: 0,
114- },
115- ]);
116- });
117-});
added core/context/retrieval/utils.vitest.ts +117 −0
@@ -0,0 +1,117 @@
1+// Generated by Continue
2+import { describe, expect, it } from "vitest";
3+import { Chunk } from "../../index";
4+import { deduplicateChunks } from "./util";
5+
6+describe("deduplicateChunks", () => {
7+ it("returns an empty array when given an empty array", () => {
8+ const chunks: Chunk[] = [];
9+ const result = deduplicateChunks(chunks);
10+ expect(result).toEqual([]);
11+ });
12+
13+ it("returns the same array when given an array with no duplicates", () => {
14+ const chunks: Chunk[] = [
15+ {
16+ filepath: "file1.ts",
17+ startLine: 0,
18+ endLine: 1,
19+ content: "chunk 1",
20+ digest: "",
21+ index: 0,
22+ },
23+ {
24+ filepath: "file2.ts",
25+ startLine: 2,
26+ endLine: 3,
27+ content: "chunk 2",
28+ digest: "",
29+ index: 1,
30+ },
31+ ];
32+ const result = deduplicateChunks(chunks);
33+ expect(result).toEqual(chunks);
34+ });
35+
36+ it("removes duplicate chunks", () => {
37+ const chunks: Chunk[] = [
38+ {
39+ filepath: "file1.ts",
40+ startLine: 0,
41+ endLine: 1,
42+ content: "chunk 1",
43+ digest: "",
44+ index: 0,
45+ },
46+ {
47+ filepath: "file1.ts",
48+ startLine: 0,
49+ endLine: 1,
50+ content: "chunk 1 duplicate",
51+ digest: "",
52+ index: 0,
53+ },
54+ {
55+ filepath: "file2.ts",
56+ startLine: 2,
57+ endLine: 3,
58+ content: "chunk 2",
59+ digest: "",
60+ index: 1,
61+ },
62+ ];
63+ const result = deduplicateChunks(chunks);
64+
65+ expect(result).toEqual([
66+ {
67+ filepath: "file1.ts",
68+ startLine: 0,
69+ endLine: 1,
70+ content: "chunk 1",
71+ digest: "",
72+ index: 0,
73+ },
74+ {
75+ filepath: "file2.ts",
76+ startLine: 2,
77+ endLine: 3,
78+ content: "chunk 2",
79+ digest: "",
80+ index: 1,
81+ },
82+ ]);
83+ });
84+
85+ it("handles chunks with different contents but the same file lines as duplicates", () => {
86+ const chunks: Chunk[] = [
87+ {
88+ filepath: "file1.ts",
89+ startLine: 0,
90+ endLine: 1,
91+ content: "chunk 1",
92+ digest: "",
93+ index: 0,
94+ },
95+ {
96+ filepath: "file1.ts",
97+ startLine: 0,
98+ endLine: 1,
99+ content: "chunk 1 different content",
100+ digest: "",
101+ index: 0,
102+ },
103+ ];
104+ const result = deduplicateChunks(chunks);
105+
106+ expect(result).toEqual([
107+ {
108+ filepath: "file1.ts",
109+ startLine: 0,
110+ endLine: 1,
111+ content: "chunk 1",
112+ digest: "",
113+ index: 0,
114+ },
115+ ]);
116+ });
117+});
modified core/core.ts +57 −4
@@ -10,7 +10,6 @@
1010 import { ConfigHandler } from "./config/ConfigHandler";
1111 import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
1212 import { addModel, deleteModel } from "./config/util";
13-import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
1413 import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
1514 import { ContinueServerClient } from "./continueServer/stubs/client";
1615 import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
@@ -21,6 +20,7 @@
2120 import DocsService from "./indexing/docs/DocsService";
2221 import { countTokens } from "./llm/countTokens";
2322 import Ollama from "./llm/llms/Ollama";
23+import { EditAggregator } from "./nextEdit/context/aggregateEdits";
2424 import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
2525 import { callTool } from "./tools/callTool";
2626 import { ChatDescriber } from "./util/chatDescriber";
@@ -41,6 +41,7 @@
4141 ContextItemWithId,
4242 IdeSettings,
4343 ModelDescription,
44+ Position,
4445 RangeInFile,
4546 ToolCall,
4647 type ContextItem,
@@ -67,6 +68,8 @@
6768 import { LLMLogger } from "./llm/logger";
6869 import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
6970 import { llmStreamChat } from "./llm/streamChat";
71+import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
72+import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
7073 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
7174 import { OnboardingModes } from "./protocol/core";
7275 import type { IMessenger, Message } from "./protocol/messenger";
@@ -716,6 +719,52 @@
716719 }
717720 });
718721
722+ on("files/smallEdit", async ({ data }) => {
723+ const EDIT_AGGREGATION_OPTIONS = {
724+ deltaT: 1.0,
725+ deltaL: 5,
726+ maxEdits: 250,
727+ maxDuration: 100.0,
728+ contextSize: 5,
729+ };
730+
731+ EditAggregator.getInstance(
732+ EDIT_AGGREGATION_OPTIONS,
733+ (
734+ beforeAfterdiff: BeforeAfterDiff,
735+ cursorPosBeforeEdit: Position,
736+ cursorPosAfterPrevEdit: Position,
737+ ) => {
738+ void processSmallEdit(
739+ beforeAfterdiff,
740+ cursorPosBeforeEdit,
741+ cursorPosAfterPrevEdit,
742+ data.configHandler,
743+ data.getDefsFromLspFunction,
744+ this.ide,
745+ );
746+ },
747+ );
748+
749+ const workspaceDir =
750+ data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
751+
752+ // Store the latest context data
753+ const instance = EditAggregator.getInstance();
754+ (instance as any).latestContextData = {
755+ configHandler: data.configHandler,
756+ getDefsFromLspFunction: data.getDefsFromLspFunction,
757+ recentlyEditedRanges: data.recentlyEditedRanges,
758+ recentlyVisitedRanges: data.recentlyVisitedRanges,
759+ workspaceDir: workspaceDir,
760+ };
761+
762+ // queueMicrotask prevents blocking the UI thread during typing
763+ queueMicrotask(() => {
764+ void EditAggregator.getInstance().processEdits(data.actions);
765+ });
766+ });
767+
719768 // Docs, etc. indexing
720769 on("indexing/reindex", async (msg) => {
721770 if (msg.data.type === "docs") {
@@ -823,7 +872,7 @@
823872 this.messenger.send("toolCallPartialOutput", params);
824873 };
825874
826- return await callTool(tool, toolCall, {
875+ const result = await callTool(tool, toolCall, {
827876 config,
828877 ide: this.ide,
829878 llm: config.selectedModelByRole.chat,
@@ -834,6 +883,8 @@
834883 onPartialOutput,
835884 codeBaseIndexer: this.codeBaseIndexer,
836885 });
886+
887+ return result;
837888 }
838889
839890 private async isItemTooBig(item: ContextItemWithId) {
@@ -1045,8 +1096,6 @@
10451096 // user doesn't need these in their config.json for the shortcuts to work
10461097 // option+enter
10471098 new CurrentFileContextProvider({}),
1048- // cmd+enter
1049- new CodebaseContextProvider({}),
10501099 ].find((provider) => provider.description.title === name);
10511100 if (!provider) {
10521101 return [];
@@ -1058,6 +1107,10 @@
10581107 itemId: uuidv4(),
10591108 };
10601109
1110+ void Telemetry.capture("context_provider_get_context_items", {
1111+ name: provider.description.title,
1112+ });
1113+
10611114 const items = await provider.getContextItems(query, {
10621115 config,
10631116 llm,
modified core/index.d.ts +21 −0
@@ -1258,6 +1258,7 @@
12581258 codeWrap?: boolean;
12591259 showSessionTabs?: boolean;
12601260 autoAcceptEditToolDiffs?: boolean;
1261+ logEditingData?: boolean;
12611262 }
12621263
12631264 export interface ContextMenuConfig {
@@ -1338,6 +1339,16 @@
13381339 contents: string;
13391340 }
13401341
1342+export interface RangeInFileWithNextEditInfo {
1343+ filepath: string;
1344+ range: Range;
1345+ fileContents: string;
1346+ editText: string;
1347+ afterCursorPos: Position;
1348+ beforeCursorPos: Position;
1349+ workspaceDir: string;
1350+}
1351+
13411352 export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
13421353
13431354 /**
@@ -1399,6 +1410,16 @@
13991410 * If enabled, will add the current file as context.
14001411 */
14011412 useCurrentFileAsContext?: boolean;
1413+
1414+ /**
1415+ * If enabled, will save data on the user's editing processes
1416+ */
1417+ logEditingData?: boolean;
1418+
1419+ /**
1420+ * If enabled, will enable next edit in place of autocomplete
1421+ */
1422+ optInNextEditFeature?: boolean;
14021423 }
14031424
14041425 export interface AnalyticsConfig {
modified core/llm/llms/Test.ts +10 −1
@@ -2,6 +2,7 @@
22 import { BaseLLM } from "../index.js";
33
44 const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE";
5+const NEXT_EDIT_COMPLETION: string = "<|editable_region_start|>\nHELLO\n";
56
67 class TestLLM extends BaseLLM {
78 static providerName = "test";
@@ -24,7 +25,15 @@
2425 signal: AbortSignal,
2526 options: CompletionOptions,
2627 ): AsyncGenerator<string> {
27- yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
28+ if (
29+ prompt === "NEXT_EDIT" ||
30+ prompt ===
31+ "<|im_start|>user\nNEXT_EDIT<|im_end|>\n<|im_start|>assistant\n"
32+ ) {
33+ yield NEXT_EDIT_COMPLETION;
34+ } else {
35+ yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
36+ }
2837 }
2938
3039 protected async *_streamChat(
modified core/nextEdit/NextEditProvider.ts +281 −95
@@ -1,17 +1,14 @@
11 import { ConfigHandler } from "../config/ConfigHandler.js";
2-import { IDE, ILLM } from "../index.js";
2+import { ChatMessage, IDE, ILLM } from "../index.js";
33 import OpenAI from "../llm/llms/OpenAI.js";
44 import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
55
6-import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js";
76 import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
87
98 import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
109 import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
11-import { postprocessCompletion } from "../autocomplete/postprocessing/index.js";
1210 import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
13-import { getAllSnippets } from "../autocomplete/snippets/index.js";
14-import { renderPrompt } from "../autocomplete/templating/index.js";
11+import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
1512 import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
1613 import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
1714 import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
@@ -21,6 +18,14 @@
2118 AutocompleteInput,
2219 AutocompleteOutcome,
2320 } from "../autocomplete/util/types.js";
21+import { replaceEscapedCharacters } from "../util/text.js";
22+import {
23+ Prompt,
24+ renderDefaultSystemPrompt,
25+ renderDefaultUserPrompt,
26+ renderPrompt,
27+} from "./templating/NextEditPromptEngine.js";
28+// import { renderPrompt } from "./templating/NextEditPromptEngine.js";
2429
2530 const autocompleteCache = AutocompleteLruCache.get();
2631
@@ -33,6 +38,8 @@
3338 ];
3439
3540 export class NextEditProvider {
41+ private static instance: NextEditProvider | null = null;
42+
3643 private autocompleteCache = AutocompleteLruCache.get();
3744 public errorsShown: Set<string> = new Set();
3845 private bracketMatchingService = new BracketMatchingService();
@@ -40,16 +47,54 @@
4047 private completionStreamer: CompletionStreamer;
4148 private loggingService = new AutocompleteLoggingService();
4249 private contextRetrievalService: ContextRetrievalService;
50+ private endpointType: "default" | "fineTuned";
51+ private diffContext: string = "";
4352
44- constructor(
53+ private constructor(
4554 private readonly configHandler: ConfigHandler,
4655 private readonly ide: IDE,
4756 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
4857 private readonly _onError: (e: any) => void,
4958 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
59+ endpointType: "default" | "fineTuned",
5060 ) {
5161 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
5262 this.contextRetrievalService = new ContextRetrievalService(this.ide);
63+ this.endpointType = endpointType;
64+ }
65+
66+ public static initialize(
67+ configHandler: ConfigHandler,
68+ ide: IDE,
69+ injectedGetLlm: () => Promise<ILLM | undefined>,
70+ onError: (e: any) => void,
71+ getDefinitionsFromLsp: GetLspDefinitionsFunction,
72+ endpointType: "default" | "fineTuned",
73+ ): NextEditProvider {
74+ if (!NextEditProvider.instance) {
75+ NextEditProvider.instance = new NextEditProvider(
76+ configHandler,
77+ ide,
78+ injectedGetLlm,
79+ onError,
80+ getDefinitionsFromLsp,
81+ endpointType,
82+ );
83+ }
84+ return NextEditProvider.instance;
85+ }
86+
87+ public static getInstance(): NextEditProvider {
88+ if (!NextEditProvider.instance) {
89+ throw new Error(
90+ "NextEditProvider has not been initialized. Call initialize() first.",
91+ );
92+ }
93+ return NextEditProvider.instance;
94+ }
95+
96+ public addDiffToContext(diff: string): void {
97+ this.diffContext = diff;
5398 }
5499
55100 private async _prepareLlm(): Promise<ILLM | undefined> {
@@ -174,7 +219,7 @@
174219 }
175220
176221 const [snippetPayload, workspaceDirs] = await Promise.all([
177- getAllSnippets({
222+ getAllSnippetsWithoutRace({
178223 helper,
179224 ide: this.ide,
180225 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@@ -183,100 +228,241 @@
183228 this.ide.getWorkspaceDirs(),
184229 ]);
185230
186- const { prompt, prefix, suffix, completionOptions } = renderPrompt({
187- snippetPayload,
188- workspaceDirs,
189- helper,
190- });
191-
192- // Completion
193- let completion: string | undefined = "";
194-
195- const cache = await autocompleteCache;
196- const cachedCompletion = helper.options.useCache
197- ? await cache.get(helper.prunedPrefix)
198- : undefined;
199- let cacheHit = false;
200- if (cachedCompletion) {
201- // Cache
202- cacheHit = true;
203- completion = cachedCompletion;
231+ // TODO: Toggle between the default endpoint and the finetuned endpoint.
232+ const prompts: Prompt[] = [];
233+
234+ if (this.endpointType === "default") {
235+ prompts.push(renderDefaultSystemPrompt());
236+ prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
204237 } else {
205- const multiline =
206- !helper.options.transform || shouldCompleteMultiline(helper);
207-
208- const completionStream =
209- this.completionStreamer.streamCompletionWithFilters(
210- token,
211- llm,
212- prefix,
213- suffix,
214- prompt,
215- multiline,
216- completionOptions,
217- helper,
218- );
219-
220- for await (const update of completionStream) {
221- completion += update;
222- }
238+ prompts.push(
239+ // await renderFineTunedUserPrompt(snippetPayload, this.ide, helper),
240+ // await renderFineTunedBasicUserPrompt(
241+ // snippetPayload,
242+ // this.ide,
243+ // helper,
244+ // this.diffContext,
245+ // ),
246+ renderPrompt(helper, this.diffContext),
247+ );
248+ }
223249
224- // Don't postprocess if aborted
225- if (token.aborted) {
250+ if (this.endpointType === "default") {
251+ const msg: ChatMessage = await llm.chat(prompts, token);
252+ if (typeof msg.content === "string") {
253+ const nextCompletion = JSON.parse(msg.content).newCode;
254+ const outcomeNext: AutocompleteOutcome = {
255+ time: Date.now() - startTime,
256+ completion: nextCompletion,
257+ prefix: "",
258+ suffix: "",
259+ prompt: "",
260+ modelProvider: llm.underlyingProviderName,
261+ modelName: llm.model,
262+ completionOptions: null,
263+ cacheHit: false,
264+ filepath: helper.filepath,
265+ numLines: nextCompletion.split("\n").length,
266+ completionId: helper.input.completionId,
267+ gitRepo: await this.ide.getRepoName(helper.filepath),
268+ uniqueId: await this.ide.getUniqueId(),
269+ timestamp: Date.now(),
270+ ...helper.options,
271+ };
272+ return outcomeNext;
273+ } else {
226274 return undefined;
227275 }
228-
229- const processedCompletion = helper.options.transform
230- ? postprocessCompletion({
231- completion,
232- prefix: helper.prunedPrefix,
233- suffix: helper.prunedSuffix,
234- llm,
235- })
236- : completion;
237-
238- completion = processedCompletion;
239- }
240-
241- if (!completion) {
242- return undefined;
243- }
244-
245- const outcome: AutocompleteOutcome = {
246- time: Date.now() - startTime,
247- completion,
248- prefix,
249- suffix,
250- prompt,
251- modelProvider: llm.underlyingProviderName,
252- modelName: llm.model,
253- completionOptions,
254- cacheHit,
255- filepath: helper.filepath,
256- numLines: completion.split("\n").length,
257- completionId: helper.input.completionId,
258- gitRepo: await this.ide.getRepoName(helper.filepath),
259- uniqueId: await this.ide.getUniqueId(),
260- timestamp: Date.now(),
261- ...helper.options,
262- };
263-
264- //////////
265-
266- // Save to cache
267- if (!outcome.cacheHit && helper.options.useCache) {
268- (await this.autocompleteCache)
269- .put(outcome.prefix, outcome.completion)
270- .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
271- }
272-
273- // When using the JetBrains extension, Mark as displayed
274- const ideType = (await this.ide.getIdeInfo()).ideType;
275- if (ideType === "jetbrains") {
276- this.markDisplayed(input.completionId, outcome);
276+ // const body = {
277+ // model: defaultModel,
278+ // messages: prompts,
279+ // // max_tokens: 15000,
280+ // // stop: ["<|editable_region_end|>"],
281+ // };
282+ //
283+ // const resp = await fetch(defaultEndpoint, {
284+ // method: "POST",
285+ // headers: {
286+ // Authorization: `Bearer ${mercuryToken} `,
287+ // "Content-Type": "application/json",
288+ // },
289+ // body: JSON.stringify(body),
290+ // });
291+ //
292+ // const respJson = await resp.json();
293+
294+ // TODO: Do some zod schema validation here if needed.
295+ } else {
296+ // const testController = new AbortController();
297+ // const msg: ChatMessage = await llm.chat(prompts, testController.signal);
298+ // const testToken = testController.signal;
299+ const msg: ChatMessage = await llm.chat(prompts, token);
300+ if (typeof msg.content === "string") {
301+ // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
302+ const nextCompletion = replaceEscapedCharacters(
303+ msg.content.split("<|editable_region_start|>\n")[1],
304+ ).replace(/\n$/, "");
305+
306+ // const diffLines = myersDiff(helper.fileContents, nextCompletion);
307+
308+ // const diff = getRenderableDiff(diffLines);
309+ const outcomeNext: AutocompleteOutcome = {
310+ time: Date.now() - startTime,
311+ completion: nextCompletion,
312+ prefix: "",
313+ suffix: "",
314+ prompt: "",
315+ modelProvider: llm.underlyingProviderName,
316+ modelName: llm.model,
317+ completionOptions: null,
318+ cacheHit: false,
319+ filepath: helper.filepath,
320+ numLines: nextCompletion.split("\n").length,
321+ completionId: helper.input.completionId,
322+ gitRepo: await this.ide.getRepoName(helper.filepath),
323+ uniqueId: await this.ide.getUniqueId(),
324+ timestamp: Date.now(),
325+ ...helper.options,
326+ };
327+ return outcomeNext;
328+ } else {
329+ return undefined;
330+ }
331+ // const body = {
332+ // model: fineTunedModel,
333+ // messages: prompts,
334+ // max_tokens: 15000,
335+ // stop: ["<|editable_region_end|>"],
336+ // };
337+ //
338+ // const resp = await fetch(fineTunedEndpoint, {
339+ // method: "POST",
340+ // headers: {
341+ // Authorization: `Bearer ${mercuryToken} `,
342+ // "Content-Type": "application/json",
343+ // },
344+ // body: JSON.stringify(body),
345+ // });
346+ //
347+ // const respJson = await resp.json();
348+ //
349+ // const nextCompletion = respJson.choices[0].message.content
350+ // .split("<|editable_region_start|>\n")[1]
351+ // .split("<|editable_region_end|>")[0]
352+ // .slice(1)
353+ // .slice(0, -1)
354+ // .replaceAll("\\n", "\n")
355+ // .replaceAll('\\"', '"');
356+ //
357+ // const outcomeNext: AutocompleteOutcome = {
358+ // time: Date.now() - startTime,
359+ // completion: nextCompletion,
360+ // prefix: "",
361+ // suffix: "",
362+ // prompt: "",
363+ // modelProvider: llm.underlyingProviderName,
364+ // modelName: llm.model,
365+ // completionOptions: null,
366+ // cacheHit: false,
367+ // filepath: helper.filepath,
368+ // numLines: nextCompletion.split("\n").length,
369+ // completionId: helper.input.completionId,
370+ // gitRepo: await this.ide.getRepoName(helper.filepath),
371+ // uniqueId: await this.ide.getUniqueId(),
372+ // timestamp: Date.now(),
373+ // ...helper.options,
374+ // };
375+ // return outcomeNext;
277376 }
278377
279- return outcome;
378+ // // Completion
379+ // let completion: string | undefined = "";
380+
381+ // const cache = await autocompleteCache;
382+ // const cachedCompletion = helper.options.useCache
383+ // ? await cache.get(helper.prunedPrefix)
384+ // : undefined;
385+ // let cacheHit = false;
386+ // if (cachedCompletion) {
387+ // // Cache
388+ // cacheHit = true;
389+ // completion = cachedCompletion;
390+ // } else {
391+ // const multiline =
392+ // !helper.options.transform || shouldCompleteMultiline(helper);
393+
394+ // const completionStream =
395+ // this.completionStreamer.streamCompletionWithFilters(
396+ // token,
397+ // llm,
398+ // prefix,
399+ // suffix,
400+ // prompt,
401+ // multiline,
402+ // completionOptions,
403+ // helper,
404+ // );
405+
406+ // for await (const update of completionStream) {
407+ // completion += update;
408+ // }
409+
410+ // // Don't postprocess if aborted
411+ // if (token.aborted) {
412+ // return undefined;
413+ // }
414+
415+ // const processedCompletion = helper.options.transform
416+ // ? postprocessCompletion({
417+ // completion,
418+ // prefix: helper.prunedPrefix,
419+ // suffix: helper.prunedSuffix,
420+ // llm,
421+ // })
422+ // : completion;
423+
424+ // completion = processedCompletion;
425+ // }
426+
427+ // if (!completion) {
428+ // return undefined;
429+ // }
430+
431+ // const outcome: AutocompleteOutcome = {
432+ // time: Date.now() - startTime,
433+ // completion,
434+ // prefix,
435+ // suffix,
436+ // prompt,
437+ // modelProvider: llm.underlyingProviderName,
438+ // modelName: llm.model,
439+ // completionOptions,
440+ // cacheHit,
441+ // filepath: helper.filepath,
442+ // numLines: completion.split("\n").length,
443+ // completionId: helper.input.completionId,
444+ // gitRepo: await this.ide.getRepoName(helper.filepath),
445+ // uniqueId: await this.ide.getUniqueId(),
446+ // timestamp: Date.now(),
447+ // ...helper.options,
448+ // };
449+
450+ // //////////
451+
452+ // // Save to cache
453+ // if (!outcome.cacheHit && helper.options.useCache) {
454+ // (await this.autocompleteCache)
455+ // .put(outcome.prefix, outcome.completion)
456+ // .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
457+ // }
458+
459+ // // When using the JetBrains extension, Mark as displayed
460+ // const ideType = (await this.ide.getIdeInfo()).ideType;
461+ // if (ideType === "jetbrains") {
462+ // this.markDisplayed(input.completionId, outcome);
463+ // }
464+
465+ // return outcome;
280466 } catch (e: any) {
281467 this.onError(e);
282468 } finally {
added core/nextEdit/README.md +29 −0
@@ -0,0 +1,29 @@
1+# Next Edit Prediction
2+
3+## What is it?
4+
5+## How is it different from autocomplete?
6+
7+## Where are we right now?
8+
9+- Users can decide to switch between autocomplete and next edit.
10+- Next edit triggers at the same time autocomplete is triggered, via vscode's inline completion provider.
11+- The following happens after the trigger:
12+ - User's current cursor position is captured.
13+ - We define an editable range, ±5 lines from the current cursor position.
14+ - User's most recent edit is captured as a unified diff. (this is currently buggy)
15+ - This is sent to the model, which returns a new editable range with next edit predictions.
16+ - We display this new editable range in a SVG decoration.
17+ - User can either tab to accept or esc to reject.
18+ - On accept, the old editable range will be replaced by the new editable region. The cursor will be moved to the last line containing some change.
19+ - On reject, nothing happens.
20+
21+## What needs to be worked on?
22+
23+- User edit captures.
24+- Find a better way to trigger next edit (this links back to the diff capture problem).
25+ - We can see that next edit triggers as soon as the user accepts a change. This is because autocomplete runs the same way.
26+ - I think autocomplete has some filter logic that doesn't display the ghost text under some conditions, which I am guessing are the following:
27+ - The model does not have any more completions to create.
28+ - The prediction at the cursor location has been cached.
29+- JetBrains integration.
modified core/nextEdit/constants.ts +5 −0
@@ -1,1 +1,6 @@
11 export const IS_NEXT_EDIT_ACTIVE = false;
2+export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
3+export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
4+export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
5+export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
6+export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
added core/nextEdit/context/aggregateEdits.ts +575 −0
@@ -0,0 +1,575 @@
1+import { Position, RangeInFileWithNextEditInfo } from "../..";
2+import {
3+ BeforeAfterDiff,
4+ DiffFormatType,
5+ createBeforeAfterDiff,
6+ createDiff,
7+} from "./diffFormatting";
8+
9+interface ClusterState {
10+ beforeState: string; // stores content of cluster before edit
11+ startRange: { minLine: number; maxLine: number };
12+ currentRange: { minLine: number; maxLine: number };
13+ edits: RangeInFileWithNextEditInfo[]; // store small edits that form the cluster
14+ firstTimestamp: number;
15+ lastTimestamp: number;
16+ lastLine: number;
17+ firstEditBeforeCursor: { line: number; character: number }; // cursor position before the first edit in the cluster
18+ lastEditAfterCursor: { line: number; character: number }; // cursor position after the last edit in the previous cluster
19+}
20+
21+interface FileState {
22+ activeClusters: ClusterState[]; // Stores active clusters for the file
23+ currentContent: string; // Stores the current content of the file
24+ priorComparisons: string[]; // Stores prior comparisons for the file (not currently used, but kept for future use)
25+ processingQueue: Array<() => Promise<void>>; // Stores a queue of small edits to be processed into clusters
26+ isProcessing: boolean;
27+}
28+
29+export interface EditClusterConfig {
30+ deltaT: number; // Time threshold in seconds; if exceeded, a new cluster is created
31+ deltaL: number; // Line threshold; if the user jumps more than this many lines, a new cluster is created
32+ maxEdits: number; // Maximum number of edits in a cluster
33+ maxDuration: number; // Maximum total duration of an edit in seconds
34+ contextSize: number; // Number of previous edits to store; not currently used but kept for future use
35+ contextLines: number; // Used for computations involving deltaL
36+}
37+
38+export class EditAggregator {
39+ private fileStates: Map<string, FileState> = new Map();
40+ public config: EditClusterConfig;
41+ private previousEditFinalCursorPosition: Position;
42+ private lastProcessedFilePath: string | null = null;
43+ public onComparisonFinalized: (
44+ diff: BeforeAfterDiff,
45+ beforeCursorPos: Position,
46+ afterPrevEditCursorPos: Position,
47+ ) => void;
48+
49+ private static _instance: EditAggregator | null = null;
50+
51+ public static getInstance(
52+ config?: Partial<EditClusterConfig>,
53+ onComparisonFinalized?: (
54+ diff: BeforeAfterDiff,
55+ beforeCursorPos: Position,
56+ afterPrevEditCursorPos: Position,
57+ ) => void,
58+ ): EditAggregator {
59+ // Create instance if it doesn't exist
60+ if (!EditAggregator._instance) {
61+ EditAggregator._instance = new EditAggregator(
62+ config,
63+ onComparisonFinalized,
64+ );
65+ }
66+ // Update instance if new parameters are provided
67+ else if (config || onComparisonFinalized) {
68+ if (config) {
69+ EditAggregator._instance.config = {
70+ deltaT: config.deltaT ?? EditAggregator._instance.config.deltaT,
71+ deltaL: config.deltaL ?? EditAggregator._instance.config.deltaL,
72+ maxEdits: config.maxEdits ?? EditAggregator._instance.config.maxEdits,
73+ maxDuration:
74+ config.maxDuration ?? EditAggregator._instance.config.maxDuration,
75+ contextSize:
76+ config.contextSize ?? EditAggregator._instance.config.contextSize,
77+ contextLines:
78+ config.contextLines ?? EditAggregator._instance.config.contextLines,
79+ };
80+ }
81+
82+ if (onComparisonFinalized) {
83+ EditAggregator._instance.onComparisonFinalized = onComparisonFinalized;
84+ }
85+ }
86+
87+ return EditAggregator._instance;
88+ }
89+
90+ constructor(
91+ config: Partial<EditClusterConfig> = {},
92+ onComparisonFinalized: (
93+ diff: BeforeAfterDiff,
94+ beforeCursorPos: Position,
95+ afterPrevEditCursorPos: Position,
96+ ) => void = () => {},
97+ ) {
98+ this.config = {
99+ deltaT: config.deltaT ?? 1.0,
100+ deltaL: config.deltaL ?? 5,
101+ maxEdits: config.maxEdits ?? 500,
102+ maxDuration: config.maxDuration ?? 100.0,
103+ contextSize: config.contextSize ?? 5,
104+ contextLines: config.contextLines ?? 3,
105+ };
106+ this.onComparisonFinalized = onComparisonFinalized;
107+ this.previousEditFinalCursorPosition = { line: 0, character: 0 };
108+ }
109+
110+ async processEdit(
111+ edit: RangeInFileWithNextEditInfo,
112+ timestamp: number = Date.now(),
113+ ): Promise<void> {
114+ const filePath = edit.filepath;
115+
116+ // If we're switching to a different file, finalize all clusters from the previous file
117+ if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) {
118+ await this.finalizeClustersForFile(this.lastProcessedFilePath);
119+ }
120+
121+ // Update the last processed file path
122+ this.lastProcessedFilePath = filePath;
123+
124+ if (!this.fileStates.has(filePath)) {
125+ this.fileStates.set(filePath, {
126+ activeClusters: [],
127+ currentContent: edit.fileContents,
128+ priorComparisons: [],
129+ processingQueue: [],
130+ isProcessing: false,
131+ });
132+ }
133+
134+ const fileState = this.fileStates.get(filePath)!;
135+ const task = async () => {
136+ await this._processEditInternal(edit, timestamp, fileState);
137+ };
138+
139+ fileState.processingQueue.push(task);
140+
141+ if (!fileState.isProcessing) {
142+ void this._processQueue(filePath);
143+ }
144+ }
145+
146+ private async _processQueue(filePath: string): Promise<void> {
147+ const fileState = this.fileStates.get(filePath);
148+ if (!fileState) return;
149+
150+ fileState.isProcessing = true;
151+
152+ // Process chunks of (5) edits instead of one at a time
153+ while (fileState.processingQueue.length > 0) {
154+ const tasks = fileState.processingQueue.splice(0, 5);
155+ if (tasks.length > 0) {
156+ try {
157+ await Promise.all(tasks.map((task) => task()));
158+ } catch (error) {
159+ console.error(`Error processing edits in ${filePath}:`, error);
160+ }
161+
162+ // Yield to the event loop to prevent blocking
163+ await new Promise((resolve) => setTimeout(resolve, 0));
164+ }
165+ }
166+
167+ fileState.isProcessing = false;
168+ }
169+
170+ private async _processEditInternal(
171+ edit: RangeInFileWithNextEditInfo,
172+ timestamp: number,
173+ fileState: FileState,
174+ ): Promise<void> {
175+ const filePath = edit.filepath;
176+
177+ const editLine = edit.range.start.line;
178+ const currentFileLines = fileState.currentContent.split("\n");
179+
180+ const clustersToFinalize = this.identifyClustersToFinalize(
181+ fileState,
182+ edit,
183+ timestamp,
184+ false,
185+ );
186+
187+ for (const cluster of clustersToFinalize) {
188+ await this.finalizeCluster(filePath, cluster, fileState);
189+ }
190+
191+ let suitableCluster = this.findSuitableCluster(
192+ fileState,
193+ editLine,
194+ timestamp,
195+ );
196+
197+ // Check if adding this edit would exceed deltaL lines for the cluster
198+ if (suitableCluster) {
199+ const potentialMinLine = Math.min(
200+ suitableCluster.currentRange.minLine,
201+ Math.max(0, editLine - this.config.contextLines),
202+ );
203+ const potentialMaxLine = Math.max(
204+ suitableCluster.currentRange.maxLine,
205+ Math.min(
206+ currentFileLines.length - 1,
207+ editLine + this.config.contextLines,
208+ ),
209+ );
210+ const potentialLineSpan = potentialMaxLine - potentialMinLine + 1;
211+
212+ if (potentialLineSpan > this.config.deltaL * 2) {
213+ // Auto-finalize the current cluster before creating a new one
214+ await this.finalizeCluster(filePath, suitableCluster, fileState);
215+ suitableCluster = null;
216+ }
217+ }
218+
219+ // initialize a cluster
220+ if (!suitableCluster) {
221+ suitableCluster = {
222+ beforeState: fileState.currentContent,
223+ startRange: {
224+ minLine: Math.max(0, editLine - this.config.contextLines),
225+ maxLine: Math.min(
226+ currentFileLines.length - 1,
227+ editLine + this.config.contextLines,
228+ ),
229+ },
230+ currentRange: {
231+ minLine: Math.max(0, editLine - this.config.contextLines),
232+ maxLine: Math.min(
233+ currentFileLines.length - 1,
234+ editLine + this.config.contextLines,
235+ ),
236+ },
237+ edits: [],
238+ firstTimestamp: timestamp,
239+ lastTimestamp: timestamp,
240+ lastLine: editLine,
241+ firstEditBeforeCursor: edit.beforeCursorPos,
242+ lastEditAfterCursor: edit.afterCursorPos,
243+ };
244+ fileState.activeClusters.push(suitableCluster);
245+ }
246+
247+ suitableCluster.edits.push(edit);
248+ suitableCluster.lastTimestamp = timestamp;
249+ suitableCluster.lastLine = editLine;
250+ suitableCluster.lastEditAfterCursor = edit.afterCursorPos;
251+
252+ const isWhitespaceOnly = this.isWhitespaceOnlyEdit(
253+ edit,
254+ fileState.currentContent,
255+ );
256+
257+ if (!isWhitespaceOnly) {
258+ suitableCluster.currentRange.minLine = Math.min(
259+ suitableCluster.currentRange.minLine,
260+ Math.max(0, editLine - this.config.contextLines),
261+ );
262+ suitableCluster.currentRange.maxLine = Math.max(
263+ suitableCluster.currentRange.maxLine,
264+ Math.min(
265+ currentFileLines.length - 1,
266+ editLine + this.config.contextLines,
267+ ),
268+ );
269+ }
270+
271+ fileState.currentContent = edit.fileContents;
272+
273+ const isStructuralEdit =
274+ edit.editText.includes("\n") ||
275+ edit.range.start.line !== edit.range.end.line;
276+
277+ if (isStructuralEdit) {
278+ const additionalClustersToFinalize = fileState.activeClusters.filter(
279+ (c) =>
280+ c !== suitableCluster && this.clustersOverlap(c, suitableCluster),
281+ );
282+
283+ for (const cluster of additionalClustersToFinalize) {
284+ await this.finalizeCluster(filePath, cluster, fileState);
285+ }
286+ }
287+ }
288+
289+ private isWhitespaceOnlyEdit(
290+ edit: RangeInFileWithNextEditInfo,
291+ currentContent: string,
292+ ): boolean {
293+ const lines = currentContent.split("\n");
294+ const line = edit.range.start.line;
295+
296+ if (line >= lines.length) return false;
297+
298+ if (edit.range.start.line === edit.range.end.line) {
299+ const beforeEdit = lines[line];
300+ const afterEdit =
301+ beforeEdit.substring(0, edit.range.start.character) +
302+ edit.editText +
303+ beforeEdit.substring(edit.range.end.character);
304+
305+ return beforeEdit.trim() === afterEdit.trim();
306+ }
307+
308+ return false;
309+ }
310+
311+ private clustersOverlap(
312+ cluster1: ClusterState,
313+ cluster2: ClusterState,
314+ ): boolean {
315+ return (
316+ cluster1.currentRange.minLine <=
317+ cluster2.currentRange.maxLine + this.config.deltaL &&
318+ cluster1.currentRange.maxLine >=
319+ cluster2.currentRange.minLine - this.config.deltaL
320+ );
321+ }
322+
323+ async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise<void> {
324+ const timestamp = Date.now();
325+
326+ // Only process the last edit during rapid typing
327+ if (this.getProcessingQueueSize() > 50) {
328+ if (edits.length > 0) {
329+ await this.processEdit(edits[edits.length - 1], timestamp);
330+ }
331+ return;
332+ }
333+
334+ for (const edit of edits) {
335+ await this.processEdit(edit, timestamp);
336+ }
337+ }
338+
339+ /**
340+ * Finalizes all clusters for a specific file
341+ */
342+ private async finalizeClustersForFile(filePath: string): Promise<void> {
343+ const fileState = this.fileStates.get(filePath);
344+ if (!fileState) return;
345+
346+ // Create a copy of the clusters to finalize to avoid modifying array during iteration
347+ const clustersToFinalize = [...fileState.activeClusters];
348+
349+ for (const cluster of clustersToFinalize) {
350+ await this.finalizeCluster(filePath, cluster, fileState);
351+ }
352+ }
353+
354+ async finalizeAllClusters(): Promise<void> {
355+ const filePromises: Promise<void>[] = [];
356+
357+ this.fileStates.forEach((fileState, filePath) => {
358+ const filePromise = this.finalizeClustersForFile(filePath);
359+ filePromises.push(filePromise);
360+ });
361+
362+ await Promise.all(filePromises);
363+ }
364+
365+ private findSuitableCluster(
366+ fileState: FileState,
367+ editLine: number,
368+ timestamp: number,
369+ ): ClusterState | null {
370+ const activeClusters = [...fileState.activeClusters];
371+
372+ for (const cluster of activeClusters) {
373+ // If we're outside the line range but within the time window,
374+ // we should finalize the current cluster
375+ const isOutsideLineRange =
376+ editLine < cluster.currentRange.minLine - this.config.deltaL ||
377+ editLine > cluster.currentRange.maxLine + this.config.deltaL;
378+
379+ const isWithinTimeWindow =
380+ (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
381+
382+ // If user quickly jumped far away, finalize this cluster before continuing
383+ if (isOutsideLineRange && isWithinTimeWindow) {
384+ void this.finalizeCluster(
385+ cluster.edits[0].filepath,
386+ cluster,
387+ fileState,
388+ );
389+ }
390+ }
391+
392+ // Now look for a suitable cluster for the new edit
393+ for (const cluster of fileState.activeClusters) {
394+ const isOnSameLine = editLine === cluster.lastLine;
395+ const isWithinTimeWindow =
396+ (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
397+ const isWithinLineRange =
398+ editLine >= cluster.currentRange.minLine - this.config.deltaL &&
399+ editLine <= cluster.currentRange.maxLine + this.config.deltaL;
400+ const isWithinEditLimit = cluster.edits.length < this.config.maxEdits;
401+ const isWithinDurationLimit =
402+ (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration;
403+
404+ if (
405+ (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) &&
406+ isWithinEditLimit &&
407+ isWithinDurationLimit
408+ ) {
409+ return cluster;
410+ }
411+ }
412+ return null;
413+ }
414+
415+ private identifyClustersToFinalize(
416+ fileState: FileState,
417+ edit: RangeInFileWithNextEditInfo,
418+ timestamp: number,
419+ isStructuralEdit: boolean,
420+ ): ClusterState[] {
421+ const clustersToFinalize: ClusterState[] = [];
422+ const editLine = edit.range.start.line;
423+
424+ fileState.activeClusters.forEach((cluster) => {
425+ const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000;
426+
427+ const isOnDifferentLineByNumber = cluster.lastLine !== editLine;
428+
429+ const isOnDifferentLineByNewline = edit.editText.includes("\n");
430+
431+ // Use different time thresholds for different types of line change detection
432+ const shouldFinalizeByLineNumber =
433+ isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT;
434+
435+ const shouldFinalizeByNewline =
436+ isOnDifferentLineByNewline &&
437+ timeSinceLastEdit > this.config.deltaT * 1.5;
438+
439+ // Finalize if we moved to a different line AND the time gap exceeds the respective threshold
440+ const shouldFinalizeByTime =
441+ shouldFinalizeByLineNumber || shouldFinalizeByNewline;
442+ const shouldFinalizeByCount =
443+ cluster.edits.length >= this.config.maxEdits;
444+ const shouldFinalizeByDuration =
445+ (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration;
446+
447+ // For structural edits, use the combined line detection
448+ const isOnDifferentLine =
449+ isOnDifferentLineByNumber || isOnDifferentLineByNewline;
450+ const shouldFinalizeByStructuralEdit =
451+ isStructuralEdit && isOnDifferentLine;
452+
453+ if (
454+ shouldFinalizeByTime ||
455+ shouldFinalizeByCount ||
456+ shouldFinalizeByDuration ||
457+ shouldFinalizeByStructuralEdit
458+ ) {
459+ clustersToFinalize.push(cluster);
460+ }
461+ });
462+
463+ return clustersToFinalize;
464+ }
465+
466+ private async finalizeCluster(
467+ filePath: string,
468+ cluster: ClusterState,
469+ fileState: FileState,
470+ ): Promise<void> {
471+ const beforeContent = cluster.beforeState;
472+ const afterContent = fileState.currentContent;
473+
474+ // Skip whitespace-only diffs
475+ const isWhitespaceOnlyDiff =
476+ beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "");
477+
478+ if (isWhitespaceOnlyDiff) {
479+ fileState.activeClusters = fileState.activeClusters.filter(
480+ (c) => c !== cluster,
481+ );
482+ return;
483+ }
484+
485+ const diff = createDiff(
486+ beforeContent,
487+ afterContent,
488+ filePath,
489+ DiffFormatType.Unified,
490+ ); // Used for checks, not for final output
491+
492+ // Skip diffs with too many changed lines
493+ const changedLineCount = this.countChangedLines(diff);
494+ if (changedLineCount > this.config.deltaL * 2) {
495+ fileState.activeClusters = fileState.activeClusters.filter(
496+ (c) => c !== cluster,
497+ );
498+ return;
499+ }
500+
501+ fileState.priorComparisons.push(diff);
502+ if (fileState.priorComparisons.length > this.config.contextSize) {
503+ fileState.priorComparisons.shift();
504+ }
505+
506+ fileState.activeClusters = fileState.activeClusters.filter(
507+ (c) => c !== cluster,
508+ );
509+
510+ // Give format-agnostic diff to the callback
511+ const fullFileVersionsDiff = createBeforeAfterDiff(
512+ beforeContent,
513+ afterContent,
514+ filePath,
515+ );
516+
517+ // Store this cluster's final cursor position for future reference
518+ this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor;
519+
520+ this.onComparisonFinalized(
521+ fullFileVersionsDiff,
522+ cluster.firstEditBeforeCursor,
523+ this.previousEditFinalCursorPosition,
524+ );
525+ }
526+
527+ private countChangedLines(diff: string): number {
528+ let count = 0;
529+ let addedLines = new Set<number>();
530+ let removedLines = new Set<number>();
531+
532+ // Parse the diff lines
533+ const lines = diff.split("\n");
534+ for (const line of lines) {
535+ if (
536+ line.startsWith("+++ ") ||
537+ line.startsWith("--- ") ||
538+ line.startsWith("@@")
539+ ) {
540+ continue; // Skip header lines
541+ }
542+
543+ if (line.startsWith("+")) {
544+ addedLines.add(count);
545+ count++;
546+ } else if (line.startsWith("-")) {
547+ removedLines.add(count);
548+ count++;
549+ }
550+ }
551+
552+ return Math.max(addedLines.size, removedLines.size);
553+ }
554+
555+ getActiveClusterCount(): number {
556+ let count = 0;
557+ this.fileStates.forEach((fileState) => {
558+ count += fileState.activeClusters.length;
559+ });
560+ return count;
561+ }
562+
563+ getProcessingQueueSize(): number {
564+ let count = 0;
565+ this.fileStates.forEach((fileState) => {
566+ count += fileState.processingQueue.length;
567+ });
568+ return count;
569+ }
570+
571+ resetState(): void {
572+ this.fileStates.clear();
573+ this.lastProcessedFilePath = null;
574+ }
575+}
added core/nextEdit/context/autocompleteContextFetching.ts +140 −0
@@ -0,0 +1,140 @@
1+import { Position } from "../..";
2+import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService";
3+import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets";
4+import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
5+import { renderPrompt } from "../../autocomplete/templating";
6+import { GetLspDefinitionsFunction } from "../../autocomplete/types";
7+import { HelperVars } from "../../autocomplete/util/HelperVars";
8+import {
9+ AutocompleteInput,
10+ RecentlyEditedRange,
11+} from "../../autocomplete/util/types";
12+import { ConfigHandler } from "../../config/ConfigHandler";
13+import { IDE, ILLM } from "../../index";
14+import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
15+
16+/**
17+ * Gets the formatted autocomplete context string that would be used for autocomplete at the given position.
18+ * This function mimics the context generation pipeline from the autocomplete system without triggering
19+ * an actual completion.
20+ *
21+ * @param filepath - The file path where context is being requested
22+ * @param pos - The position in the file where context is being requested
23+ * @param ide - The IDE interface for file system operations
24+ * @param configHandler - The config handler to load user configuration
25+ * @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed)
26+ * @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model)
27+ * @param recentlyEditedRanges - Recently edited ranges (defaults to empty array)
28+ * @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete)
29+ * @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config)
30+ * @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state)
31+ * @returns Promise that resolves to the formatted context string
32+ */
33+export const getAutocompleteContext = async (
34+ filepath: string,
35+ pos: Position,
36+ ide: IDE,
37+ configHandler: ConfigHandler,
38+ getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [],
39+ recentlyEditedRanges: RecentlyEditedRange[],
40+ recentlyVisitedRanges: AutocompleteCodeSnippet[],
41+ maxPromptTokens: number,
42+ manuallyPassFileContents: string,
43+ autocompleteModel?: ILLM | string,
44+ // eslint-disable-next-line max-params
45+): Promise<string> => {
46+ if (!recentlyEditedRanges) recentlyEditedRanges = [];
47+ if (!recentlyVisitedRanges) recentlyVisitedRanges = [];
48+
49+ const input: AutocompleteInput = {
50+ isUntitledFile: false,
51+ completionId: `context-fetch-${Date.now()}`,
52+ filepath,
53+ pos,
54+ recentlyVisitedRanges,
55+ recentlyEditedRanges,
56+ manuallyPassFileContents,
57+ };
58+
59+ const { config } = await configHandler.loadConfig();
60+ if (!config) {
61+ throw new Error("No config available");
62+ }
63+
64+ // Use provided autocomplete model or fall back to configured autocomplete model
65+ let finalModel: ILLM;
66+ let modelNameForTemplating: string;
67+
68+ if (autocompleteModel) {
69+ if (typeof autocompleteModel === "string") {
70+ // Try to find the model in config first
71+ const foundModel = config.modelsByRole.autocomplete.find(
72+ (m) => m.title === autocompleteModel,
73+ );
74+ if (foundModel) {
75+ finalModel = foundModel;
76+ modelNameForTemplating = foundModel.model;
77+ } else {
78+ // Model not found in config, but we can still use it for template selection
79+ const configuredModel = config.selectedModelByRole.autocomplete;
80+ if (!configuredModel) {
81+ throw new Error(
82+ "No autocomplete model configured and provided model not found in config",
83+ );
84+ }
85+ finalModel = configuredModel;
86+ modelNameForTemplating = autocompleteModel; // Use the provided string for template selection
87+ }
88+ } else {
89+ finalModel = autocompleteModel;
90+ modelNameForTemplating = autocompleteModel.model;
91+ }
92+ } else {
93+ const configuredModel = config.selectedModelByRole.autocomplete;
94+ if (!configuredModel) {
95+ throw new Error("No autocomplete model configured and no model provided");
96+ }
97+ finalModel = configuredModel;
98+ modelNameForTemplating = configuredModel.model;
99+ }
100+
101+ const options = {
102+ ...DEFAULT_AUTOCOMPLETE_OPTS,
103+ ...config.tabAutocompleteOptions,
104+ ...finalModel.autocompleteOptions,
105+ ...(maxPromptTokens && { maxPromptTokens }),
106+ };
107+
108+ if (finalModel.promptTemplates?.autocomplete) {
109+ options.template = finalModel.promptTemplates.autocomplete as string;
110+ }
111+
112+ const helper = await HelperVars.create(
113+ input,
114+ options,
115+ modelNameForTemplating,
116+ ide,
117+ );
118+
119+ const contextRetrievalService = new ContextRetrievalService(ide);
120+
121+ await contextRetrievalService.initializeForFile(filepath);
122+
123+ const [snippetPayload, workspaceDirs] = await Promise.all([
124+ getAllSnippetsWithoutRace({
125+ helper,
126+ ide: ide,
127+ getDefinitionsFromLsp: getDefinitionsFromLsp,
128+ contextRetrievalService: contextRetrievalService,
129+ }),
130+ ide.getWorkspaceDirs(),
131+ ]);
132+
133+ const { prompt, prefix, suffix, completionOptions } = renderPrompt({
134+ snippetPayload,
135+ workspaceDirs,
136+ helper,
137+ });
138+
139+ return prefix;
140+};
added core/nextEdit/context/diffFormatting.ts +82 −0
@@ -0,0 +1,82 @@
1+import { createPatch } from "diff";
2+
3+export enum DiffFormatType {
4+ Unified = "unified",
5+ RawBeforeAfter = "beforeAfter",
6+ TokenLineDiff = "linediff",
7+}
8+
9+export type BeforeAfterDiff = {
10+ filePath: string;
11+ beforeContent: string;
12+ afterContent: string;
13+};
14+
15+export const createDiff = (
16+ beforeContent: string,
17+ afterContent: string,
18+ filePath: string,
19+ diffType: DiffFormatType,
20+) => {
21+ switch (diffType) {
22+ case DiffFormatType.Unified:
23+ return createUnifiedDiff(beforeContent, afterContent, filePath);
24+ case DiffFormatType.TokenLineDiff:
25+ return createTokenLineDiff(beforeContent, afterContent, filePath);
26+ }
27+ return "";
28+};
29+
30+const createUnifiedDiff = (
31+ beforeContent: string,
32+ afterContent: string,
33+ filePath: string,
34+) => {
35+ const normalizedBefore = beforeContent.endsWith("\n")
36+ ? beforeContent
37+ : beforeContent + "\n";
38+ const normalizedAfter = afterContent.endsWith("\n")
39+ ? afterContent
40+ : afterContent + "\n";
41+
42+ const patch = createPatch(
43+ filePath,
44+ normalizedBefore,
45+ normalizedAfter,
46+ "before",
47+ "after",
48+ { context: 3 },
49+ );
50+
51+ return patch;
52+};
53+
54+export const createBeforeAfterDiff = (
55+ beforeContent: string,
56+ afterContent: string,
57+ filePath: string,
58+) => {
59+ const normalizedBefore = beforeContent.endsWith("\n")
60+ ? beforeContent
61+ : beforeContent + "\n";
62+ const normalizedAfter = afterContent.endsWith("\n")
63+ ? afterContent
64+ : afterContent + "\n";
65+
66+ const result: BeforeAfterDiff = {
67+ filePath: filePath,
68+ beforeContent: normalizedBefore,
69+ afterContent: normalizedAfter,
70+ };
71+
72+ return result;
73+};
74+
75+const createTokenLineDiff = (
76+ beforeContent: string,
77+ afterContent: string,
78+ filePath: string,
79+) => {
80+ // TODO: Implement token line diff
81+ return "";
82+};
added core/nextEdit/context/processNextEditData.ts +83 −0
@@ -0,0 +1,83 @@
1+import { IDE, Position } from "../..";
2+import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
3+import { GetLspDefinitionsFunction } from "../../autocomplete/types";
4+import { ConfigHandler } from "../../config/ConfigHandler";
5+import { DataLogger } from "../../data/log";
6+import { RecentlyEditedRange } from "../types";
7+import { getAutocompleteContext } from "./autocompleteContextFetching";
8+
9+const randomNumberBetween = (min: number, max: number) => {
10+ min = Math.ceil(min); // Ensure min is an integer
11+ max = Math.floor(max); // Ensure max is an integer
12+ return Math.floor(Math.random() * (max - min + 1)) + min;
13+};
14+
15+interface ProcessNextEditDataParams {
16+ filePath: string;
17+ beforeContent: string;
18+ afterContent: string;
19+ cursorPosBeforeEdit: Position;
20+ cursorPosAfterPrevEdit: Position;
21+ ide: IDE;
22+ configHandler: ConfigHandler;
23+ getDefinitionsFromLsp: GetLspDefinitionsFunction;
24+ recentlyEditedRanges: RecentlyEditedRange[];
25+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
26+ workspaceDir: string;
27+ modelNameOrInstance?: string | undefined;
28+}
29+
30+export const processNextEditData = async ({
31+ filePath,
32+ beforeContent,
33+ afterContent,
34+ cursorPosBeforeEdit,
35+ cursorPosAfterPrevEdit,
36+ ide,
37+ configHandler,
38+ getDefinitionsFromLsp,
39+ recentlyEditedRanges,
40+ recentlyVisitedRanges,
41+ workspaceDir,
42+ modelNameOrInstance,
43+}: ProcessNextEditDataParams) => {
44+ // To switch to the user's autocomplete model, uncomment the following lines
45+ // const { config } = await configHandler.loadConfig();
46+ // const autocompleteModel =
47+ // (modelNameOrInstance || config?.selectedModelByRole.autocomplete) ??
48+ // undefined;
49+
50+ const modelName = "Codestral";
51+
52+ const maxPromptTokens = randomNumberBetween(500, 12000);
53+
54+ const autocompleteContext = await getAutocompleteContext(
55+ filePath,
56+ cursorPosBeforeEdit,
57+ ide,
58+ configHandler,
59+ getDefinitionsFromLsp,
60+ recentlyEditedRanges,
61+ recentlyVisitedRanges,
62+ maxPromptTokens,
63+ beforeContent,
64+ modelName,
65+ );
66+
67+ // console.log(
68+ // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
69+ // );
70+
71+ void DataLogger.getInstance().logDevData({
72+ name: "nextEdit",
73+ data: {
74+ fileURI: filePath,
75+ workspaceDirURI: workspaceDir,
76+ beforeContent,
77+ afterContent,
78+ beforeCursorPos: cursorPosBeforeEdit,
79+ afterCursorPos: cursorPosAfterPrevEdit,
80+ context: autocompleteContext,
81+ },
82+ });
83+};
added core/nextEdit/context/processSmallEdit.ts +48 −0
@@ -0,0 +1,48 @@
1+import { IDE, Position } from "../..";
2+import { GetLspDefinitionsFunction } from "../../autocomplete/types";
3+import { ConfigHandler } from "../../config/ConfigHandler";
4+import { NextEditProvider } from "../NextEditProvider";
5+import { EditAggregator } from "./aggregateEdits";
6+import { BeforeAfterDiff, createDiff, DiffFormatType } from "./diffFormatting";
7+import { processNextEditData } from "./processNextEditData";
8+
9+export const processSmallEdit = async (
10+ beforeAfterdiff: BeforeAfterDiff,
11+ cursorPosBeforeEdit: Position,
12+ cursorPosAfterPrevEdit: Position,
13+ configHandler: ConfigHandler,
14+ getDefsFromLspFunction: GetLspDefinitionsFunction,
15+ ide: IDE,
16+) => {
17+ NextEditProvider.getInstance().addDiffToContext(
18+ createDiff(
19+ beforeAfterdiff.beforeContent,
20+ beforeAfterdiff.afterContent,
21+ beforeAfterdiff.filePath,
22+ DiffFormatType.Unified,
23+ ),
24+ );
25+
26+ // Get the current context data from the most recent message
27+ const currentData = (EditAggregator.getInstance() as any)
28+ .latestContextData || {
29+ configHandler: configHandler,
30+ getDefsFromLspFunction: getDefsFromLspFunction,
31+ recentlyEditedRanges: [],
32+ recentlyVisitedRanges: [],
33+ };
34+
35+ void processNextEditData({
36+ filePath: beforeAfterdiff.filePath,
37+ beforeContent: beforeAfterdiff.beforeContent,
38+ afterContent: beforeAfterdiff.afterContent,
39+ cursorPosBeforeEdit: cursorPosBeforeEdit,
40+ cursorPosAfterPrevEdit: cursorPosAfterPrevEdit,
41+ ide: ide,
42+ configHandler: currentData.configHandler,
43+ getDefinitionsFromLsp: currentData.getDefsFromLspFunction,
44+ recentlyEditedRanges: currentData.recentlyEditedRanges,
45+ recentlyVisitedRanges: currentData.recentlyVisitedRanges,
46+ workspaceDir: currentData.workspaceDir,
47+ });
48+};
added core/nextEdit/diff/diff.ts +114 −0
@@ -0,0 +1,114 @@
1+import { DiffLine } from "../..";
2+
3+/**
4+ * Given a diff of two editable regions, get the offset position at the last new line inside the editable region.
5+ * @param diffLines Result of myersDiff.
6+ * @param lineContentAtCursorPos Content of the line at cursor position.
7+ * @param lineOffsetAtCursorPos Offset of the line at cursor position compared to the start of the editable region.
8+ * @returns Offset position at last new line inside the editable region.
9+ */
10+export function getOffsetPositionAtLastNewLine(
11+ diffLines: DiffLine[],
12+ lineContentAtCursorPos: string,
13+ lineOffsetAtCursorPos: number,
14+): {
15+ line: number;
16+ character: number;
17+} {
18+ let lastNewLineContent = "";
19+ let lineOffset = -1;
20+ let currentResultLine = 0;
21+ let hasChanges = false;
22+
23+ // Build the string while tracking line numbers in the result
24+ diffLines.reduce((acc, curr, i) => {
25+ // Add the current line to our result
26+ acc += curr.line;
27+
28+ // Add newline if not the last line
29+ if (i < diffLines.length - 1) {
30+ acc += "\n";
31+ }
32+
33+ // If this is a "new" or "same" line, it will be part of the result
34+ if (curr.type === "new" || curr.type === "same") {
35+ if (curr.type === "new") {
36+ // If it's a new line, update our tracking
37+ lastNewLineContent = curr.line;
38+ lineOffset = currentResultLine;
39+ hasChanges = true;
40+ }
41+ // Increment our position in the result
42+ currentResultLine++;
43+ }
44+
45+ return acc;
46+ }, "");
47+
48+ // If nothing has changed, return the original position
49+ if (!hasChanges) {
50+ lineOffset = lineOffsetAtCursorPos;
51+ lastNewLineContent = lineContentAtCursorPos;
52+ }
53+ // Calculate the character position for the end of the last relevant line
54+ const endOfCharPos = lastNewLineContent.length;
55+ return {
56+ line: lineOffset,
57+ character: endOfCharPos,
58+ };
59+}
60+
61+export function getRenderableDiffWithGutterAnnotations(
62+ diffLines: DiffLine[],
63+ lineContentAtCursorPos: string,
64+ lineOffsetAtCursorPos: number,
65+): {
66+ offset: {
67+ line: number;
68+ character: number;
69+ };
70+} {
71+ let lastNewLineContent = "";
72+ let lineOffset = -1;
73+ let currentResultLine = 0;
74+ let hasChanges = false;
75+
76+ // Build the string while tracking line numbers in the result
77+ diffLines.reduce((acc, curr, i) => {
78+ // Add the current line to our result
79+ acc += curr.line;
80+
81+ // Add newline if not the last line
82+ if (i < diffLines.length - 1) {
83+ acc += "\n";
84+ }
85+
86+ // If this is a "new" or "same" line, it will be part of the result
87+ if (curr.type === "new" || curr.type === "same") {
88+ if (curr.type === "new") {
89+ // If it's a new line, update our tracking
90+ lastNewLineContent = curr.line;
91+ lineOffset = currentResultLine;
92+ hasChanges = true;
93+ }
94+ // Increment our position in the result
95+ currentResultLine++;
96+ }
97+
98+ return acc;
99+ }, "");
100+
101+ // If nothing has changed, return the original position
102+ if (!hasChanges) {
103+ lineOffset = lineOffsetAtCursorPos;
104+ lastNewLineContent = lineContentAtCursorPos;
105+ }
106+ // Calculate the character position for the end of the last relevant line
107+ const endOfCharPos = lastNewLineContent.length;
108+ return {
109+ offset: {
110+ line: lineOffset,
111+ character: endOfCharPos,
112+ },
113+ };
114+}
added core/nextEdit/templating/NextEditPromptEngine.ts +332 −0
@@ -0,0 +1,332 @@
1+import Handlebars from "handlebars";
2+import { Position } from "../..";
3+import { SnippetPayload } from "../../autocomplete/snippets";
4+import { HelperVars } from "../../autocomplete/util/HelperVars";
5+import {
6+ EDITABLE_REGION_END_TOKEN,
7+ EDITABLE_REGION_START_TOKEN,
8+ NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
9+ NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
10+ USER_CURSOR_IS_HERE_TOKEN,
11+} from "../constants";
12+
13+export type Prompt = SystemPrompt | UserPrompt;
14+
15+interface SystemPrompt {
16+ role: "system";
17+ content: string;
18+}
19+
20+interface UserPrompt {
21+ role: "user";
22+ content: string;
23+}
24+
25+export interface NextEditTemplate {
26+ template: string;
27+}
28+
29+export interface TemplateVars {
30+ userEdits: string;
31+ languageShorthand: string;
32+ userExcerpts: string;
33+}
34+
35+type TemplateRenderer = (vars: TemplateVars) => string;
36+
37+type NextEditModelName = "mercury-coder-nextedit" | "this field is not used";
38+
39+const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
40+ "mercury-coder-nextedit": {
41+ template:
42+ "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{userExcerpts}}}\`\`\`",
43+ },
44+ "this field is not used": {
45+ template: "NEXT_EDIT",
46+ },
47+};
48+
49+function templateRendererOfModel(
50+ modelName: NextEditModelName,
51+): TemplateRenderer {
52+ const template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
53+ if (!template) {
54+ throw new Error(`Model ${modelName} is not supported for next edit.`);
55+ }
56+
57+ const compiledTemplate = Handlebars.compile(template.template);
58+
59+ return (vars: TemplateVars): string => {
60+ return compiledTemplate(vars);
61+ };
62+}
63+
64+export function renderPrompt(
65+ helper: HelperVars,
66+ userEdits: string,
67+): UserPrompt {
68+ const modelName = helper.modelName as NextEditModelName;
69+
70+ if (modelName === "this field is not used") {
71+ return {
72+ role: "user",
73+ content: "NEXT_EDIT",
74+ };
75+ }
76+
77+ // Validate that the modelName is actually a supported model.
78+ if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
79+ throw new Error(`${helper.modelName} is not yet supported for next edit.`);
80+ }
81+
82+ const renderer = templateRendererOfModel(modelName);
83+ const editedCodeWithTokens = insertTokens(
84+ helper.fileContents.split("\n"),
85+ helper.pos,
86+ );
87+
88+ const tv: TemplateVars = {
89+ userEdits,
90+ languageShorthand: helper.lang.name,
91+ userExcerpts: editedCodeWithTokens,
92+ };
93+
94+ return {
95+ role: "user",
96+ content: renderer(tv),
97+ };
98+}
99+
100+export function renderDefaultSystemPrompt(): SystemPrompt {
101+ return {
102+ role: "system",
103+ content: [
104+ /* Identity forming */
105+ "You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
106+ "You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
107+ "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.",
108+ /* Action crash course */
109+ "An action is a change in code state that preserves the well-formedness of the code.",
110+ "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.",
111+ /* Input description */
112+ // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
113+ // "language is the language the code is written in.",
114+ // "originalCode is the code state before the junior has taken some edit action.",
115+ // "editedCode is the code state after the junior has taken some edit action.",
116+ // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
117+ // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.",
118+ 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.',
119+ "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
120+ "recentlyEditedRange is the code that the junior has recently edited.",
121+ "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
122+ "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.",
123+ "The junior might want to add new code, delete existing code, or replace different parts of code.",
124+ "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
125+ /* Output description */
126+ 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
127+ /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
128+ /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
129+ "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.",
130+ // "actionType is the type of action the junior has taken.",
131+ "newCode is what the full code looks like after applying your nextEditContent.",
132+ // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
133+ "Given the above definition of an action, you should prioritize fixing the following:",
134+ "- Patterns and repetition in code.",
135+ "- Static errors that the compiler of the language may return.",
136+ "- The junior's code style.",
137+ "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
138+ "If the junior has added some code, there's a good chance that the next edit will also be additions.",
139+ "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.",
140+ "Careful of language intricacies.",
141+ // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
142+ "Do not reply in markdown.",
143+ "Do not hallucinate.",
144+ ].join(" "),
145+ };
146+}
147+
148+export function renderDefaultUserPrompt(
149+ // originalCode: string,
150+ // editedCode: string,
151+ snippets: SnippetPayload,
152+ helper: HelperVars,
153+): UserPrompt {
154+ const userEdit = {
155+ language: helper.lang,
156+ rootPathSnippets: snippets.rootPathSnippets,
157+ importDefinitionSnippets: snippets.importDefinitionSnippets,
158+ ideSnippets: snippets.ideSnippets,
159+ recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
160+ diffSnippets: snippets.diffSnippets,
161+ clipboardSnippets: snippets.clipboardSnippets,
162+ recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
163+ };
164+
165+ return {
166+ role: "user",
167+ content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`,
168+ };
169+}
170+
171+// export async function renderFineTunedUserPrompt(
172+// snippets: SnippetPayload,
173+// ide: IDE,
174+// helper: HelperVars,
175+// ): Promise<UserPrompt> {
176+// const ideInfo = await ide.getIdeInfo();
177+// switch (ideInfo.ideType) {
178+// case "vscode":
179+// const editedCodeWithPins = insertTokens(
180+// helper.fileContents.split("\n"),
181+// helper.pos,
182+// );
183+
184+// return {
185+// role: "user",
186+// content: renderStringTemplate(
187+// mercuryCoderTemplate,
188+// snippets.diffSnippets.join("\n"),
189+// helper.lang.name,
190+// editedCodeWithPins,
191+// ),
192+// };
193+
194+// case "jetbrains":
195+// return {
196+// role: "user",
197+// content: "",
198+// };
199+// }
200+// }
201+
202+// export async function renderDefaultBasicUserPrompt(
203+// snippets: SnippetPayload,
204+// ide: IDE,
205+// helper: HelperVars,
206+// ): Promise<UserPrompt> {
207+// const ideInfo = await ide.getIdeInfo();
208+// switch (ideInfo.ideType) {
209+// case "vscode":
210+// const editedCodeWithPins = insertTokens(
211+// helper.fileContents.split("\n"),
212+// helper.pos,
213+// );
214+
215+// return {
216+// role: "user",
217+// content: renderStringTemplate(
218+// mercuryCoderTemplate,
219+// JSON.stringify(snippets),
220+// helper.lang.name,
221+// editedCodeWithPins,
222+// ),
223+// };
224+
225+// case "jetbrains":
226+// return {
227+// role: "user",
228+// content: "",
229+// };
230+// }
231+// }
232+
233+// export async function renderFineTunedBasicUserPrompt(
234+// snippets: SnippetPayload,
235+// ide: IDE,
236+// helper: HelperVars,
237+// diffContext: string,
238+// ): Promise<UserPrompt> {
239+// const ideInfo = await ide.getIdeInfo();
240+// switch (ideInfo.ideType) {
241+// case "vscode":
242+// const lines = helper.fileContents.split("\n");
243+// const editedCodeWithPins = insertTokens(lines, helper.pos);
244+
245+// return {
246+// role: "user",
247+// content: renderStringTemplate(
248+// mercuryCoderTemplate,
249+// diffContext,
250+// helper.lang.name,
251+// editedCodeWithPins,
252+// ),
253+// };
254+
255+// case "jetbrains":
256+// return {
257+// role: "user",
258+// content: "",
259+// };
260+// }
261+// }
262+
263+function insertTokens(lines: string[], cursorPos: Position) {
264+ const a = insertCursorToken(lines, cursorPos);
265+ const b = insertEditableRegionTokensWithStaticRange(a, cursorPos);
266+ return b.join("\n");
267+}
268+
269+function insertCursorToken(lines: string[], cursorPos: Position) {
270+ if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
271+ return lines;
272+ }
273+
274+ // Ensure character position is within bounds or at the end of the line.
275+ const lineLength = lines[cursorPos.line].length;
276+ const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
277+
278+ lines[cursorPos.line] =
279+ lines[cursorPos.line].slice(0, charPos) +
280+ USER_CURSOR_IS_HERE_TOKEN +
281+ lines[cursorPos.line].slice(charPos);
282+
283+ return lines;
284+}
285+
286+function insertEditableRegionTokensWithStaticRange(
287+ lines: string[],
288+ cursorPos: Position,
289+) {
290+ if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
291+ return lines;
292+ }
293+
294+ // Ensure editable regions are within bounds.
295+ const editableRegionStart = Math.max(
296+ cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
297+ 0,
298+ );
299+ const editableRegionEnd = Math.min(
300+ cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
301+ lines.length - 1, // Line numbers should be zero-indexed.
302+ );
303+
304+ const instrumentedLines = [
305+ ...lines.slice(0, editableRegionStart),
306+ EDITABLE_REGION_START_TOKEN,
307+ ...lines.slice(editableRegionStart, editableRegionEnd + 1),
308+ EDITABLE_REGION_END_TOKEN,
309+ ...lines.slice(editableRegionEnd + 1),
310+ ];
311+
312+ return instrumentedLines;
313+}
314+
315+function insertEditableRegionTokensWithAst(
316+ lines: string[],
317+ cursorPos: Position,
318+) {
319+ if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
320+ return lines;
321+ }
322+
323+ // Ensure character position is within bounds or at the end of the line.
324+ const lineLength = lines[cursorPos.line].length;
325+ const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
326+
327+ (lines[cursorPos.line] =
328+ lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN),
329+ lines[cursorPos.line].slice(charPos);
330+
331+ return lines;
332+}
added core/nextEdit/types.ts +45 −0
@@ -0,0 +1,45 @@
1+import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../";
2+import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
3+
4+export type RecentlyEditedRange = RangeInFile & {
5+ timestamp: number;
6+ lines: string[];
7+ symbols: Set<string>;
8+};
9+
10+export interface AutocompleteInput {
11+ isUntitledFile: boolean;
12+ completionId: string;
13+ filepath: string;
14+ pos: Position;
15+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
16+ recentlyEditedRanges: RecentlyEditedRange[];
17+ // Used for notebook files
18+ manuallyPassFileContents?: string;
19+ // Used for VS Code git commit input box
20+ manuallyPassPrefix?: string;
21+ selectedCompletionInfo?: {
22+ text: string;
23+ range: Range;
24+ };
25+ injectDetails?: string;
26+}
27+
28+export interface NextEditOutcome extends TabAutocompleteOptions {
29+ accepted?: boolean;
30+ time: number;
31+ prefix: string;
32+ suffix: string;
33+ prompt: string;
34+ completion: string;
35+ modelProvider: string;
36+ modelName: string;
37+ completionOptions: any;
38+ cacheHit: boolean;
39+ numLines: number;
40+ filepath: string;
41+ gitRepo?: string;
42+ completionId: string;
43+ uniqueId: string;
44+ timestamp: number;
45+}
modified core/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 core/package.json +1 −0
@@ -41,6 +41,7 @@
4141 "myers-diff": "^2.1.0",
4242 "onnxruntime-common": "1.14.0",
4343 "onnxruntime-web": "1.14.0",
44+ "shiki": "^3.6.0",
4445 "ts-jest": "^29.1.1",
4546 "typescript": "^5.6.3",
4647 "vitest": "^3.1.4"
modified core/protocol/core.ts +18 −1
@@ -5,7 +5,10 @@
55 ModelRole,
66 } from "@continuedev/config-yaml";
77
8-import { AutocompleteInput } from "../autocomplete/util/types";
8+import {
9+ AutocompleteInput,
10+ RecentlyEditedRange,
11+} from "../autocomplete/util/types";
912 import { SharedConfigSchema } from "../config/sharedConfig";
1013 import { GlobalContextModelSelections } from "../util/GlobalContext";
1114
@@ -25,6 +28,7 @@
2528 ModelDescription,
2629 PromptLog,
2730 RangeInFile,
31+ RangeInFileWithNextEditInfo,
2832 SerializedContinueConfig,
2933 Session,
3034 SessionMetadata,
@@ -33,6 +37,9 @@
3337 StreamDiffLinesPayload,
3438 ToolCall,
3539 } from "../";
40+import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
41+import { GetLspDefinitionsFunction } from "../autocomplete/types";
42+import { ConfigHandler } from "../config/ConfigHandler";
3643 import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
3744 import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
3845 import { FreeTrialStatus } from "../control-plane/client";
@@ -193,6 +200,16 @@
193200 "files/created": [{ uris?: string[] }, void];
194201 "files/deleted": [{ uris?: string[] }, void];
195202 "files/closed": [{ uris?: string[] }, void];
203+ "files/smallEdit": [
204+ {
205+ actions: RangeInFileWithNextEditInfo[];
206+ configHandler: ConfigHandler;
207+ getDefsFromLspFunction: GetLspDefinitionsFunction;
208+ recentlyEditedRanges: RecentlyEditedRange[];
209+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
210+ },
211+ void,
212+ ];
196213
197214 // Docs etc. Indexing. TODO move codebase to this
198215 "indexing/reindex": [{ type: string; id: string }, void];
modified core/tools/builtIn.ts +1 −0
@@ -13,6 +13,7 @@
1313 CreateRuleBlock = "builtin_create_rule_block",
1414 RequestRule = "builtin_request_rule",
1515 FetchUrlContent = "builtin_fetch_url_content",
16+ CodebaseTool = "builtin_codebase",
1617
1718 // excluded from allTools for now
1819 ViewRepoMap = "builtin_view_repo_map",
modified core/tools/callTool.ts +26 −0
@@ -1,8 +1,10 @@
11 import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
22 import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
3+import { DataLogger } from "../data/log";
34 import { canParseUrl } from "../util/url";
45 import { BuiltInToolNames } from "./builtIn";
56
7+import { codebaseToolImpl } from "./implementations/codebaseTool";
68 import { createNewFileImpl } from "./implementations/createNewFile";
79 import { createRuleBlockImpl } from "./implementations/createRuleBlock";
810 import { fetchUrlContentImpl } from "./implementations/fetchUrlContent";
@@ -164,11 +166,33 @@
164166 return await createRuleBlockImpl(args, extras);
165167 case BuiltInToolNames.RequestRule:
166168 return await requestRuleImpl(args, extras);
169+ case BuiltInToolNames.CodebaseTool:
170+ return await codebaseToolImpl(args, extras);
167171 default:
168172 throw new Error(`Tool "${functionName}" not found`);
169173 }
170174 }
171175
176+function logToolUsage(
177+ toolCall: ToolCall,
178+ args: Record<string, any>,
179+ contextItems: ContextItem[],
180+ success: boolean,
181+) {
182+ void DataLogger.getInstance().logDevData({
183+ name: "toolUsage",
184+ data: {
185+ toolCallId: toolCall.id,
186+ functionName: toolCall.function.name,
187+ functionArgs: toolCall.function.arguments,
188+ toolCallArgs: args,
189+ parsedArgs: args,
190+ output: contextItems,
191+ succeeded: success,
192+ },
193+ });
194+}
195+
172196 // Handles calls for core/non-client tools
173197 // Returns an error context item if the tool call fails
174198 // Note: Edit tool is handled on client
@@ -190,6 +214,7 @@
190214 item.icon = tool.faviconUrl;
191215 });
192216 }
217+ logToolUsage(toolCall, args, contextItems, true);
193218 return {
194219 contextItems,
195220 errorMessage: undefined,
@@ -199,6 +224,7 @@
199224 if (e instanceof Error) {
200225 errorMessage = e.message;
201226 }
227+ logToolUsage(toolCall, {}, [], false);
202228 return {
203229 contextItems: [],
204230 errorMessage,
added core/tools/definitions/codebaseTool.ts +29 −0
@@ -0,0 +1,29 @@
1+import { Tool } from "../..";
2+import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
3+
4+export const codebaseTool: Tool = {
5+ type: "function",
6+ displayTitle: "Codebase Search",
7+ wouldLikeTo: "search the codebase for: {{{ query }}}",
8+ isCurrently: "searching the codebase for: {{{ query }}}",
9+ hasAlready: "searched the codebase for: {{{ query }}}",
10+ readonly: true,
11+ isInstant: false,
12+ group: BUILT_IN_GROUP_NAME,
13+ function: {
14+ name: BuiltInToolNames.CodebaseTool,
15+ description:
16+ "Use this tool to semantically search through the codebase and retrieve relevant code snippets based on a natural language query. This helps find relevant code context for understanding or working with the codebase.",
17+ parameters: {
18+ type: "object",
19+ required: ["query"],
20+ properties: {
21+ query: {
22+ type: "string",
23+ description:
24+ "Natural language description of what you're looking for in the codebase (e.g., 'authentication logic', 'database connection setup', 'error handling')",
25+ },
26+ },
27+ },
28+ },
29+};
added core/tools/implementations/codebaseTool.ts +61 −0
@@ -0,0 +1,61 @@
1+import { ToolImpl } from ".";
2+import { RangeInFile } from "../..";
3+import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
4+
5+export const codebaseToolImpl: ToolImpl = async (args, extras) => {
6+ if (!args.query || args.query.trim() === "") {
7+ return [
8+ {
9+ name: "Error",
10+ description: "Codebase search error",
11+ content: "Query parameter is required and cannot be empty.",
12+ },
13+ ];
14+ }
15+
16+ try {
17+ const contextExtras = {
18+ config: extras.config,
19+ fullInput: args.query,
20+ embeddingsProvider: extras.config.selectedModelByRole.embed,
21+ reranker: extras.config.selectedModelByRole.rerank,
22+ llm: extras.llm,
23+ ide: extras.ide,
24+ selectedCode: [] as RangeInFile[],
25+ fetch: extras.fetch,
26+ };
27+
28+ // Use the existing retrieval function to get context items
29+ const results = await retrieveContextItemsFromEmbeddings(
30+ contextExtras,
31+ undefined,
32+ undefined,
33+ );
34+
35+ // If no results found, return helpful message
36+ if (results.length === 0) {
37+ return [
38+ {
39+ name: "No Results",
40+ description: "Codebase search",
41+ content: `No relevant code found for query: "${args.query}". This could mean:
42+- The codebase hasn't been indexed yet
43+- No code matches the search criteria
44+- Embeddings provider is not configured
45+
46+Try re-indexing the codebase or using a more specific query.`,
47+ },
48+ ];
49+ }
50+
51+ return results;
52+ } catch (error) {
53+ return [
54+ {
55+ name: "Error",
56+ description: "Codebase search error",
57+ content: `Failed to search codebase: ${error instanceof Error ? error.message : String(error)}`,
58+ },
59+ ];
60+ }
61+};
modified core/tools/index.ts +7 −1
@@ -1,4 +1,5 @@
11 import { ConfigDependentToolParams, IDE, Tool } from "..";
2+import { codebaseTool } from "./definitions/codebaseTool";
23 import { createNewFileTool } from "./definitions/createNewFile";
34 import { createRuleBlock } from "./definitions/createRuleBlock";
45 import { editFileTool } from "./definitions/editFile";
@@ -37,7 +38,12 @@
3738 ): Tool[] => [
3839 requestRuleTool(params),
3940 ...(params.enableExperimentalTools
40- ? [searchAndReplaceInFileTool, viewRepoMapTool, viewSubdirectoryTool]
41+ ? [
42+ searchAndReplaceInFileTool,
43+ viewRepoMapTool,
44+ viewSubdirectoryTool,
45+ codebaseTool,
46+ ]
4147 : [editFileTool]),
4248 ];
4349
modified core/util/text.ts +37 −0
@@ -4,3 +4,40 @@
44 }
55 return val[0].toUpperCase() + val.slice(1);
66 };
7+
8+export function replaceEscapedCharacters(str: string): string {
9+ return str.replaceAll(/\\(n|t|r|\\|"|')/g, (match, p1) => {
10+ switch (p1) {
11+ case "n":
12+ return "\n";
13+ case "t":
14+ return "\t";
15+ case "r":
16+ return "\r";
17+ case "\\":
18+ return "\\";
19+ case '"':
20+ return '"';
21+ case "'":
22+ return "'";
23+ default:
24+ return match; // NOTE: Handle unexpected escapes better than this.
25+ }
26+ });
27+}
28+
29+export function escapeForSVG(text: string): string {
30+ return text
31+ .replace(/&/g, "&amp;") // must be first
32+ .replace(/</g, "&lt;")
33+ .replace(/>/g, "&gt;")
34+ .replace(/"/g, "&quot;")
35+ .replace(/'/g, "&apos;");
36+}
37+
38+export function kebabOfStr(str: string): string {
39+ return str
40+ .replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase
41+ .replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens
42+ .toLowerCase();
43+}
modified docs/docs/advanced/model-providers/top-level/bedrock.mdx +8 −0
@@ -1,3 +1,11 @@
1+---
2+title: Amazon Bedrock
3+slug: ../bedrock
4+---
5+
6+import TabItem from "@theme/TabItem";
7+import Tabs from "@theme/Tabs";
8+
19 Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API.
210
311 ## Chat model
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +2 −2
@@ -5,7 +5,7 @@
55 import com.intellij.openapi.actionSystem.ActionPromoter
66 import com.intellij.openapi.actionSystem.AnAction
77 import com.intellij.openapi.actionSystem.DataContext
8-import com.intellij.openapi.components.ServiceManager
8+import com.intellij.openapi.components.service
99 import org.jetbrains.annotations.NotNull
1010
1111 class ContinueActionPromote : ActionPromoter {
@@ -13,7 +13,7 @@
1313 override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
1414 // For autocomplete actions
1515 if (actions.any { it is AcceptAutocompleteAction }) {
16- val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
16+ val settings = service<ContinueExtensionSettings>()
1717 if (settings.continueState.showIDECompletionSideBySide) {
1818 return actions.filterIsInstance<AcceptAutocompleteAction>()
1919 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +3 −10
@@ -1,7 +1,7 @@
11 package com.github.continuedev.continueintellijextension.actions
22
33 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
4-import com.intellij.openapi.components.ServiceManager
4+import com.intellij.openapi.components.service
55 import com.intellij.openapi.project.Project
66 import com.intellij.openapi.wm.ToolWindowManager
77
@@ -28,12 +28,5 @@
2828 continuePluginService.ideProtocolClient?.sendHighlightedCode()
2929 }
3030
31-fun getPluginService(project: Project?): ContinuePluginService? {
32- if (project == null) {
33- return null
34- }
35- return ServiceManager.getService(
36- project,
37- ContinuePluginService::class.java
38- )
39-}
No newline at the end of the file
31+fun getPluginService(project: Project?): ContinuePluginService? =
32+ project?.service<ContinuePluginService>()
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt +0 −13
@@ -1,9 +1,7 @@
11 package com.github.continuedev.continueintellijextension.activities
22
33 import com.intellij.openapi.Disposable
4-import com.intellij.openapi.application.ApplicationManager
54 import com.intellij.openapi.components.Service
6-import com.intellij.openapi.project.Project
75
86 /**
97 * The service is a parent disposable that represents the entire plugin lifecycle
@@ -18,15 +16,4 @@
1816 override fun dispose() {
1917 }
2018
21- companion object {
22-
23- fun getInstance(): ContinuePluginDisposable {
24- return ApplicationManager.getApplication().getService(ContinuePluginDisposable::class.java)
25- }
26-
27- fun getInstance(project: Project): ContinuePluginDisposable {
28- return project.getService(ContinuePluginDisposable::class.java)
29- }
30-
31- }
3219 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +3 −8
@@ -14,7 +14,6 @@
1414 import com.intellij.openapi.actionSystem.KeyboardShortcut
1515 import com.intellij.openapi.application.ApplicationManager
1616 import com.intellij.openapi.application.ApplicationNamesInfo
17-import com.intellij.openapi.components.ServiceManager
1817 import com.intellij.openapi.editor.EditorFactory
1918 import com.intellij.openapi.fileEditor.FileEditorManager
2019 import com.intellij.openapi.keymap.KeymapManager
@@ -122,14 +121,10 @@
122121
123122 private fun initializePlugin(project: Project) {
124123 val coroutineScope = CoroutineScope(Dispatchers.IO)
125- val continuePluginService = ServiceManager.getService(
126- project,
127- ContinuePluginService::class.java
128- )
124+ val continuePluginService = project.service<ContinuePluginService>()
129125
130126 coroutineScope.launch {
131- val settings =
132- ServiceManager.getService(ContinueExtensionSettings::class.java)
127+ val settings = service<ContinueExtensionSettings>()
133128 if (!settings.continueState.shownWelcomeDialog) {
134129 settings.continueState.shownWelcomeDialog = true
135130 // Open tutorial file
@@ -270,7 +265,7 @@
270265
271266 EditorFactory.getInstance().eventMulticaster.addSelectionListener(
272267 listener,
273- ContinuePluginDisposable.getInstance(project)
268+ project.service<ContinuePluginDisposable>()
274269 )
275270
276271 val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope)
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +6 −7
@@ -7,7 +7,6 @@
77 import com.intellij.injected.editor.VirtualFileWindow
88 import com.intellij.openapi.application.*
99 import com.intellij.openapi.components.Service
10-import com.intellij.openapi.components.ServiceManager
1110 import com.intellij.openapi.components.service
1211 import com.intellij.openapi.editor.Editor
1312 import com.intellij.openapi.editor.InlayProperties
@@ -64,8 +63,7 @@
6463 var lastChangeWasPartialAccept = false
6564
6665 fun triggerCompletion(editor: Editor) {
67- val settings =
68- ServiceManager.getService(ContinueExtensionSettings::class.java)
66+ val settings = service<ContinueExtensionSettings>()
6967 if (!settings.continueState.enableTabAutocomplete) {
7068 return
7169 }
@@ -183,7 +181,7 @@
183181 }
184182 if (isInjectedFile(editor)) return
185183 // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
186- if (shouldSkipRender(ServiceManager.getService(ContinueExtensionSettings::class.java))) {
184+ if (shouldSkipRender()) {
187185 return
188186 }
189187
@@ -230,9 +228,10 @@
230228 }
231229 }
232230
233- private fun shouldSkipRender(settings: ContinueExtensionSettings) =
234- !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
235-
231+ private fun shouldSkipRender(): Boolean {
232+ val settings = service<ContinueExtensionSettings>()
233+ return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
234+ }
236235
237236 private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
238237 val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +1 −1
@@ -26,7 +26,7 @@
2626 private val animatedIcon = AnimatedIcon.Default()
2727
2828 init {
29- Disposer.register(ContinuePluginDisposable.getInstance(project), this)
29+ Disposer.register(project.service<ContinuePluginDisposable>(), this)
3030 updateIcon()
3131 }
3232
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +2 −1
@@ -10,6 +10,7 @@
1010 import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
1111 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
1212 import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
13+import com.intellij.openapi.components.service
1314 import com.intellij.openapi.editor.Editor
1415 import com.intellij.openapi.project.Project
1516 import kotlinx.coroutines.suspendCancellableCoroutine
@@ -201,7 +202,7 @@
201202 if (EditorUtils.editorFileExist(params.filepath)) EditorUtils.getOrOpenEditor(project, params.filepath)
202203 else EditorUtils.getEditorByCreateFile(project, params.filepath)
203204
204- val diffStreamService = project.getService(DiffStreamService::class.java)
205+ val diffStreamService = project.service<DiffStreamService>()
205206
206207 val handler = ApplyToFileHandler(
207208 project, continuePluginService, ide, params, editorUtils, diffStreamService
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +3 −11
@@ -9,7 +9,7 @@
99 import com.intellij.diff.requests.SimpleDiffRequest
1010 import com.intellij.openapi.application.ApplicationManager
1111 import com.intellij.openapi.command.WriteCommandAction
12-import com.intellij.openapi.components.ServiceManager
12+import com.intellij.openapi.components.service
1313 import com.intellij.openapi.fileEditor.FileDocumentManager
1414 import com.intellij.openapi.project.DumbAware
1515 import com.intellij.openapi.project.Project
@@ -18,7 +18,6 @@
1818 import com.intellij.openapi.vfs.LocalFileSystem
1919 import java.awt.Toolkit
2020 import java.io.File
21-import java.net.URI
2221 import java.nio.file.Paths
2322 import javax.swing.Action
2423 import javax.swing.JComponent
@@ -89,11 +88,7 @@
8988 FileDocumentManager.getInstance().saveDocument(document)
9089
9190 // Notify server of acceptance
92- val continuePluginService = ServiceManager.getService(
93- project,
94- ContinuePluginService::class.java
95- )
96- continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex)
91+ project.service<ContinuePluginService>().ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex)
9792
9893 // Clean up state
9994 cleanUpFile(file)
@@ -102,10 +97,7 @@
10297 fun rejectDiff(file2: String?) {
10398 val file = (file2 ?: lastFile2) ?: return
10499 val diffInfo = diffInfoMap[file] ?: return
105- val continuePluginService = ServiceManager.getService(
106- project,
107- ContinuePluginService::class.java
108- )
100+ val continuePluginService = project.service<ContinuePluginService>()
109101 continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
110102 continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
111103 continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +7 −5
@@ -6,6 +6,7 @@
66 import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
77 import com.github.continuedev.continueintellijextension.editor.DiffStreamService
88 import com.github.continuedev.continueintellijextension.editor.EditorUtils
9+import com.github.continuedev.continueintellijextension.error.ContinueErrorService
910 import com.github.continuedev.continueintellijextension.protocol.*
1011 import com.github.continuedev.continueintellijextension.services.*
1112 import com.github.continuedev.continueintellijextension.utils.*
@@ -46,7 +47,7 @@
4647 init {
4748 // Setup config.json / config.ts save listeners
4849 VirtualFileManager.getInstance().addAsyncFileListener(
49- AsyncFileSaveListener(continuePluginService), ContinuePluginDisposable.getInstance(project)
50+ AsyncFileSaveListener(continuePluginService), project.service<ContinuePluginDisposable>()
5051 )
5152 }
5253
@@ -67,8 +68,7 @@
6768 }
6869
6970 "jetbrains/isOSREnabled" -> {
70- val isOSREnabled =
71- ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
71+ val isOSREnabled = service<ContinueExtensionSettings>().continueState.enableOSR
7272 respond(isOSREnabled)
7373 }
7474
@@ -463,8 +463,10 @@
463463 println("Unknown message type: $messageType")
464464 }
465465 }
466- } catch (error: Exception) {
467- ide.showToast(ToastType.ERROR, " Error handling message of type $messageType: $error")
466+ } catch (exception: Exception) {
467+ val exceptionMessage = "Error handling message of type $messageType: $exception"
468+ service<ContinueErrorService>().report(exception, exceptionMessage)
469+ ide.showToast(ToastType.ERROR, exceptionMessage)
468470 }
469471 }
470472 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +10 −15
@@ -1,9 +1,9 @@
11 package com.github.continuedev.continueintellijextension.`continue`
22
33 import com.github.continuedev.continueintellijextension.*
4-import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
54 import com.github.continuedev.continueintellijextension.constants.ContinueConstants
6-import com.github.continuedev.continueintellijextension.`continue`.GitService
5+import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
6+import com.github.continuedev.continueintellijextension.error.ContinueErrorService
77 import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
88 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
99 import com.github.continuedev.continueintellijextension.utils.*
@@ -11,7 +11,6 @@
1111 import com.intellij.execution.configurations.GeneralCommandLine
1212 import com.intellij.execution.util.ExecUtil
1313 import com.intellij.ide.BrowserUtil
14-import com.intellij.ide.plugins.PluginManager
1514 import com.intellij.ide.plugins.PluginManagerCore
1615 import com.intellij.lang.annotation.HighlightSeverity
1716 import com.intellij.notification.NotificationAction
@@ -38,9 +37,7 @@
3837 import java.io.File
3938 import java.io.FileInputStream
4039 import java.io.InputStreamReader
41-import java.net.URI
4240 import java.nio.charset.Charset
43-import java.nio.file.Paths
4441
4542 class IntelliJIDE(
4643 private val project: Project,
@@ -344,11 +341,10 @@
344341 command.setWorkDirectory(project.basePath)
345342 val results = ExecUtil.execAndGetOutput(command).stdout
346343 return results.split("\n")
347- } catch (e: Exception) {
348- showToast(
349- ToastType.ERROR,
350- "Error executing ripgrep: ${e.message}"
351- )
344+ } catch (exception: Exception) {
345+ val message = "Error executing ripgrep: ${exception.message}"
346+ service<ContinueErrorService>().report(exception, message)
347+ showToast(ToastType.ERROR, message)
352348 return emptyList()
353349 }
354350 } else {
@@ -386,11 +382,10 @@
386382
387383 command.setWorkDirectory(project.basePath)
388384 return ExecUtil.execAndGetOutput(command).stdout
389- } catch (e: Exception) {
390- showToast(
391- ToastType.ERROR,
392- "Error executing ripgrep: ${e.message}"
393- )
385+ } catch (exception: Exception) {
386+ val message = "Error executing ripgrep: ${exception.message}"
387+ service<ContinueErrorService>().report(exception, message)
388+ showToast(ToastType.ERROR, message)
394389 return "Error: Unable to execute ripgrep command."
395390 }
396391 } else {
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +4 −5
@@ -7,7 +7,7 @@
77 import com.intellij.openapi.application.ApplicationManager
88 import com.intellij.openapi.command.WriteCommandAction
99 import com.intellij.openapi.command.undo.UndoManager
10-import com.intellij.openapi.components.ServiceManager
10+import com.intellij.openapi.components.service
1111 import com.intellij.openapi.editor.Editor
1212 import com.intellij.openapi.editor.markup.HighlighterLayer
1313 import com.intellij.openapi.editor.markup.RangeHighlighter
@@ -42,7 +42,6 @@
4242 private var isRunning: Boolean = false
4343 private var hasAcceptedOrRejectedBlock: Boolean = false
4444 private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
45- private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
4645 private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
4746
4847
@@ -62,10 +61,10 @@
6261 numDiffs = diffBlocks.size,
6362 filepath = virtualFile?.url,
6463 fileContent = "not implemented",
65- toolCallId = toolCallId?.toString()
64+ toolCallId = toolCallId
6665 )
6766
68- continuePluginService.sendToWebview("updateApplyState", payload)
67+ project.service<ContinuePluginService>().sendToWebview("updateApplyState", payload)
6968 }
7069
7170 fun acceptAll() {
@@ -102,7 +101,7 @@
102101 isRunning = true
103102 sendUpdate(ApplyStateStatus.STREAMING)
104103
105- continuePluginService.coreMessenger?.request(
104+ project.service<ContinuePluginService>().coreMessenger?.request(
106105 "streamDiffLines",
107106 StreamDiffLinesPayload(
108107 input = input,
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt +50 −0
@@ -0,0 +1,50 @@
1+package com.github.continuedev.continueintellijextension.error
2+
3+import com.intellij.ide.plugins.PluginManagerCore
4+import com.intellij.openapi.application.ApplicationInfo
5+import com.intellij.openapi.components.Service
6+import com.intellij.openapi.diagnostic.Attachment
7+import com.intellij.openapi.diagnostic.Logger
8+import com.intellij.openapi.extensions.PluginId
9+import com.intellij.ui.jcef.JBCefApp
10+import io.sentry.Hint
11+import io.sentry.Sentry
12+import io.sentry.SentryEvent
13+import io.sentry.protocol.Message
14+
15+private typealias SentryAttachment = io.sentry.Attachment
16+
17+@Service
18+class ContinueErrorService {
19+ private val log = Logger.getInstance(ContinueErrorService::class.java)
20+
21+ init {
22+ Sentry.init { config ->
23+ config.dsn = SENTRY_DSN
24+ config.isSendDefaultPii = false
25+ config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
26+ config.setTag("jcef_supported", JBCefApp.isSupported().toString())
27+ config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version)
28+ }
29+ }
30+
31+ fun report(
32+ throwable: Throwable,
33+ message: String? = null,
34+ attachments: List<Attachment>? = null
35+ ) {
36+ val sentryEvent = SentryEvent()
37+ sentryEvent.throwable = throwable
38+ sentryEvent.message = Message().apply { this.message = message }
39+ val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) })
40+ Sentry.captureEvent(sentryEvent, hint)
41+ log.warn("Problem sent to Sentry: $message", throwable)
42+ }
43+
44+ private companion object {
45+ private const val PLUGIN_ID = "com.github.continuedev.continueintellijextension"
46+ private const val SENTRY_DSN =
47+ "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016"
48+ }
49+
50+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt +8 −24
@@ -1,29 +1,16 @@
11 package com.github.continuedev.continueintellijextension.error
22
33 import com.intellij.diagnostic.IdeaReportingEvent
4-import com.intellij.openapi.application.ApplicationInfo
4+import com.intellij.openapi.components.service
55 import com.intellij.openapi.diagnostic.ErrorReportSubmitter
66 import com.intellij.openapi.diagnostic.IdeaLoggingEvent
77 import com.intellij.openapi.diagnostic.SubmittedReportInfo
88 import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus
9-import com.intellij.ui.jcef.JBCefApp
109 import com.intellij.util.Consumer
11-import io.sentry.Sentry
12-import io.sentry.SentryEvent
13-import io.sentry.protocol.Message
1410 import java.awt.Component
1511
1612 class ContinueErrorSubmitter : ErrorReportSubmitter() {
1713
18- init {
19- Sentry.init { config ->
20- config.dsn = SENTRY_DSN
21- config.isSendDefaultPii = false
22- config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
23- config.setTag("jcef_supported", JBCefApp.isSupported().toString())
24- }
25- }
26-
2714 override fun getReportActionText() =
2815 "Report to Continue"
2916
@@ -34,12 +21,13 @@
3421 consumer: Consumer<in SubmittedReportInfo>
3522 ): Boolean {
3623 try {
37- val event = events.filterIsInstance<IdeaReportingEvent>().firstOrNull() ?: return false
38- val sentryEvent = SentryEvent()
39- sentryEvent.throwable = event.data.throwable
40- sentryEvent.message = Message().apply { message = additionalInfo }
41- sentryEvent.setTag("plugin_version", event.plugin?.version)
42- Sentry.captureEvent(sentryEvent)
24+ val event = events.filterIsInstance<IdeaReportingEvent>()
25+ .firstOrNull() ?: return false
26+ service<ContinueErrorService>().report(
27+ throwable = event.data.throwable,
28+ message = additionalInfo ?: event.data.message,
29+ attachments = event.data.allAttachments
30+ )
4331 } catch (_: Exception) {
4432 consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED))
4533 return false
@@ -48,8 +36,4 @@
4836 return true
4937 }
5038
51- private companion object {
52- private const val SENTRY_DSN = "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016"
53- }
54-
5539 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +1 −1
@@ -111,7 +111,7 @@
111111
112112 companion object {
113113 val instance: ContinueExtensionSettings
114- get() = ServiceManager.getService(ContinueExtensionSettings::class.java)
114+ get() = service<ContinueExtensionSettings>()
115115 }
116116
117117
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +14 −15
@@ -9,30 +9,21 @@
99 import com.google.gson.Gson
1010 import com.google.gson.JsonObject
1111 import com.google.gson.JsonParser
12+import com.intellij.openapi.components.service
1213 import com.intellij.openapi.project.Project
1314 import com.intellij.openapi.util.Disposer
1415 import com.intellij.ui.jcef.*
1516 import com.intellij.ui.jcef.JBCefClient.Properties
16-import com.intellij.util.application
1717 import org.cef.CefApp
1818 import org.cef.browser.CefBrowser
1919 import org.cef.handler.CefLoadHandlerAdapter
2020
2121 class ContinueBrowser(val project: Project, url: String) {
22- private fun registerAppSchemeHandler() {
23- CefApp.getInstance().registerSchemeHandlerFactory(
24- "http",
25- "continue",
26- CustomSchemeHandlerFactory()
27- )
28- }
2922
3023 val browser: JBCefBrowser
3124
32- val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java)
33-
3425 init {
35- val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
26+ val isOSREnabled = service<ContinueExtensionSettings>().continueState.enableOSR
3627
3728 this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply {
3829 // To avoid using System.setProperty to affect other plugins,
@@ -43,7 +34,7 @@
4334 }
4435
4536 registerAppSchemeHandler()
46- Disposer.register(ContinuePluginDisposable.getInstance(project), browser)
37+ Disposer.register(project.service<ContinuePluginDisposable>(), browser)
4738
4839 // Listen for events sent from browser
4940 val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!)
@@ -60,7 +51,7 @@
6051 }
6152
6253 if (PASS_THROUGH_TO_CORE.contains(messageType)) {
63- continuePluginService.coreMessenger?.request(messageType, data, messageId, respond)
54+ project.service<ContinuePluginService>().coreMessenger?.request(messageType, data, messageId, respond)
6455 return@addHandler null
6556 }
6657
@@ -75,7 +66,7 @@
7566 }
7667
7768 if (msg != null) {
78- continuePluginService.ideProtocolClient?.handleMessage(msg, respondToWebview)
69+ project.service<ContinuePluginService>().ideProtocolClient?.handleMessage(msg, respondToWebview)
7970 }
8071
8172 null
@@ -99,7 +90,7 @@
9990 // Load the url only after the protocolClient is initialized,
10091 // otherwise some messages will be lost, which are some configurations when the page is loaded.
10192 // Moreover, we should add LoadHandler before loading the url.
102- continuePluginService.onProtocolClientInitialized {
93+ project.service<ContinuePluginService>().onProtocolClientInitialized {
10394 browser.loadURL(url)
10495 }
10596
@@ -138,6 +129,14 @@
138129 }
139130 }
140131
132+ private fun registerAppSchemeHandler() {
133+ CefApp.getInstance().registerSchemeHandlerFactory(
134+ "http",
135+ "continue",
136+ CustomSchemeHandlerFactory()
137+ )
138+ }
139+
141140 private fun buildJavaScript(jsonData: String): String {
142141 return """window.postMessage($jsonData, "*");"""
143142 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +3 −5
@@ -3,13 +3,13 @@
33 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
44 import com.intellij.openapi.actionSystem.ActionManager
55 import com.intellij.openapi.actionSystem.AnAction
6-import com.intellij.openapi.components.ServiceManager
6+import com.intellij.openapi.components.service
77 import com.intellij.openapi.project.DumbAware
88 import com.intellij.openapi.project.Project
99 import com.intellij.openapi.wm.ToolWindow
1010 import com.intellij.openapi.wm.ToolWindowFactory
1111 import com.intellij.ui.content.ContentFactory
12-import javax.swing.*
12+import javax.swing.JComponent
1313
1414 const val JS_QUERY_POOL_SIZE = "200"
1515
@@ -52,9 +52,7 @@
5252 val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl
5353
5454 val browser = ContinueBrowser(project, url)
55- val continuePluginService =
56- ServiceManager.getService(project, ContinuePluginService::class.java)
57- continuePluginService.continuePluginWindow = this
55+ project.service<ContinuePluginService>().continuePluginWindow = this
5856 browser
5957 }
6058
modified extensions/vscode/e2e/README.md +8 −0
@@ -31,3 +31,11 @@
3131 - Is your `data-testid` or selector actually just wrong?
3232 - Are you inconsistently getting different behaviors? You can try adding a `TestUtils.waitForTimeout` between two events if you think it's caused by a race condition. Note that this may lead to flake down the road.
3333 - Alternatively, you can add a `TestUtils.waitForSuccess`
34+
35+### How is it connecting to the LLM?
36+
37+- This depends on the model provider written inside the `test-continue/config.json` and `test-continue/config.yaml`. If the model provider is `mock`, it will use `MockLLM`, and if it uses `test`, it will use `TestLLM`.
38+
39+### Quirks
40+
41+- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.
No newline at the end of the file
modified extensions/vscode/e2e/TestUtils.ts +17 −0
@@ -1,9 +1,26 @@
11 import { expect } from "chai";
22 import { Key } from "vscode-extension-tester";
33
4+import { access, constants } from 'fs/promises';
5+import * as path from "path";
46 import { DEFAULT_TIMEOUT } from "./constants";
57
68 export class TestUtils {
9+ public static CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? "";
10+
11+ public static getGlobalContextFilePath(): string {
12+ return path.join(TestUtils.CONTINUE_GLOBAL_DIR, "index", "globalContext.json");
13+ }
14+
15+ public static async fileExists(path: string): Promise<boolean> {
16+ try {
17+ await access(path, constants.F_OK);
18+ return true;
19+ } catch {
20+ return false;
21+ }
22+ }
23+
724 /**
825 * In many cases it might be more useful to use existing Selenium
926 * utilities. For example:
added extensions/vscode/e2e/actions/NextEdit.actions.ts +60 −0
@@ -0,0 +1,60 @@
1+import { expect } from "chai";
2+import { TextEditor, VSBrowser, Workbench } from "vscode-extension-tester";
3+
4+import { DEFAULT_TIMEOUT } from "../constants";
5+import { NextEditSelectors } from "../selectors/NextEdit.selectors";
6+import { TestUtils } from "../TestUtils";
7+
8+export class NextEditActions {
9+ /**
10+ * Test accepting a Next Edit suggestion with Tab.
11+ */
12+ public static async acceptNextEditSuggestion(editor: TextEditor) {
13+ const hasDecoration = await NextEditActions.forceNextEdit(editor);
14+ expect(hasDecoration).to.be.true;
15+
16+ await new Workbench().executeCommand("Continue: Accept Next Edit Suggestion");
17+
18+ // Check if HELLO is written into the editor.
19+ const editorText = await editor.getTextAtLine(1);
20+
21+ return editorText === "HELLO";
22+ }
23+
24+ /**
25+ * Test rejecting a Next Edit suggestion with Esc.
26+ */
27+ public static async rejectNextEditSuggestion(editor: TextEditor) {
28+ const hasDecoration = await NextEditActions.forceNextEdit(editor);
29+ expect(hasDecoration).to.be.true;
30+
31+ await new Workbench().executeCommand("Continue: Hide Next Edit Suggestion");
32+
33+ // Check if the editor text didn't change.
34+ const editorText = await editor.getText();
35+
36+ return editorText === "def main():\n ";
37+ }
38+
39+ /**
40+ * Force a Next Edit suggestion using command.
41+ */
42+ public static async forceNextEdit(editor: TextEditor): Promise<boolean> {
43+ await editor.setText("def main():\n ");
44+ await editor.moveCursor(2, 4);
45+
46+ await new Workbench().executeCommand("Continue: Force Next Edit");
47+ await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL);
48+
49+ const svgDecoration = await TestUtils.waitForSuccess(
50+ () => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver),
51+ DEFAULT_TIMEOUT.XL
52+ );
53+
54+ return svgDecoration !== null;
55+ }
56+
57+ public static async reload(): Promise<void> {
58+ await new Workbench().executeCommand('workbench.action.reloadWindow');
59+ }
60+}
modified extensions/vscode/e2e/constants.ts +1 −0
@@ -5,4 +5,5 @@
55 SM: BASELINE * 0.5,
66 MD: BASELINE,
77 XL: BASELINE * 5,
8+ XXL: BASELINE * 7,
89 };
added extensions/vscode/e2e/selectors/NextEdit.selectors.ts +19 −0
@@ -0,0 +1,19 @@
1+import { By, WebDriver } from "vscode-extension-tester";
2+
3+export class NextEditSelectors {
4+ /**
5+ * Get the SVG decoration element if present (for next edit).
6+ */
7+ public static async getSvgDecoration(driver: WebDriver) {
8+ try {
9+ const decorations = await driver.findElement(
10+ // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]")
11+ By.css("[class*='TextEditorDecorationType']")
12+ );
13+ return decorations ?? null;
14+ } catch (error) {
15+ console.error("Error finding SVG decoration:", error);
16+ return null;
17+ }
18+ }
19+}
No newline at the end of the file
added extensions/vscode/e2e/tests/NextEdit.test.ts +120 −0
@@ -0,0 +1,120 @@
1+import { expect } from "chai";
2+import * as fs from "fs/promises";
3+import { EditorView, TextEditor } from "vscode-extension-tester";
4+
5+import { GlobalActions } from "../actions/Global.actions";
6+import { NextEditActions } from "../actions/NextEdit.actions";
7+import { DEFAULT_TIMEOUT } from "../constants";
8+import { TestUtils } from "../TestUtils";
9+
10+describe("Next Edit", () => {
11+ let editor: TextEditor;
12+
13+ before(async function () {
14+ // this.timeout(DEFAULT_TIMEOUT.XL);
15+
16+ const globalContextPath = TestUtils.getGlobalContextFilePath();
17+
18+ // Update config.json to add optInNextEditFeature.
19+ // globalContext.json does not exist in CI before this test runs.
20+ if (await TestUtils.fileExists(globalContextPath)) {
21+ const globalContext = await fs.readFile(globalContextPath, "utf8");
22+ const sharedConfig = JSON.parse(globalContext).sharedConfig;
23+
24+ const sharedConfigWithNextEditEnabled = {
25+ ...sharedConfig,
26+ "optInNextEditFeature": true
27+ };
28+
29+ const globalContextWithNextEditEnabled = {
30+ ...JSON.parse(globalContext),
31+ "sharedConfig": sharedConfigWithNextEditEnabled
32+ };
33+
34+ await fs.writeFile(globalContextPath, JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
35+ } else {
36+ await fs.writeFile(
37+ globalContextPath,
38+ JSON.stringify(
39+ {
40+ sharedConfig: {
41+ optInNextEditFeature: true
42+ },
43+ selectedModelsByProfileId: {
44+ local: {
45+ chat: "TEST LLM",
46+ edit: "TEST LLM",
47+ apply: "TEST LLM",
48+ embed: "Transformers.js (Built-In)",
49+ autocomplete: "TEST LLM",
50+ rerank: null,
51+ summarize: null
52+ }
53+ }
54+ },
55+ null,
56+ 2,
57+ ),
58+ );
59+ }
60+
61+ await NextEditActions.reload();
62+ }).timeout(DEFAULT_TIMEOUT.XL);
63+
64+ beforeEach(async function () {
65+ // this.timeout(DEFAULT_TIMEOUT.XL);
66+
67+ await GlobalActions.openTestWorkspace();
68+ ({ editor } = await GlobalActions.createAndOpenNewTextFile());
69+ }).timeout(DEFAULT_TIMEOUT.XL);
70+
71+ afterEach(async function () {
72+ // this.timeout(DEFAULT_TIMEOUT.XL);
73+
74+ await editor.clearText();
75+ await new EditorView().closeAllEditors();
76+ }).timeout(DEFAULT_TIMEOUT.XL);
77+
78+ after(async function () {
79+ // this.timeout(DEFAULT_TIMEOUT.XL);
80+
81+ // Update config.json to delete optInNextEditFeature.
82+ const globalContext = await fs.readFile(TestUtils.getGlobalContextFilePath(), "utf8");
83+ const sharedConfig = JSON.parse(globalContext).sharedConfig;
84+
85+ const sharedConfigWithoutNextEdit = { ...sharedConfig };
86+ delete sharedConfigWithoutNextEdit.optInNextEditFeature;
87+
88+ const globalContextWithNextEditEnabled = {
89+ ...JSON.parse(globalContext),
90+ "sharedConfig": sharedConfigWithoutNextEdit
91+ };
92+
93+ await fs.writeFile(TestUtils.getGlobalContextFilePath(), JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
94+ await NextEditActions.reload();
95+ }).timeout(DEFAULT_TIMEOUT.XL);
96+
97+ // it("Should enable Next Edit feature in settings", async () => {
98+ // expect(false).to.be.true;
99+ // }).timeout(DEFAULT_TIMEOUT.XL);
100+
101+ // it("Should check that autocomplete is disabled when next edit is enabled", async () => {
102+ // expect(false).to.be.true;
103+ // }).timeout(DEFAULT_TIMEOUT.XL);
104+
105+ it("Should force a Next Edit", async () => {
106+ const hasDecoration = await NextEditActions.forceNextEdit(editor);
107+ expect(hasDecoration).to.be.true;
108+ }).timeout(DEFAULT_TIMEOUT.XXL);
109+
110+ it("Should accept Next Edit suggestion with Tab", async () => {
111+ const accepted = await NextEditActions.acceptNextEditSuggestion(editor);
112+ expect(accepted).to.be.true;
113+ }).timeout(DEFAULT_TIMEOUT.XXL);
114+
115+ it("Should reject Next Edit suggestion with Esc", async () => {
116+ const rejected = await NextEditActions.rejectNextEditSuggestion(editor);
117+ expect(rejected).to.be.true;
118+ }).timeout(DEFAULT_TIMEOUT.XXL);
119+
120+});
No newline at the end of the file
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 +27 −1
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.52",
5+ "version": "1.1.54",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -334,6 +334,21 @@
334334 "category": "Continue",
335335 "title": "Enter Enterprise License Key",
336336 "group": "Continue"
337+ },
338+ {
339+ "command": "continue.nextEditWindow.hideNextEditSuggestion",
340+ "category": "Continue",
341+ "title": "Hide Next Edit Suggestion"
342+ },
343+ {
344+ "command": "continue.nextEditWindow.acceptNextEditSuggestion",
345+ "category": "Continue",
346+ "title": "Accept Next Edit Suggestion"
347+ },
348+ {
349+ "command": "continue.forceNextEdit",
350+ "category": "Continue",
351+ "title": "Continue: Force Next Edit"
337352 }
338353 ],
339354 "keybindings": [
@@ -426,6 +441,16 @@
426441 "command": "continue.applyCodeFromChat",
427442 "mac": "alt+a",
428443 "key": "alt+a"
444+ },
445+ {
446+ "command": "continue.nextEditWindow.hideNextEditSuggestion",
447+ "key": "escape",
448+ "when": "editorTextFocus && nextEditWindowActive"
449+ },
450+ {
451+ "command": "continue.nextEditWindow.acceptNextEditSuggestion",
452+ "key": "tab",
453+ "when": "editorTextFocus && nextEditWindowActive"
429454 }
430455 ],
431456 "submenus": [
@@ -644,6 +669,7 @@
644669 "e2e:test": "extest run-tests ${TEST_FILE:-'./e2e/_output/tests/*.test.js'} --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
645670 "e2e:clean": "rm -rf ./e2e/_output ./e2e/storage",
646671 "e2e:all": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
672+ "e2e:all-non-mac": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
647673 "e2e:recompile-extension": "npm run package && npm run e2e:compile && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
648674 "e2e:rebuild-gui": "rm -rf gui && cp -r ../../gui/dist gui && npm run package && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
649675 "e2e:quick": "npm run e2e:compile && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
added extensions/vscode/src/activation/NextEditWindowManager.ts +720 −0
@@ -0,0 +1,720 @@
1+/* eslint-disable @typescript-eslint/naming-convention */
2+import { EXTENSION_NAME } from "core/control-plane/env";
3+// @ts-ignore
4+import * as vscode from "vscode";
5+
6+import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
7+import { myersDiff } from "core/diff/myers";
8+import {
9+ NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
10+ NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
11+} from "core/nextEdit/constants";
12+import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
13+import { getThemeString } from "../util/getTheme";
14+
15+export interface TextApplier {
16+ applyText(
17+ editor: vscode.TextEditor,
18+ text: string,
19+ position: vscode.Position,
20+ finalCursorPos: vscode.Position | null,
21+ ): Promise<boolean>;
22+}
23+
24+const SVG_CONFIG = {
25+ stroke: "#999998",
26+ strokeWidth: 1,
27+ textColor: "#999998",
28+ filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
29+ radius: 3,
30+ leftMargin: 40,
31+ defaultText: "",
32+ lineSpacing: 1.2, // Line spacing multiplier
33+ cursorOffset: 4, // Spaces to offset from cursor
34+
35+ get fontSize() {
36+ return Math.ceil(
37+ vscode.workspace.getConfiguration("editor").get<number>("fontSize") ?? 14,
38+ );
39+ },
40+ get fontFamily() {
41+ return (
42+ vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
43+ "helvetica"
44+ );
45+ },
46+ get paddingX() {
47+ return Math.ceil(this.getEstimatedTextWidth(" "));
48+ },
49+ get paddingY() {
50+ return Math.ceil(this.fontSize * 0.3);
51+ },
52+ get lineHeight() {
53+ return Math.ceil(this.fontSize * this.lineSpacing);
54+ },
55+ getEstimatedTextWidth(text: string): number {
56+ return text.length * this.fontSize * 0.6;
57+ },
58+ getTipWidth(text: string): number {
59+ // Find the longest line
60+ const lines = text.split("\n");
61+ const longestLine = lines.reduce(
62+ (longest, line) => (line.length > longest.length ? line : longest),
63+ "",
64+ );
65+
66+ return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2;
67+ },
68+ getTipHeight(text: string): number {
69+ // Count the number of lines
70+ const lineCount = text.split("\n").length;
71+ return this.lineHeight * lineCount + this.paddingY * 2;
72+ },
73+} as const;
74+
75+// Command ID - can be used in package.json
76+export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND =
77+ "continue.nextEditWindow.hideNextEditSuggestion";
78+export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND =
79+ "continue.nextEditWindow.acceptNextEditSuggestion";
80+
81+export class NextEditWindowManager {
82+ private static instance: NextEditWindowManager | undefined;
83+
84+ private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"];
85+ private theme: string;
86+ private fontSize: number;
87+ private fontFamily: string;
88+ private codeRenderer: CodeRenderer;
89+
90+ // Current active decoration
91+ private currentDecoration: vscode.TextEditorDecorationType | null = null;
92+ // Track which editor has the active decoration
93+ private activeEditor: vscode.TextEditor | null = null;
94+ // Store the current tooltip text for accepting
95+ private currentTooltipText: string | null = null;
96+
97+ // Disposables
98+ private disposables: vscode.Disposable[] = [];
99+
100+ private textApplier: TextApplier | null = null;
101+
102+ private finalCursorPos: vscode.Position | null = null;
103+
104+ private context: vscode.ExtensionContext | null = null;
105+
106+ public static getInstance(): NextEditWindowManager {
107+ if (!NextEditWindowManager.instance) {
108+ NextEditWindowManager.instance = new NextEditWindowManager();
109+ }
110+ return NextEditWindowManager.instance;
111+ }
112+
113+ public static isInstantiated(): boolean {
114+ return !!NextEditWindowManager.instance;
115+ }
116+
117+ public static clearInstance(): void {
118+ if (NextEditWindowManager.instance) {
119+ NextEditWindowManager.instance.dispose();
120+ NextEditWindowManager.instance = undefined;
121+ }
122+ }
123+
124+ private constructor() {
125+ this.theme = getThemeString();
126+
127+ console.log(
128+ "Next Edit Theme initialized:",
129+ this.theme
130+ ? `Theme exists: ${JSON.stringify(this.theme)}`
131+ : "Theme is undefined",
132+ );
133+ this.setupListeners();
134+ this.codeRenderer = CodeRenderer.getInstance();
135+
136+ const editorConfig = vscode.workspace.getConfiguration("editor");
137+ this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
138+ this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
139+ }
140+
141+ public static async reserveTabAndEsc() {
142+ await vscode.commands.executeCommand(
143+ "setContext",
144+ "nextEditWindowActive",
145+ true,
146+ );
147+ }
148+
149+ public static async freeTabAndEsc() {
150+ await vscode.commands.executeCommand(
151+ "setContext",
152+ "nextEditWindowActive",
153+ false,
154+ );
155+ }
156+
157+ /**
158+ * An async setup function to help us initialize the NextEditWindowManager.
159+ * This is necessary because we need some setup to be done asynchronously,
160+ * and constructors in TypeScript cannot be async.
161+ * Plus, it's generally not recommended to pass arguments to getInstance() of a singleton.
162+ * @param context The extension context.
163+ * @param textApplier Callback that lets us use external deps such as llms if needed.
164+ */
165+ public async setupNextEditWindowManager(
166+ context: vscode.ExtensionContext,
167+ textApplier?: TextApplier,
168+ ) {
169+ this.context = context;
170+
171+ // Set nextEditWindowActive to false to free esc and tab,
172+ // letting them return to their original behaviors.
173+ await NextEditWindowManager.freeTabAndEsc();
174+
175+ // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
176+ this.registerCommandSafely(
177+ HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
178+ async () => await this.hideAllNextEditWindows(),
179+ );
180+ this.registerCommandSafely(
181+ ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
182+ async () => await this.acceptNextEdit(),
183+ );
184+
185+ // Add this class to context disposables.
186+ context.subscriptions.push(this);
187+
188+ if (textApplier) {
189+ this.textApplier = textApplier;
190+ }
191+
192+ await this.codeRenderer.setTheme(this.theme);
193+ }
194+
195+ /**
196+ * Registers our two custom commands to the extension context.
197+ * @param commandId Custom commands to help set up next edit.
198+ * @param callback Function to run on command execution.
199+ */
200+ private registerCommandSafely(
201+ commandId:
202+ | "continue.nextEditWindow.hideNextEditSuggestion"
203+ | "continue.nextEditWindow.acceptNextEditSuggestion",
204+ callback: () => Promise<void>,
205+ ) {
206+ if (!this.context) {
207+ console.log("Extension context is not yet set.");
208+ return;
209+ }
210+
211+ try {
212+ const command = vscode.commands.registerCommand(commandId, callback);
213+ this.context.subscriptions.push(command);
214+ } catch (error) {
215+ console.log(
216+ `Command ${commandId} already has an associated callback, skipping registration`,
217+ );
218+ }
219+ }
220+
221+ /**
222+ * Show a tooltip with the given text at the current cursor position.
223+ * @param editor The active text editor.
224+ * @param text Text to display in the tooltip.
225+ */
226+ public async showNextEditWindow(
227+ editor: vscode.TextEditor,
228+ newEditRangeSlice: string,
229+ ) {
230+ if (!newEditRangeSlice || !this.shouldRenderTip(editor.document.uri)) {
231+ return;
232+ }
233+
234+ // Clear any existing decorations first (very important to prevent overlapping).
235+ await this.hideAllNextEditWindows();
236+
237+ // Store the current tooltip text for accepting later.
238+ this.currentTooltipText = newEditRangeSlice;
239+
240+ // Get the contents of the old (current) editable region.
241+ const currCursorPos = editor.selection.active;
242+ const editableRegionStartLine = Math.max(
243+ currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
244+ 0,
245+ );
246+ const editableRegionEndLine = Math.min(
247+ currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
248+ editor.document.lineCount - 1,
249+ );
250+ const oldEditRangeSlice = editor.document
251+ .getText()
252+ .split("\n")
253+ .slice(editableRegionStartLine, editableRegionEndLine + 1)
254+ .join("\n");
255+
256+ // We don't need to show the next edit window under these conditions:
257+ // - There are no predicted edits.
258+ // - The predicted edits are identical to the previous version.
259+ if (newEditRangeSlice === "" || oldEditRangeSlice === newEditRangeSlice)
260+ return;
261+
262+ const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice);
263+
264+ // How far away is the current line from the start of the editable region?
265+ const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine;
266+
267+ // How long is the line at the current cursor position?
268+ const lineContentAtCursorPos =
269+ newEditRangeSlice.split("\n")[lineOffsetAtCursorPos];
270+
271+ const offset = getOffsetPositionAtLastNewLine(
272+ diffLines,
273+ lineContentAtCursorPos,
274+ lineOffsetAtCursorPos,
275+ );
276+
277+ // Calculate the actual line number in the editor by adding the startPos offset
278+ // to the line number from the diff calculation.
279+ this.finalCursorPos = new vscode.Position(
280+ editableRegionStartLine + offset.line,
281+ offset.character,
282+ );
283+
284+ // Create and apply decoration with the text.
285+ await this.renderTooltip(editor, currCursorPos, newEditRangeSlice);
286+
287+ // Reserve tab and esc to either accept or reject the displayed next edit contents.
288+ await NextEditWindowManager.reserveTabAndEsc();
289+ }
290+
291+ /**
292+ * Hide all tooltips in all editors.
293+ */
294+ public async hideAllNextEditWindows() {
295+ if (this.currentDecoration) {
296+ vscode.window.visibleTextEditors.forEach((editor) => {
297+ editor.setDecorations(this.currentDecoration!, []);
298+ });
299+
300+ // If we know which editor had the decoration, clear it specifically.
301+ // This is a bit redundant but ensures we don't leave any decorations behind.
302+ if (this.activeEditor) {
303+ this.activeEditor.setDecorations(this.currentDecoration, []);
304+ this.activeEditor = null;
305+ }
306+
307+ // This prevents memory leaks.
308+ this.currentDecoration.dispose();
309+ this.currentDecoration = null;
310+
311+ this.disposables.forEach((d) => d.dispose());
312+ this.disposables = [];
313+
314+ // Clear the current tooltip text.
315+ this.currentTooltipText = null;
316+ }
317+
318+ await NextEditWindowManager.freeTabAndEsc();
319+ }
320+
321+ /**
322+ * Accept the current next edit suggestion by inserting it at cursor position.
323+ */
324+ private async acceptNextEdit() {
325+ if (!this.activeEditor || !this.currentTooltipText) {
326+ return;
327+ }
328+
329+ const editor = this.activeEditor;
330+ const text = this.currentTooltipText;
331+ const position = editor.selection.active;
332+
333+ let success = false;
334+ if (this.textApplier) {
335+ success = await this.textApplier.applyText(
336+ editor,
337+ text,
338+ position,
339+ this.finalCursorPos,
340+ );
341+ } else {
342+ // Define the editable region.
343+ const editableRegionStartLine = Math.max(
344+ 0,
345+ position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
346+ );
347+ const editableRegionEndLine = Math.min(
348+ editor.document.lineCount - 1,
349+ position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
350+ );
351+ const startPos = new vscode.Position(editableRegionStartLine, 0);
352+ const endPosChar = editor.document.lineAt(editableRegionEndLine).text
353+ .length;
354+
355+ const endPos = new vscode.Position(editableRegionEndLine, endPosChar);
356+ const editRange = new vscode.Range(startPos, endPos);
357+
358+ success = await editor.edit((editBuilder) => {
359+ editBuilder.replace(editRange, text);
360+ });
361+
362+ // Disable inline suggestions temporarily.
363+ // This prevents the race condition between vscode's inline completion provider
364+ // and the next edit window manager's cursor repositioning logic.
365+ await vscode.workspace
366+ .getConfiguration()
367+ .update("editor.inlineSuggest.enabled", false, true);
368+ }
369+
370+ if (success) {
371+ // Move cursor to the final position if available.
372+ if (this.finalCursorPos) {
373+ editor.selection = new vscode.Selection(
374+ this.finalCursorPos,
375+ this.finalCursorPos,
376+ );
377+
378+ // Reenable inline suggestions after we move the cursor.
379+ await vscode.workspace
380+ .getConfiguration()
381+ .update("editor.inlineSuggest.enabled", true, true);
382+
383+ await this.hideAllNextEditWindows();
384+ }
385+ }
386+ }
387+
388+ /**
389+ * Dispose of the NextEditWindowManager.
390+ */
391+ public dispose() {
392+ // Dispose current decoration.
393+ if (this.currentDecoration) {
394+ this.currentDecoration.dispose();
395+ this.currentDecoration = null;
396+ }
397+
398+ // Dispose all other disposables.
399+ this.disposables.forEach((d) => d.dispose());
400+ this.disposables = [];
401+ }
402+
403+ /**
404+ * Setup listeners for theme, font, and cursor position changes.
405+ */
406+ private setupListeners() {
407+ // Theme change listener.
408+ vscode.workspace.onDidChangeConfiguration((e) => {
409+ if (
410+ e.affectsConfiguration("workbench.colorTheme") ||
411+ e.affectsConfiguration("editor.fontSize") ||
412+ e.affectsConfiguration("editor.fontFamily") ||
413+ e.affectsConfiguration("window.autoDetectColorScheme") ||
414+ e.affectsConfiguration("window.autoDetectHighContrast") ||
415+ e.affectsConfiguration("workbench.preferredDarkColorTheme") ||
416+ e.affectsConfiguration("workbench.preferredLightColorTheme") ||
417+ e.affectsConfiguration("workbench.preferredHighContrastColorTheme") ||
418+ e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
419+ ) {
420+ this.theme = getThemeString();
421+ this.codeRenderer.setTheme(this.theme);
422+ console.log(
423+ "Theme updated:",
424+ this.theme ? "Theme exists" : "Theme is undefined",
425+ );
426+ const editorConfig = vscode.workspace.getConfiguration("editor");
427+ this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
428+ this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
429+ }
430+ });
431+
432+ // Listen for active color theme changes.
433+ vscode.window.onDidChangeActiveColorTheme(() => {
434+ this.theme = getThemeString();
435+ this.codeRenderer.setTheme(this.theme);
436+ console.log(
437+ "Active theme changed:",
438+ this.theme ? "Theme exists" : "Theme is undefined",
439+ );
440+ });
441+
442+ // Listen for editor changes to clean up decorations when editor closes.
443+ vscode.window.onDidChangeVisibleTextEditors(async () => {
444+ // If our active editor is no longer visible, clear decorations.
445+ if (
446+ this.activeEditor &&
447+ !vscode.window.visibleTextEditors.includes(this.activeEditor)
448+ ) {
449+ await this.hideAllNextEditWindows();
450+ }
451+ });
452+
453+ // Listen for selection changes to hide tooltip when cursor moves.
454+ vscode.window.onDidChangeTextEditorSelection(async (e) => {
455+ // If the selection changed in our active editor, hide the tooltip.
456+ if (this.activeEditor && e.textEditor === this.activeEditor) {
457+ await this.hideAllNextEditWindows();
458+ }
459+ });
460+ }
461+
462+ private shouldRenderTip(uri: vscode.Uri): boolean {
463+ const isAllowedUri =
464+ !this.excludedURIPrefixes.some((prefix) =>
465+ uri.toString().startsWith(prefix),
466+ ) && uri.scheme !== "comment";
467+
468+ const isEnabled =
469+ !!vscode.workspace
470+ .getConfiguration(EXTENSION_NAME)
471+ .get<boolean>("showInlineTip") === true;
472+
473+ return isAllowedUri && isEnabled;
474+ }
475+
476+ /**
477+ * Create a render of the given code, supporting multiple lines.
478+ */
479+ private async createCodeRender(
480+ text: string,
481+ ): Promise<
482+ | { uri: vscode.Uri; dimensions: { width: number; height: number } }
483+ | undefined
484+ > {
485+ try {
486+ const tipWidth = SVG_CONFIG.getTipWidth(text);
487+ const tipHeight = SVG_CONFIG.getTipHeight(text);
488+ const dimensions = {
489+ width: tipWidth,
490+ height: tipHeight,
491+ };
492+
493+ const uri = await this.codeRenderer.getDataUri(
494+ text,
495+ "typescript",
496+ this.fontSize,
497+ this.fontFamily,
498+ dimensions,
499+ SVG_CONFIG.lineHeight,
500+ {
501+ imageType: "svg",
502+ },
503+ );
504+
505+ return {
506+ uri: vscode.Uri.parse(uri),
507+ dimensions,
508+ };
509+ } catch (error) {
510+ console.error("Error creating SVG tooltip:", error);
511+ return undefined;
512+ }
513+ }
514+
515+ /**
516+ * Create a decoration type with the code render.
517+ * @param code: The code to render.
518+ * @returns The decoration.
519+ */
520+ private async createCodeRenderDecoration(
521+ code: string,
522+ ): Promise<vscode.TextEditorDecorationType | undefined> {
523+ const uriAndDimensions = await this.createCodeRender(code);
524+ if (!uriAndDimensions) {
525+ return undefined;
526+ }
527+
528+ const { uri, dimensions } = uriAndDimensions;
529+ const tipWidth = dimensions.width;
530+ const tipHeight = dimensions.height;
531+
532+ return vscode.window.createTextEditorDecorationType({
533+ after: {
534+ contentIconPath: uri,
535+ // border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour};
536+ // border-radius: ${SVG_CONFIG.radius}px;
537+ // filter: ${SVG_CONFIG.filter}`,
538+ // width: `${tipWidth}px`,
539+ // height: `${tipHeight}px`,
540+ // border: `transparent; position: absolute; z-index: 1000;
541+ // box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke},
542+ // inset 0 0 0 ${tipHeight}px ${backgroundColour};
543+ // border-radius: ${SVG_CONFIG.radius}px;
544+ // filter: ${SVG_CONFIG.filter};
545+ // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`,
546+ border: `transparent; position: absolute; z-index: 1000;
547+ box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px;
548+ filter: ${SVG_CONFIG.filter};
549+ border-radius: ${SVG_CONFIG.radius}px;
550+ margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`,
551+ // border: `solid 1px white; position: absolute; z-index: 1000;
552+ // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;
553+ // margin-top: 0em;`,
554+ // border: `solid 1px white; position: absolute; z-index: 1000;
555+ // margin: 0em; padding: 0em;
556+ // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;
557+ // margin-top: 0em;`,
558+ width: `${tipWidth}px`,
559+ height: `${tipHeight}px`,
560+ // textDecoration: `none; transform: translateY(-100%);`,
561+ },
562+ // Set a negative margin to make the decoration float if it starts to displace text.
563+ // Also use absolute positioning.
564+ rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
565+ });
566+ }
567+
568+ private buildHideTooltipHoverMsg() {
569+ const hoverMarkdown = new vscode.MarkdownString(
570+ `[Reject (Esc)](command:${HIDE_NEXT_EDIT_SUGGESTION_COMMAND}) | [Accept (Tab)](command:${ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND})`,
571+ );
572+
573+ hoverMarkdown.isTrusted = true;
574+ hoverMarkdown.supportHtml = true;
575+ return hoverMarkdown;
576+ }
577+
578+ private isValidRange(
579+ editor: vscode.TextEditor,
580+ range: vscode.Range,
581+ ): boolean {
582+ const doc = editor.document;
583+
584+ // Check if line numbers are valid.
585+ if (range.start.line < 0 || range.start.line >= doc.lineCount) {
586+ console.log(
587+ "Invalid start line:",
588+ range.start.line,
589+ "doc lines:",
590+ doc.lineCount,
591+ );
592+ return false;
593+ }
594+
595+ if (range.end.line < 0 || range.end.line >= doc.lineCount) {
596+ console.log(
597+ "Invalid end line:",
598+ range.end.line,
599+ "doc lines:",
600+ doc.lineCount,
601+ );
602+ return false;
603+ }
604+
605+ // Check if character positions are valid.
606+ const startLine = doc.lineAt(range.start.line);
607+ const endLine = doc.lineAt(range.end.line);
608+
609+ if (
610+ range.start.character < 0 ||
611+ range.start.character > startLine.text.length
612+ ) {
613+ console.log(
614+ "Invalid start character:",
615+ range.start.character,
616+ "line length:",
617+ startLine.text.length,
618+ );
619+ return false;
620+ }
621+
622+ if (range.end.character < 0 || range.end.character > endLine.text.length) {
623+ console.log(
624+ "Invalid end character:",
625+ range.end.character,
626+ "line length:",
627+ endLine.text.length,
628+ );
629+ return false;
630+ }
631+
632+ return true;
633+ }
634+
635+ /**
636+ * Calculate a position to the right of the cursor with the specified offset.
637+ */
638+ private getDecorationOffsetPosition(
639+ editor: vscode.TextEditor,
640+ position: vscode.Position,
641+ ): vscode.Position {
642+ // Create a position that's offset spaces to the right of the cursor.
643+
644+ const line = editor.document.lineAt(position.line);
645+ const offsetChar = Math.min(
646+ position.character + SVG_CONFIG.cursorOffset,
647+ line.text.length,
648+ );
649+ return new vscode.Position(position.line, offsetChar);
650+ }
651+
652+ /**
653+ * Render a tooltip with the given text at the specified position.
654+ */
655+ private async renderTooltip(
656+ editor: vscode.TextEditor,
657+ position: vscode.Position,
658+ text: string,
659+ ) {
660+ console.log("renderTooltip");
661+ // Capture document version to detect changes.
662+ const docVersion = editor.document.version;
663+
664+ // Create a new decoration with the text.
665+ const decoration = await this.createCodeRenderDecoration(text);
666+ if (!decoration) {
667+ console.error("Failed to create decoration for text:", text);
668+ return;
669+ }
670+
671+ // Check if document changed during async operation.
672+ if (editor.document.version !== docVersion) {
673+ console.log("Document changed during decoration creation, aborting");
674+ decoration.dispose();
675+ return;
676+ }
677+
678+ // Store the decoration and editor.
679+ await this.hideAllNextEditWindows();
680+ this.currentDecoration = decoration;
681+ this.activeEditor = editor;
682+
683+ // Calculate how far off to the right of the cursor the decoration should be.
684+ const decorationOffsetPosition = this.getDecorationOffsetPosition(
685+ editor,
686+ position,
687+ );
688+ const range = new vscode.Range(
689+ decorationOffsetPosition,
690+ decorationOffsetPosition,
691+ );
692+
693+ // Validate the range before applying.
694+ if (!this.isValidRange(editor, range)) {
695+ console.error("Invalid range detected, skipping decoration");
696+ return;
697+ }
698+
699+ // Apply the decoration at the calculated position.
700+ editor.setDecorations(this.currentDecoration, [
701+ {
702+ range: new vscode.Range(
703+ decorationOffsetPosition,
704+ decorationOffsetPosition,
705+ ),
706+ hoverMessage: [this.buildHideTooltipHoverMsg()],
707+ },
708+ ]);
709+ }
710+}
711+
712+export default async function setupNextEditWindowManager(
713+ context: vscode.ExtensionContext,
714+ textApplier?: TextApplier,
715+) {
716+ await NextEditWindowManager.getInstance().setupNextEditWindowManager(
717+ context,
718+ textApplier,
719+ );
720+}
modified extensions/vscode/src/apply/ApplyManager.ts +4 −4
@@ -42,7 +42,7 @@
4242
4343 const { activeTextEditor } = vscode.window;
4444 if (!activeTextEditor) {
45- vscode.window.showErrorMessage("No active editor to apply edits to");
45+ void vscode.window.showErrorMessage("No active editor to apply edits to");
4646 return;
4747 }
4848
@@ -116,14 +116,14 @@
116116 ) {
117117 const { config } = await this.configHandler.loadConfig();
118118 if (!config) {
119- vscode.window.showErrorMessage("Config not loaded");
119+ void vscode.window.showErrorMessage("Config not loaded");
120120 return;
121121 }
122122
123123 const llm =
124124 config.selectedModelByRole.apply ?? config.selectedModelByRole.chat;
125125 if (!llm) {
126- vscode.window.showErrorMessage(
126+ void vscode.window.showErrorMessage(
127127 `No model with roles "apply" or "chat" found in config.`,
128128 );
129129 return;
@@ -177,7 +177,7 @@
177177 ) {
178178 const { config } = await this.configHandler.loadConfig();
179179 if (!config) {
180- vscode.window.showErrorMessage("Config not loaded");
180+ void vscode.window.showErrorMessage("Config not loaded");
181181 return;
182182 }
183183
modified extensions/vscode/src/autocomplete/completionProvider.ts +63 −34
@@ -5,8 +5,8 @@
55 type AutocompleteOutcome,
66 } from "core/autocomplete/util/types";
77 import { ConfigHandler } from "core/config/ConfigHandler";
8-import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants";
9-import { NextEditProvider } from "core/nextEdit/NextEditProvider";
8+// import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants";
9+// import { NextEditProvider } from "core/nextEdit/NextEditProvider";
1010 import * as URI from "uri-js";
1111 import { v4 as uuidv4 } from "uuid";
1212 import * as vscode from "vscode";
@@ -15,6 +15,8 @@
1515 import { VsCodeIde } from "../VsCodeIde";
1616 import { VsCodeWebviewProtocol } from "../webviewProtocol";
1717
18+import { NextEditProvider } from "core/nextEdit/NextEditProvider";
19+import { NextEditWindowManager } from "../activation/NextEditWindowManager";
1820 import { getDefinitionsFromLsp } from "./lsp";
1921 import { RecentlyEditedTracker } from "./recentlyEdited";
2022 import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService";
@@ -54,9 +56,19 @@
5456 }
5557
5658 private completionProvider: CompletionProvider;
57- private nextEditProvider: NextEditProvider | undefined;
58- private recentlyVisitedRanges: RecentlyVisitedRangesService;
59- private recentlyEditedTracker: RecentlyEditedTracker;
59+ private nextEditProvider: NextEditProvider;
60+ public recentlyVisitedRanges: RecentlyVisitedRangesService;
61+ public recentlyEditedTracker: RecentlyEditedTracker;
62+
63+ private isNextEditActive: boolean = false;
64+
65+ public activateNextEdit() {
66+ this.isNextEditActive = true;
67+ }
68+
69+ public deactivateNextEdit() {
70+ this.isNextEditActive = false;
71+ }
6072
6173 constructor(
6274 private readonly configHandler: ConfigHandler,
@@ -79,16 +91,16 @@
7991 this.onError.bind(this),
8092 getDefinitionsFromLsp,
8193 );
82- // NOTE: Only turn it on locally when testing (for review purposes).
83- if (IS_NEXT_EDIT_ACTIVE) {
84- this.nextEditProvider = new NextEditProvider(
85- this.configHandler,
86- this.ide,
87- getAutocompleteModel,
88- this.onError.bind(this),
89- getDefinitionsFromLsp,
90- );
91- }
94+
95+ this.nextEditProvider = NextEditProvider.initialize(
96+ this.configHandler,
97+ this.ide,
98+ getAutocompleteModel,
99+ this.onError.bind(this),
100+ getDefinitionsFromLsp,
101+ "fineTuned",
102+ );
103+
92104 this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide);
93105 }
94106
@@ -148,6 +160,10 @@
148160 line: position.line,
149161 character: position.character,
150162 };
163+ // const pos = {
164+ // line: 0,
165+ // character: 0,
166+ // };
151167 let manuallyPassFileContents: string | undefined = undefined;
152168 if (document.uri.scheme === "vscode-notebook-cell") {
153169 const notebook = vscode.workspace.notebookDocuments.find((notebook) =>
@@ -208,29 +224,20 @@
208224 };
209225
210226 setupStatusBar(undefined, true);
211- const outcome =
212- await this.completionProvider.provideInlineCompletionItems(
213- input,
214- signal,
215- wasManuallyTriggered,
216- );
217-
218- if (!outcome || !outcome.completion) {
219- return null;
220- }
221227
222- // NOTE: This is a very rudimentary check to see if we can call the next edit service.
223- // In the future we will have to figure out how to call this more gracefully.
224- if (this.nextEditProvider) {
225- const nextEditOutcome =
226- await this.nextEditProvider?.provideInlineCompletionItems(
228+ const outcome = this.isNextEditActive
229+ ? await this.nextEditProvider.provideInlineCompletionItems(
230+ input,
231+ signal,
232+ )
233+ : await this.completionProvider.provideInlineCompletionItems(
227234 input,
228235 signal,
236+ wasManuallyTriggered,
229237 );
230238
231- if (nextEditOutcome && nextEditOutcome.completion) {
232- outcome.completion = nextEditOutcome.completion;
233- }
239+ if (!outcome || !outcome.completion) {
240+ return null;
234241 }
235242
236243 // VS Code displays dependent on selectedCompletionInfo (their docstring below)
@@ -265,7 +272,10 @@
265272
266273 // Construct the range/text to show
267274 const startPos = selectedCompletionInfo?.range.start ?? position;
275+ // const startPos = new vscode.Position(0, 0);
276+ // const endPos = new vscode.Position(0, 5);
268277 let range = new vscode.Range(startPos, startPos);
278+ // let range = new vscode.Range(startPos, endPos);
269279 let completionText = outcome.completion;
270280 const isSingleLineCompletion = outcome.completion.split("\n").length <= 1;
271281
@@ -292,14 +302,20 @@
292302 new vscode.Position(startPos.line, result.range.end),
293303 );
294304 }
305+ // console.log("range", range.start, range.end);
295306 } else {
296307 // Extend the range to the end of the line for multiline completions
297308 range = new vscode.Range(startPos, document.lineAt(startPos).range.end);
309+ // console.log("range", range.start, range.end);
298310 }
299311
300312 const completionItem = new vscode.InlineCompletionItem(
301313 completionText,
302314 range,
315+ // new vscode.Range(
316+ // new vscode.Position(36, 3),
317+ // new vscode.Position(36, 3),
318+ // ),
303319 {
304320 title: "Log Autocomplete Outcome",
305321 command: "continue.logAutocompleteOutcome",
@@ -308,7 +324,20 @@
308324 );
309325
310326 (completionItem as any).completeBracketPairs = true;
311- return [completionItem];
327+
328+ if (this.isNextEditActive) {
329+ const editor = vscode.window.activeTextEditor;
330+ if (editor && NextEditWindowManager.isInstantiated()) {
331+ await NextEditWindowManager.getInstance().showNextEditWindow(
332+ editor,
333+ completionText,
334+ );
335+ }
336+
337+ return undefined;
338+ } else {
339+ return [completionItem];
340+ }
312341 } finally {
313342 stopStatusBarLoading();
314343 }
modified extensions/vscode/src/commands.ts +12 −0
@@ -779,6 +779,18 @@
779779 );
780780 }
781781 },
782+ "continue.forceNextEdit": async () => {
783+ captureCommandTelemetry("forceNextEdit");
784+
785+ // This is basically the same logic as forceAutocomplete.
786+ // I'm writing a new command KV pair here in case we diverge in features.
787+
788+ await vscode.commands.executeCommand("editor.action.inlineSuggest.hide");
789+
790+ await vscode.commands.executeCommand(
791+ "editor.action.inlineSuggest.trigger",
792+ );
793+ },
782794 };
783795 };
784796
modified extensions/vscode/src/diff/processDiff.ts +14 −0
@@ -1,5 +1,7 @@
11 import { Core } from "core/core";
2+import { DataLogger } from "core/data/log";
23 import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
4+import { editOutcomeTracker } from "../extension/EditOutcomeTracker";
35 import { VsCodeIde } from "../VsCodeIde";
46 import { VerticalDiffManager } from "./vertical/manager";
57
@@ -27,6 +29,11 @@
2729
2830 await ide.openFile(newOrCurrentUri);
2931
32+ // If streamId is not provided, try to get it from the VerticalDiffManager
33+ if (!streamId) {
34+ streamId = verticalDiffManager.getStreamIdForFile(newOrCurrentUri);
35+ }
36+
3037 // Clear vertical diffs depending on action
3138 verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
3239 if (action === "reject") {
@@ -37,6 +44,13 @@
3744 if (streamId) {
3845 const fileContent = await ide.readFile(newOrCurrentUri);
3946
47+ // Record the edit outcome before updating the apply state
48+ await editOutcomeTracker.recordEditOutcome(
49+ streamId,
50+ action === "accept",
51+ DataLogger.getInstance(),
52+ );
53+
4054 await sidebar.webviewProtocol.request("updateApplyState", {
4155 fileContent,
4256 filepath: newOrCurrentUri,
modified extensions/vscode/src/diff/vertical/handler.ts +8 −17
@@ -9,8 +9,8 @@
99 indexDecorationType,
1010 } from "./decorations";
1111
12-import type { VerticalDiffCodeLens } from "./manager";
1312 import type { ApplyState, DiffLine } from "core";
13+import type { VerticalDiffCodeLens } from "./manager";
1414
1515 export interface VerticalDiffHandlerOptions {
1616 input?: string;
@@ -20,10 +20,12 @@
2020 numDiffs?: ApplyState["numDiffs"],
2121 fileContent?: ApplyState["fileContent"],
2222 ) => void;
23+ streamId?: string;
2324 }
2425
2526 export class VerticalDiffHandler implements vscode.Disposable {
2627 public insertedInCurrentBlock = 0;
28+ public streamId?: string;
2729 disposables: vscode.Disposable[] = [];
2830 private currentLineIndex: number;
2931 private cancelled = false;
@@ -50,6 +52,7 @@
5052 public options: VerticalDiffHandlerOptions,
5153 ) {
5254 this.currentLineIndex = startLine;
55+ this.streamId = options.streamId;
5356
5457 this.removedLineDecorations = new RemovedLineDecorationManager(this.editor);
5558 this.addedLineDecorations = new AddedLineDecorationManager(this.editor);
@@ -330,10 +333,7 @@
330333 // Then, we insert our diff lines
331334 await this.editor.edit((editBuilder) => {
332335 editBuilder.replace(this.range, replaceContent),
333- {
334- undoStopAfter: false,
335- undoStopBefore: false,
336- };
336+ { undoStopAfter: false, undoStopBefore: false };
337337 });
338338
339339 // Lastly, we apply decorations
@@ -446,10 +446,7 @@
446446 editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
447447 }
448448 },
449- {
450- undoStopAfter: false,
451- undoStopBefore: false,
452- },
449+ { undoStopAfter: false, undoStopBefore: false },
453450 );
454451 }
455452
@@ -467,10 +464,7 @@
467464 new vscode.Range(startLine, startLine.translate(numLines)),
468465 );
469466 },
470- {
471- undoStopAfter: false,
472- undoStopBefore: false,
473- },
467+ { undoStopAfter: false, undoStopBefore: false },
474468 );
475469 }
476470
@@ -486,10 +480,7 @@
486480 );
487481 }
488482 },
489- {
490- undoStopAfter: false,
491- undoStopBefore: false,
492- },
483+ { undoStopAfter: false, undoStopBefore: false },
493484 );
494485 }
495486
modified extensions/vscode/src/diff/vertical/manager.ts +63 −7
@@ -1,4 +1,4 @@
1-import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
1+import { ChatMessage, DiffLine, IDE, ILLM, RuleWithSource } from "core";
22 import { streamDiffLines } from "core/edit/streamDiffLines";
33 import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
44 import { getMarkdownLanguageTagForFile } from "core/util";
@@ -11,6 +11,9 @@
1111 import { VsCodeWebviewProtocol } from "../../webviewProtocol";
1212
1313 import { ApplyAbortManager } from "core/edit/applyAbortManager";
14+import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
15+import { stripImages } from "core/util/messageContent";
16+import { editOutcomeTracker } from "../../extension/EditOutcomeTracker";
1417 import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
1518
1619 export interface VerticalDiffCodeLens {
@@ -23,7 +26,6 @@
2326 public refreshCodeLens: () => void = () => {};
2427
2528 private fileUriToHandler: Map<string, VerticalDiffHandler> = new Map();
26-
2729 fileUriToCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
2830
2931 private userChangeListener: vscode.Disposable | undefined;
@@ -33,6 +35,7 @@
3335 constructor(
3436 private readonly webviewProtocol: VsCodeWebviewProtocol,
3537 private readonly editDecorationManager: EditDecorationManager,
38+ private readonly ide: IDE,
3639 ) {
3740 this.userChangeListener = undefined;
3841 }
@@ -69,6 +72,10 @@
6972 return this.fileUriToHandler.get(fileUri);
7073 }
7174
75+ getStreamIdForFile(fileUri: string): string | undefined {
76+ return this.fileUriToHandler.get(fileUri)?.streamId;
77+ }
78+
7279 // Creates a listener for document changes by user.
7380 private enableDocumentChangeListener(): vscode.Disposable | undefined {
7481 if (this.userChangeListener) {
@@ -229,6 +236,7 @@
229236 filepath: fileUri,
230237 toolCallId,
231238 }),
239+ streamId,
232240 },
233241 );
234242
@@ -296,7 +304,11 @@
296304 toolCallId?: string;
297305 rulesToInclude: undefined | RuleWithSource[];
298306 }): Promise<string | undefined> {
299- vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
307+ void vscode.commands.executeCommand(
308+ "setContext",
309+ "continue.diffVisible",
310+ true,
311+ );
300312
301313 let editor = vscode.window.activeTextEditor;
302314
@@ -373,6 +385,7 @@
373385 filepath: fileUri,
374386 toolCallId,
375387 }),
388+ streamId,
376389 },
377390 );
378391
@@ -430,7 +443,7 @@
430443 );
431444 }
432445
433- vscode.commands.executeCommand(
446+ void vscode.commands.executeCommand(
434447 "setContext",
435448 "continue.streamingDiff",
436449 true,
@@ -472,10 +485,18 @@
472485 this.enableDocumentChangeListener();
473486
474487 if (abortController.signal.aborted) {
475- vscode.commands.executeCommand("continue.rejectDiff");
488+ void vscode.commands.executeCommand("continue.rejectDiff");
476489 }
477490
478- return `${prefix}${streamedLines.join("\n")}${suffix}`;
491+ const fileAfterEdit = `${prefix}${streamedLines.join("\n")}${suffix}`;
492+ await this.trackEditInteraction({
493+ model: llm,
494+ filepath: fileUri,
495+ prompt: input,
496+ fileAfterEdit,
497+ });
498+
499+ return fileAfterEdit;
479500 } catch (e) {
480501 this.disableDocumentChangeListener();
481502 const handled = await handleLLMError(e);
@@ -487,11 +508,46 @@
487508 throw new Error(message);
488509 }
489510 } finally {
490- vscode.commands.executeCommand(
511+ void vscode.commands.executeCommand(
491512 "setContext",
492513 "continue.streamingDiff",
493514 false,
494515 );
495516 }
496517 }
518+
519+ async trackEditInteraction({
520+ model,
521+ filepath,
522+ prompt,
523+ fileAfterEdit,
524+ }: {
525+ model: ILLM;
526+ filepath: string;
527+ prompt: string;
528+ fileAfterEdit: string | undefined;
529+ }) {
530+ // Get previous code content for outcome tracking
531+ const previousCode = await this.ide.readFile(filepath);
532+ const newCode = fileAfterEdit ?? "";
533+ const previousCodeLines = previousCode.split("\n").length;
534+ const newCodeLines = newCode.split("\n").length;
535+ const lineChange = newCodeLines - previousCodeLines;
536+
537+ // Store pending edit data for outcome tracking
538+ editOutcomeTracker.trackEditInteraction({
539+ streamId: EDIT_MODE_STREAM_ID,
540+ timestamp: new Date().toISOString(),
541+ modelProvider: model.underlyingProviderName,
542+ modelTitle: model.title ?? "",
543+ prompt: stripImages(prompt),
544+ completion: newCode,
545+ previousCode,
546+ newCode,
547+ filepath: filepath,
548+ previousCodeLines,
549+ newCodeLines,
550+ lineChange,
551+ });
552+ }
497553 }
added extensions/vscode/src/extension/EditOutcomeTracker.ts +96 −0
@@ -0,0 +1,96 @@
1+/**
2+ * Tracks pending edit interactions until they are accepted or rejected,
3+ * then emits editOutcome events with the final result.
4+ */
5+export interface PendingEditData {
6+ streamId: string;
7+ timestamp: string;
8+ modelProvider: string;
9+ modelTitle: string;
10+ prompt: string;
11+ completion: string;
12+ previousCode: string;
13+ newCode: string;
14+ filepath: string;
15+ previousCodeLines: number;
16+ newCodeLines: number;
17+ lineChange: number;
18+}
19+
20+class EditOutcomeTracker {
21+ private static instance: EditOutcomeTracker;
22+ private pendingEdits: Map<string, PendingEditData> = new Map();
23+
24+ private constructor() {}
25+
26+ public static getInstance(): EditOutcomeTracker {
27+ if (!EditOutcomeTracker.instance) {
28+ EditOutcomeTracker.instance = new EditOutcomeTracker();
29+ }
30+ return EditOutcomeTracker.instance;
31+ }
32+
33+ /**
34+ * Store a pending edit interaction for later outcome tracking
35+ */
36+ public trackEditInteraction(data: PendingEditData): void {
37+ this.pendingEdits.set(data.streamId, data);
38+ }
39+
40+ /**
41+ * Record the outcome of an edit interaction and emit the editOutcome event
42+ */
43+ public async recordEditOutcome(
44+ streamId: string,
45+ accepted: boolean,
46+ dataLogger: any,
47+ ): Promise<void> {
48+ const pendingEdit = this.pendingEdits.get(streamId);
49+ if (!pendingEdit) {
50+ console.warn(`No pending edit found for streamId: ${streamId}`);
51+ return;
52+ }
53+
54+ // Emit the editOutcome event
55+ await dataLogger.logDevData({
56+ name: "editOutcome",
57+ data: {
58+ modelProvider: pendingEdit.modelProvider,
59+ modelTitle: pendingEdit.modelTitle,
60+ prompt: pendingEdit.prompt,
61+ completion: pendingEdit.completion,
62+ previousCode: pendingEdit.previousCode,
63+ newCode: pendingEdit.newCode,
64+ previousCodeLines: pendingEdit.previousCodeLines,
65+ newCodeLines: pendingEdit.newCodeLines,
66+ lineChange: pendingEdit.lineChange,
67+ accepted,
68+ },
69+ });
70+
71+ // Clean up the pending edit
72+ this.pendingEdits.delete(streamId);
73+ }
74+
75+ /**
76+ * Clean up pending edits that might have been abandoned
77+ */
78+ public cleanupOldPendingEdits(maxAgeMs: number = 30 * 60 * 1000): void {
79+ const now = Date.now();
80+ for (const [streamId, edit] of this.pendingEdits.entries()) {
81+ const editTime = new Date(edit.timestamp).getTime();
82+ if (now - editTime > maxAgeMs) {
83+ this.pendingEdits.delete(streamId);
84+ }
85+ }
86+ }
87+
88+ /**
89+ * Get count of pending edits (for debugging/monitoring)
90+ */
91+ public getPendingEditCount(): number {
92+ return this.pendingEdits.size;
93+ }
94+}
95+
96+export const editOutcomeTracker = EditOutcomeTracker.getInstance();
modified extensions/vscode/src/extension/VsCodeExtension.ts +56 −14
@@ -36,12 +36,17 @@
3636 } from "../stubs/WorkOsAuthProvider";
3737 import { Battery } from "../util/battery";
3838 import { FileSearch } from "../util/FileSearch";
39+import { VsCodeIdeUtils } from "../util/ideUtils";
3940 import { VsCodeIde } from "../VsCodeIde";
4041
4142 import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
4243 import { VsCodeMessenger } from "./VsCodeMessenger";
4344
44-import { VsCodeIdeUtils } from "../util/ideUtils";
45+import setupNextEditWindowManager, {
46+ NextEditWindowManager,
47+} from "../activation/NextEditWindowManager";
48+import { getDefinitionsFromLsp } from "../autocomplete/lsp";
49+import { handleTextDocumentChange } from "../util/editLoggingUtils";
4550 import type { VsCodeWebviewProtocol } from "../webviewProtocol";
4651
4752 export class VsCodeExtension {
@@ -62,11 +67,12 @@
6267 private workOsAuthProvider: WorkOsAuthProvider;
6368 private fileSearch: FileSearch;
6469 private uriHandler = new UriEventHandler();
70+ private completionProvider: ContinueCompletionProvider;
6571
6672 constructor(context: vscode.ExtensionContext) {
6773 // Register auth provider
6874 this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
69- this.workOsAuthProvider.refreshSessions();
75+ void this.workOsAuthProvider.refreshSessions();
7076 context.subscriptions.push(this.workOsAuthProvider);
7177
7278 this.editDecorationManager = new EditDecorationManager(context);
@@ -124,25 +130,28 @@
124130 configHandlerPromise,
125131 this.workOsAuthProvider,
126132 this.editDecorationManager,
133+ context,
134+ this,
127135 );
128136
129137 this.core = new Core(inProcessMessenger, this.ide);
130138 this.configHandler = this.core.configHandler;
131139 resolveConfigHandler?.(this.configHandler);
132140
133- this.configHandler.loadConfig();
141+ void this.configHandler.loadConfig();
134142
135143 this.verticalDiffManager = new VerticalDiffManager(
136144 this.sidebar.webviewProtocol,
137145 this.editDecorationManager,
146+ this.ide,
138147 );
139148 resolveVerticalDiffManager?.(this.verticalDiffManager);
140149
141- setupRemoteConfigSync(
150+ void setupRemoteConfigSync(
142151 this.configHandler.reloadConfig.bind(this.configHandler),
143152 );
144153
145- this.configHandler.loadConfig().then(({ config }) => {
154+ void this.configHandler.loadConfig().then(({ config }) => {
146155 const { verticalDiffCodeLens } = registerAllCodeLensProviders(
147156 context,
148157 this.verticalDiffManager.fileUriToCodeLens,
@@ -155,6 +164,18 @@
155164
156165 this.configHandler.onConfigUpdate(
157166 async ({ config: newConfig, configLoadInterrupted }) => {
167+ if (newConfig?.experimental?.optInNextEditFeature) {
168+ // Set up next edit window manager only for Continue team members
169+ await setupNextEditWindowManager(context);
170+
171+ this.activateNextEdit();
172+ await NextEditWindowManager.freeTabAndEsc();
173+ } else {
174+ NextEditWindowManager.clearInstance();
175+ this.deactivateNextEdit();
176+ await NextEditWindowManager.freeTabAndEsc();
177+ }
178+
158179 if (configLoadInterrupted) {
159180 // Show error in status bar
160181 setupStatusBar(undefined, undefined, true);
@@ -178,14 +199,15 @@
178199 setupStatusBar(
179200 enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
180201 );
202+ this.completionProvider = new ContinueCompletionProvider(
203+ this.configHandler,
204+ this.ide,
205+ this.sidebar.webviewProtocol,
206+ );
181207 context.subscriptions.push(
182208 vscode.languages.registerInlineCompletionItemProvider(
183209 [{ pattern: "**" }],
184- new ContinueCompletionProvider(
185- this.configHandler,
186- this.ide,
187- this.sidebar.webviewProtocol,
188- ),
210+ this.completionProvider,
189211 ),
190212 );
191213
@@ -280,7 +302,19 @@
280302 if (stats.size === 0) {
281303 return;
282304 }
283- this.configHandler.reloadConfig();
305+ void this.configHandler.reloadConfig();
306+ });
307+
308+ vscode.workspace.onDidChangeTextDocument(async (event) => {
309+ const editInfo = await handleTextDocumentChange(
310+ event,
311+ this.configHandler,
312+ this.ide,
313+ this.completionProvider,
314+ getDefinitionsFromLsp,
315+ );
316+
317+ if (editInfo) this.core.invoke("files/smallEdit", editInfo);
284318 });
285319
286320 vscode.workspace.onDidSaveTextDocument(async (event) => {
@@ -311,7 +345,7 @@
311345 vscode.authentication.onDidChangeSessions(async (e) => {
312346 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
313347 if (e.provider.id === env.AUTH_TYPE) {
314- vscode.commands.executeCommand(
348+ void vscode.commands.executeCommand(
315349 "setContext",
316350 "continue.isSignedInToControlPlane",
317351 true,
@@ -322,7 +356,7 @@
322356 sessionInfo,
323357 });
324358 } else {
325- vscode.commands.executeCommand(
359+ void vscode.commands.executeCommand(
326360 "setContext",
327361 "continue.isSignedInToControlPlane",
328362 false,
@@ -335,7 +369,7 @@
335369 });
336370
337371 // Refresh index when branch is changed
338- this.ide.getWorkspaceDirs().then((dirs) =>
372+ void this.ide.getWorkspaceDirs().then((dirs) =>
339373 dirs.forEach(async (dir) => {
340374 const repo = await this.ide.getRepo(dir);
341375 if (repo) {
@@ -410,4 +444,12 @@
410444 registerCustomContextProvider(contextProvider: IContextProvider) {
411445 this.configHandler.registerCustomContextProvider(contextProvider);
412446 }
447+
448+ public activateNextEdit() {
449+ this.completionProvider.activateNextEdit();
450+ }
451+
452+ public deactivateNextEdit() {
453+ this.completionProvider.deactivateNextEdit();
454+ }
413455 }
modified extensions/vscode/src/extension/VsCodeMessenger.ts +3 −0
@@ -30,6 +30,7 @@
3030 import { getExtensionUri } from "../util/vscode";
3131 import { VsCodeIde } from "../VsCodeIde";
3232 import { VsCodeWebviewProtocol } from "../webviewProtocol";
33+import { VsCodeExtension } from "./VsCodeExtension";
3334
3435 type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
3536 ToWebviewFromCoreProtocol;
@@ -82,6 +83,8 @@
8283 private readonly configHandlerPromise: Promise<ConfigHandler>,
8384 private readonly workOsAuthProvider: WorkOsAuthProvider,
8485 private readonly editDecorationManager: EditDecorationManager,
86+ private readonly context: vscode.ExtensionContext,
87+ private readonly vsCodeExtension: VsCodeExtension,
8588 ) {
8689 /** WEBVIEW ONLY LISTENERS **/
8790 this.onWebview("showFile", (msg) => {
added extensions/vscode/src/util/editLoggingUtils.ts +91 −0
@@ -0,0 +1,91 @@
1+import { IDE, Position, Range, RangeInFileWithNextEditInfo } from "core";
2+import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types";
3+import { GetLspDefinitionsFunction } from "core/autocomplete/types";
4+import { ConfigHandler } from "core/config/ConfigHandler";
5+import { RecentlyEditedRange } from "core/nextEdit/types";
6+import * as vscode from "vscode";
7+import { ContinueCompletionProvider } from "../autocomplete/completionProvider";
8+
9+export const getBeforeCursorPos = (range: Range, activePos: Position) => {
10+ // whichever side of the range isn't active is the before position
11+ if (
12+ range.start.line === activePos.line &&
13+ range.start.character === activePos.character
14+ ) {
15+ return range.end as Position;
16+ } else {
17+ return range.start as Position;
18+ }
19+};
20+
21+const getWorkspaceDirInfo = async (
22+ event: vscode.TextDocumentChangeEvent,
23+ ide: IDE,
24+) => {
25+ // gets the workspace dir uri and checks if it's the open-source continue repo
26+ const workspaceFolder = vscode.workspace.getWorkspaceFolder(
27+ event.document.uri,
28+ );
29+ if (!workspaceFolder) {
30+ return false;
31+ }
32+ const workspaceDirUri = workspaceFolder.uri.toString();
33+ const repoName = await ide.getRepoName(workspaceDirUri);
34+ return {
35+ workspaceDirUri: workspaceDirUri,
36+ isContinueRepo: repoName === "continuedev/continue",
37+ };
38+};
39+
40+export const handleTextDocumentChange = async (
41+ event: vscode.TextDocumentChangeEvent,
42+ configHandler: ConfigHandler,
43+ ide: IDE,
44+ completionProvider: ContinueCompletionProvider,
45+ getDefinitionsFromLsp: GetLspDefinitionsFunction,
46+) => {
47+ const changes = event.contentChanges;
48+ const editor = vscode.window.activeTextEditor;
49+ const { config } = await configHandler.loadConfig();
50+
51+ if (!config?.experimental?.logEditingData) return;
52+ if (!editor) return;
53+ if (event.contentChanges.length === 0) return;
54+
55+ // Ensure that loggin will only happen in the open-source continue repo
56+ const workspaceDirInfo = await getWorkspaceDirInfo(event, ide);
57+ if (!workspaceDirInfo) return;
58+ // if (!workspaceDirInfo.isContinueRepo) return;
59+
60+ const activeCursorPos = editor.selection.active;
61+ const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({
62+ filepath: event.document.uri.toString(),
63+ range: {
64+ start: change.range.start as Position,
65+ end: change.range.end as Position,
66+ },
67+ fileContents: event.document.getText(),
68+ editText: change.text,
69+ beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos),
70+ afterCursorPos: activeCursorPos as Position,
71+ workspaceDir: workspaceDirInfo.workspaceDirUri,
72+ }));
73+
74+ let recentlyEditedRanges: RecentlyEditedRange[] = [];
75+ let recentlyVisitedRanges: AutocompleteCodeSnippet[] = [];
76+
77+ if (completionProvider) {
78+ recentlyEditedRanges =
79+ await completionProvider.recentlyEditedTracker.getRecentlyEditedRanges();
80+ recentlyVisitedRanges =
81+ completionProvider.recentlyVisitedRanges.getSnippets();
82+ }
83+
84+ return {
85+ actions: editActions,
86+ configHandler: configHandler,
87+ getDefsFromLspFunction: getDefinitionsFromLsp,
88+ recentlyEditedRanges,
89+ recentlyVisitedRanges,
90+ };
91+};
modified extensions/vscode/src/util/getTheme.ts +8 −0
@@ -45,6 +45,14 @@
4545 return JSON.parse(themeString ?? "{}");
4646 }
4747
48+export function getThemeString(): string {
49+ const workbenchConfig = vscode.workspace.getConfiguration();
50+ const themeString =
51+ workbenchConfig.get<string>("workbench.colorTheme") ??
52+ "Default Dark Modern";
53+ return themeString;
54+}
55+
4856 export function getTheme() {
4957 let currentTheme: string | undefined = undefined;
5058 // Get color theme from settings
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 gui/package.json +0 −1
@@ -46,7 +46,6 @@
4646 "minisearch": "^7.0.2",
4747 "mustache": "^4.2.0",
4848 "posthog-js": "^1.130.1",
49- "prismjs": "^1.29.0",
5049 "react": "^18.2.0",
5150 "react-dom": "^18.2.0",
5251 "react-error-boundary": "^4.0.11",
modified gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +1 −0
@@ -37,6 +37,7 @@
3737 contextRequests.push({
3838 provider:
3939 attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!,
40+ query: attrs.query,
4041 });
4142 return child.attrs?.renderInlineAs ?? child.attrs?.label;
4243
added gui/src/pages/config/ContinueFeaturesMenu.tsx +48 −0
@@ -0,0 +1,48 @@
1+import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
2+import ToggleSwitch from "../../components/gui/Switch";
3+import { ToolTip } from "../../components/gui/Tooltip";
4+interface ContinueFeaturesMenuProps {
5+ logEditingData: boolean;
6+ handleLogEditingDataToggle: (value: boolean) => void;
7+ optInNextEditFeature: boolean;
8+ handleOptInNextEditToggle: (value: boolean) => void;
9+}
10+
11+export function ContinueFeaturesMenu({
12+ logEditingData,
13+ handleLogEditingDataToggle,
14+ optInNextEditFeature,
15+ handleOptInNextEditToggle,
16+}: ContinueFeaturesMenuProps) {
17+ return (
18+ <div className="flex w-full flex-col gap-y-4">
19+ <div className="my-2 text-center text-xs font-medium text-slate-400">
20+ 🚧 INTERNAL SETTINGS 🚧
21+ </div>
22+ <div className="flex w-full flex-col gap-y-4">
23+ <ToggleSwitch
24+ isToggled={logEditingData}
25+ onToggle={() => handleLogEditingDataToggle(!logEditingData)}
26+ text="Log Editing Data"
27+ showIfToggled={
28+ <>
29+ <ExclamationTriangleIcon
30+ data-tooltip-id={`auto-accept-diffs-warning-tooltip`}
31+ className="h-3 w-3 text-yellow-500"
32+ />
33+ <ToolTip id={`auto-accept-diffs-warning-tooltip`}>
34+ {`Only turn this on if you want to log your editing processes in addition to the normal dev data. Note that this will store a lot of data.`}
35+ </ToolTip>
36+ </>
37+ }
38+ />
39+
40+ <ToggleSwitch
41+ isToggled={optInNextEditFeature}
42+ onToggle={() => handleOptInNextEditToggle(!optInNextEditFeature)}
43+ text="Enable Next Edit Over Autocomplete"
44+ />
45+ </div>
46+ </div>
47+ );
48+}
modified gui/src/pages/config/UserSettingsForm.tsx +32 −1
@@ -8,6 +8,7 @@
88 SharedConfigSchema,
99 modifyAnyConfigWithSharedConfig,
1010 } from "core/config/sharedConfig";
11+import { HubSessionInfo } from "core/control-plane/AuthTypes";
1112 import { useContext, useEffect, useState } from "react";
1213 import { Input } from "../../components";
1314 import NumberInput from "../../components/gui/NumberInput";
@@ -15,10 +16,12 @@
1516 import ToggleSwitch from "../../components/gui/Switch";
1617 import { ToolTip } from "../../components/gui/Tooltip";
1718 import { useFontSize } from "../../components/ui/font";
19+import { useAuth } from "../../context/Auth";
1820 import { IdeMessengerContext } from "../../context/IdeMessenger";
1921 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
2022 import { updateConfig } from "../../redux/slices/configSlice";
2123 import { setLocalStorage } from "../../util/localStorage";
24+import { ContinueFeaturesMenu } from "./ContinueFeaturesMenu";
2225
2326 export function UserSettingsForm() {
2427 /////// User settings section //////
@@ -26,6 +29,7 @@
2629 const ideMessenger = useContext(IdeMessengerContext);
2730 const config = useAppSelector((state) => state.config.config);
2831 const [showExperimental, setShowExperimental] = useState(false);
32+ const { session } = useAuth();
2933
3034 function handleUpdate(sharedConfig: SharedConfigSchema) {
3135 // Optimistic update
@@ -63,6 +67,14 @@
6367 });
6468 };
6569
70+ const handleLogEditingDataToggle = (value: boolean) => {
71+ handleUpdate({ logEditingData: value });
72+ };
73+
74+ const handleOptInNextEditToggle = (value: boolean) => {
75+ handleUpdate({ optInNextEditFeature: value });
76+ };
77+
6678 useEffect(() => {
6779 // Necessary so that reformatted/trimmed values don't cause dirty state
6880 setFormPromptPath(promptPath);
@@ -74,12 +86,16 @@
7486 const showChatScrollbar = config.ui?.showChatScrollbar ?? false;
7587 const readResponseTTS = config.experimental?.readResponseTTS ?? false;
7688 const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false;
89+ const logEditingData = config.experimental?.logEditingData ?? false;
7790 const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false;
7891 const disableSessionTitles = config.disableSessionTitles ?? false;
7992 const useCurrentFileAsContext =
8093 config.experimental?.useCurrentFileAsContext ?? false;
8194 const enableExperimentalTools =
8295 config.experimental?.enableExperimentalTools ?? false;
96+ const optInNextEditFeature =
97+ config.experimental?.optInNextEditFeature ?? false;
98+
8399 const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
84100 const disableIndexing = config.disableIndexing ?? false;
85101
@@ -114,6 +130,10 @@
114130 });
115131 }, [ideMessenger]);
116132
133+ const hasContinueEmail = (session as HubSessionInfo)?.account?.id.includes(
134+ "@continue.dev",
135+ );
136+
117137 return (
118138 <div className="flex flex-col">
119139 {/* {selectedProfile && isLocalProfile(selectedProfile) ? (
@@ -355,7 +375,9 @@
355375 </div>
356376 <div
357377 className={`duration-400 overflow-hidden transition-all ease-in-out ${
358- showExperimental ? "max-h-40" : "max-h-0"
378+ showExperimental
379+ ? "max-h-96" /* Increased from max-h-40 to max-h-96 to accommodate ContinueFeaturesMenu */
380+ : "max-h-0"
359381 }`}
360382 >
361383 <div className="flex flex-col gap-x-1 gap-y-4 pl-6">
@@ -399,6 +421,15 @@
399421 }
400422 text="Enable experimental tools"
401423 />
424+
425+ {hasContinueEmail && (
426+ <ContinueFeaturesMenu
427+ logEditingData={logEditingData}
428+ handleLogEditingDataToggle={handleLogEditingDataToggle}
429+ optInNextEditFeature={optInNextEditFeature}
430+ handleOptInNextEditToggle={handleOptInNextEditToggle}
431+ />
432+ )}
402433 </div>
403434 </div>
404435 </div>
modified gui/src/redux/slices/sessionSlice.ts +2 −0
@@ -28,6 +28,8 @@
2828 import { streamResponseThunk } from "../thunks/streamResponse";
2929 import { findCurrentToolCall, findToolCall } from "../util";
3030
31+const getIdeMessenger = () => (window as any).ideMessenger;
32+
3133 // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
3234 // The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
3335 export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
modified gui/src/redux/thunks/callCurrentTool.ts +5 −0
@@ -12,6 +12,7 @@
1212 updateToolCallOutput,
1313 } from "../slices/sessionSlice";
1414 import { ThunkApiType } from "../store";
15+import { logToolUsage } from "../util";
1516 import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
1617
1718 export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
@@ -100,6 +101,8 @@
100101 ],
101102 }),
102103 );
104+
105+ logToolUsage(toolCallState, false, extra.ideMessenger, output);
103106 } else if (output?.length) {
104107 dispatch(
105108 updateToolCallOutput({
@@ -107,6 +110,8 @@
107110 contextItems: output,
108111 }),
109112 );
113+
114+ logToolUsage(toolCallState, true, extra.ideMessenger, output);
110115 }
111116
112117 // Because we don't have access to use hooks, we check `allowAnonymousTelemetry`
modified gui/src/redux/util/index.ts +23 −1
@@ -1,4 +1,6 @@
1-import { ToolCallState } from "core";
1+import { ContextItem, ToolCallState } from "core";
2+import { safeParseToolCallArgs } from "core/tools/parseArgs";
3+import { IIdeMessenger } from "../../context/IdeMessenger";
24 import { RootState } from "../store";
35
46 export function findCurrentToolCall(
@@ -15,3 +17,23 @@
1517 (item) => item.toolCallState?.toolCallId === toolCallId,
1618 )?.toolCallState;
1719 }
20+
21+export function logToolUsage(
22+ toolCallState: ToolCallState,
23+ success: boolean,
24+ messenger: IIdeMessenger,
25+ finalOutput?: ContextItem[],
26+) {
27+ messenger.post("devdata/log", {
28+ name: "toolUsage",
29+ data: {
30+ toolCallId: toolCallState.toolCallId,
31+ functionName: toolCallState.toolCall?.function?.name,
32+ functionArgs: toolCallState.toolCall?.function?.arguments,
33+ toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall),
34+ parsedArgs: toolCallState.parsedArgs,
35+ output: finalOutput || toolCallState.output || [],
36+ succeeded: success,
37+ },
38+ });
39+}
added manual-testing-sandbox/next-edit/next-edit-1-1-sol.ts +81 −0
@@ -0,0 +1,81 @@
1+// A clean implementation of the price calculation utility
2+// Solution for: next-edit-1-1.ts
3+
4+/**
5+ * Interface for a purchasable item
6+ */
7+interface PricedItem {
8+ name: string;
9+ price: number;
10+}
11+
12+/**
13+ * Calculates the total price of items with an optional discount
14+ *
15+ * @param items - Array of priced items
16+ * @param discountPercentage - Optional discount to apply (percentage)
17+ * @returns The final price after discount
18+ */
19+function calculateTotalPrice(
20+ items: PricedItem[],
21+ discountPercentage = 0,
22+): number {
23+ // Calculate total price
24+ const subtotal = items.reduce((total, item) => total + item.price, 0);
25+
26+ // Apply discount
27+ const discount = (subtotal * discountPercentage) / 100;
28+ const finalPrice = subtotal - discount;
29+
30+ return finalPrice;
31+}
32+
33+// Example usage
34+const cart: PricedItem[] = [
35+ { name: "Shirt", price: 25 },
36+ { name: "Pants", price: 50 },
37+ { name: "Shoes", price: 100 },
38+];
39+
40+// Calculate price with 10% discount
41+const finalPrice = calculateTotalPrice(cart, 10);
42+console.log(`Final price: $${finalPrice}`);
43+
44+// Export function
45+export default calculateTotalPrice;
46+
47+/*
48+Single Responsibility Principle:
49+
50+The function now has a clearer, more descriptive name: calculateTotalPrice instead of calc_price
51+Used proper camelCase naming convention for JavaScript/TypeScript functions
52+
53+
54+Type Safety:
55+
56+Created a proper PricedItem interface instead of using any[]
57+Added proper type annotations throughout the code
58+
59+
60+Code Quality Improvements:
61+
62+Replaced the for loop with a more functional reduce() approach
63+Used const instead of let where variables aren't reassigned
64+Used default parameter syntax instead of conditional checking
65+Improved variable naming for clarity
66+Added JSDoc comments for better documentation
67+Used template literals instead of string concatenation
68+
69+
70+Fixed Potential Issues:
71+
72+Replaced loose inequality check (!=) with default parameter
73+Changed var to const in the loop to avoid scope issues
74+Made intermediate calculations more explicit with named variables
75+
76+
77+Maintainability:
78+
79+Added proper documentation with JSDoc comments
80+Used more explicit and descriptive variable names
81+*/
added manual-testing-sandbox/next-edit/next-edit-1-1.ts +32 −0
@@ -0,0 +1,32 @@
1+// A simple utility function with minor issues
2+// Difficulty: 1 - Easy fixes needed
3+
4+// Function to calculate total price with discount
5+function calc_price(items: any[], discountPercentage?: number) {
6+ // Calculate total price
7+ let total = 0;
8+ for (var i = 0; i < items.length; i++) {
9+ total = total + items[i].price;
10+ }
11+
12+ // Apply discount
13+ if (discountPercentage != undefined) {
14+ total = total - (total * discountPercentage) / 100;
15+ }
16+
17+ return total;
18+}
19+
20+// Example usage
21+const cart = [
22+ { name: "Shirt", price: 25 },
23+ { name: "Pants", price: 50 },
24+ { name: "Shoes", price: 100 },
25+];
26+
27+// Calculate price with 10% discount
28+const finalPrice = calc_price(cart, 10);
29+console.log("Final price: $" + finalPrice);
30+
31+// Export function
32+export default calc_price;
added manual-testing-sandbox/next-edit/next-edit-10-5-sol.ts +1110 −0
@@ -0,0 +1,1110 @@
1+// Clean, refactored project management application
2+// Demonstrates proper separation of concerns, clean architecture, and SOLID principles
3+
4+// ===== DOMAIN MODELS =====
5+
6+interface User {
7+ readonly id: string;
8+ readonly username: string;
9+ readonly email: string;
10+ readonly isAdmin: boolean;
11+ completedTasks: number;
12+ achievements: string[];
13+}
14+
15+interface Task {
16+ readonly id: string;
17+ readonly createdAt: Date;
18+ readonly createdBy: string;
19+ title: string;
20+ description: string;
21+ status: TaskStatus;
22+ priority: TaskPriority;
23+ assignedTo: string;
24+ projectId: string;
25+ dueDate: Date | null;
26+ comments: string[];
27+ attachments: string[];
28+ tags: string[];
29+ timeSpent: number;
30+ lastUpdated: Date;
31+ completedAt?: Date;
32+ completedBy?: string;
33+ reopenCount: number;
34+}
35+
36+interface Project {
37+ readonly id: string;
38+ readonly createdBy: string;
39+ readonly members: string[];
40+ readonly isPublic: boolean;
41+ taskCount: number;
42+ progress: number;
43+ lastActivity: Date;
44+}
45+
46+type TaskStatus = "new" | "in_progress" | "completed" | "cancelled";
47+type TaskPriority = "low" | "medium" | "high";
48+
49+interface TaskSearchCriteria {
50+ status?: TaskStatus;
51+ priority?: TaskPriority;
52+ assignedTo?: string;
53+ projectId?: string;
54+ searchText?: string;
55+ createdAfter?: Date;
56+ createdBefore?: Date;
57+ dueBefore?: Date;
58+ dueAfter?: Date;
59+ sortBy?: "dueDate" | "priority" | "createdAt";
60+ sortDir?: "asc" | "desc";
61+ page?: number;
62+ limit?: number;
63+}
64+
65+interface CreateTaskRequest {
66+ title: string;
67+ description?: string;
68+ priority?: TaskPriority;
69+ assignedTo?: string;
70+ projectId: string;
71+ dueDate?: Date;
72+ tags?: string[];
73+}
74+
75+interface UpdateTaskRequest {
76+ title?: string;
77+ description?: string;
78+ status?: TaskStatus;
79+ priority?: TaskPriority;
80+ assignedTo?: string;
81+ dueDate?: Date;
82+ tags?: string[];
83+}
84+
85+// ===== CONFIGURATION =====
86+
87+interface AppConfig {
88+ readonly maxTasksPerUser: number;
89+ readonly maxProjectsPerUser: number;
90+ readonly defaultPriority: TaskPriority;
91+ readonly enableNotifications: boolean;
92+ readonly serverUrl: string;
93+}
94+
95+const DEFAULT_CONFIG: AppConfig = {
96+ maxTasksPerUser: 20,
97+ maxProjectsPerUser: 5,
98+ defaultPriority: "medium",
99+ enableNotifications: true,
100+ serverUrl: "https://api.example.com/v1",
101+};
102+
103+// ===== UTILITIES =====
104+
105+class IdGenerator {
106+ static generate(prefix: string): string {
107+ return `${prefix}_${Math.random().toString(36).substring(2, 15)}${Date.now()}`;
108+ }
109+}
110+
111+class ProgressCalculator {
112+ static calculate(tasks: Task[]): number {
113+ if (tasks.length === 0) return 0;
114+ const completed = tasks.filter(
115+ (task) => task.status === "completed",
116+ ).length;
117+ return Math.round((completed / tasks.length) * 100);
118+ }
119+}
120+
121+class TaskSorter {
122+ static sort(
123+ tasks: Task[],
124+ sortBy: string,
125+ sortDir: "asc" | "desc" = "asc",
126+ ): Task[] {
127+ return [...tasks].sort((a, b) => {
128+ switch (sortBy) {
129+ case "dueDate":
130+ return this.compareDates(a.dueDate, b.dueDate, sortDir);
131+ case "priority":
132+ return this.comparePriorities(a.priority, b.priority, sortDir);
133+ default:
134+ return this.compareDates(a.createdAt, b.createdAt, sortDir);
135+ }
136+ });
137+ }
138+
139+ private static compareDates(
140+ a: Date | null,
141+ b: Date | null,
142+ sortDir: "asc" | "desc",
143+ ): number {
144+ if (!a) return sortDir === "asc" ? 1 : -1;
145+ if (!b) return sortDir === "asc" ? -1 : 1;
146+ const diff = a.getTime() - b.getTime();
147+ return sortDir === "asc" ? diff : -diff;
148+ }
149+
150+ private static comparePriorities(
151+ a: TaskPriority,
152+ b: TaskPriority,
153+ sortDir: "asc" | "desc",
154+ ): number {
155+ const priorityMap: Record<TaskPriority, number> = {
156+ high: 3,
157+ medium: 2,
158+ low: 1,
159+ };
160+ const diff = priorityMap[a] - priorityMap[b];
161+ return sortDir === "asc" ? diff : -diff;
162+ }
163+}
164+
165+class Paginator {
166+ static paginate<T>(items: T[], page: number = 1, limit: number): T[] {
167+ const start = (page - 1) * limit;
168+ return items.slice(start, start + limit);
169+ }
170+}
171+
172+// ===== VALIDATION SERVICES =====
173+
174+class TaskValidationError extends Error {
175+ constructor(
176+ message: string,
177+ public field?: string,
178+ ) {
179+ super(message);
180+ this.name = "TaskValidationError";
181+ }
182+}
183+
184+class TaskValidator {
185+ constructor(
186+ private readonly projectRepository: ProjectRepository,
187+ private readonly taskRepository: TaskRepository,
188+ private readonly config: AppConfig,
189+ ) {}
190+
191+ validateCreateRequest(request: CreateTaskRequest): void {
192+ if (!request.title?.trim()) {
193+ throw new TaskValidationError("Task title is required", "title");
194+ }
195+
196+ if (!request.projectId) {
197+ throw new TaskValidationError(
198+ "Task must belong to a project",
199+ "projectId",
200+ );
201+ }
202+
203+ if (!this.projectRepository.exists(request.projectId)) {
204+ throw new TaskValidationError("Project does not exist", "projectId");
205+ }
206+ }
207+
208+ validateTaskLimits(assignedUserId: string): void {
209+ const userActiveTasks =
210+ this.taskRepository.getActiveTasksByUser(assignedUserId);
211+ if (userActiveTasks.length >= this.config.maxTasksPerUser) {
212+ throw new TaskValidationError(
213+ `User cannot have more than ${this.config.maxTasksPerUser} active tasks`,
214+ );
215+ }
216+ }
217+
218+ validateUpdateRequest(request: UpdateTaskRequest): void {
219+ if (request.title !== undefined && !request.title?.trim()) {
220+ throw new TaskValidationError("Task title cannot be empty", "title");
221+ }
222+ }
223+}
224+
225+// ===== REPOSITORY INTERFACES =====
226+
227+interface TaskRepository {
228+ save(task: Task): void;
229+ findById(id: string): Task | null;
230+ findAll(): Task[];
231+ update(id: string, task: Task): void;
232+ delete(id: string): void;
233+ getActiveTasksByUser(userId: string): Task[];
234+ findByProject(projectId: string): Task[];
235+ search(criteria: TaskSearchCriteria, currentUserId: string): Task[];
236+}
237+
238+interface UserRepository {
239+ findById(id: string): User | null;
240+ findByUsername(username: string): User | null;
241+ update(user: User): void;
242+}
243+
244+interface ProjectRepository {
245+ findById(id: string): Project | null;
246+ exists(id: string): boolean;
247+ update(project: Project): void;
248+ isUserMember(projectId: string, userId: string): boolean;
249+}
250+
251+// ===== IN-MEMORY IMPLEMENTATIONS =====
252+
253+class InMemoryTaskRepository implements TaskRepository {
254+ private tasks: Map<string, Task> = new Map();
255+
256+ save(task: Task): void {
257+ this.tasks.set(task.id, { ...task });
258+ }
259+
260+ findById(id: string): Task | null {
261+ const task = this.tasks.get(id);
262+ return task ? { ...task } : null;
263+ }
264+
265+ findAll(): Task[] {
266+ return Array.from(this.tasks.values()).map((task) => ({ ...task }));
267+ }
268+
269+ update(id: string, task: Task): void {
270+ if (!this.tasks.has(id)) {
271+ throw new Error("Task not found");
272+ }
273+ this.tasks.set(id, { ...task });
274+ }
275+
276+ delete(id: string): void {
277+ this.tasks.delete(id);
278+ }
279+
280+ getActiveTasksByUser(userId: string): Task[] {
281+ return this.findAll().filter(
282+ (task) => task.assignedTo === userId && task.status !== "completed",
283+ );
284+ }
285+
286+ findByProject(projectId: string): Task[] {
287+ return this.findAll().filter((task) => task.projectId === projectId);
288+ }
289+
290+ search(criteria: TaskSearchCriteria, currentUserId: string): Task[] {
291+ return this.findAll().filter((task) =>
292+ this.matchesSearchCriteria(task, criteria, currentUserId),
293+ );
294+ }
295+
296+ private matchesSearchCriteria(
297+ task: Task,
298+ criteria: TaskSearchCriteria,
299+ currentUserId: string,
300+ ): boolean {
301+ // Simplified visibility check - in real app, this would use ProjectRepository
302+ const isVisible =
303+ task.createdBy === currentUserId || task.assignedTo === currentUserId;
304+ if (!isVisible) return false;
305+
306+ if (criteria.status && task.status !== criteria.status) return false;
307+ if (criteria.priority && task.priority !== criteria.priority) return false;
308+ if (criteria.assignedTo && task.assignedTo !== criteria.assignedTo)
309+ return false;
310+ if (criteria.projectId && task.projectId !== criteria.projectId)
311+ return false;
312+
313+ if (criteria.searchText) {
314+ const searchText = criteria.searchText.toLowerCase();
315+ const matchesTitle = task.title.toLowerCase().includes(searchText);
316+ const matchesDescription = task.description
317+ .toLowerCase()
318+ .includes(searchText);
319+ const matchesTags = task.tags.some((tag) =>
320+ tag.toLowerCase().includes(searchText),
321+ );
322+
323+ if (!matchesTitle && !matchesDescription && !matchesTags) return false;
324+ }
325+
326+ if (criteria.createdAfter && task.createdAt < criteria.createdAfter)
327+ return false;
328+ if (criteria.createdBefore && task.createdAt > criteria.createdBefore)
329+ return false;
330+ if (criteria.dueBefore && task.dueDate && task.dueDate > criteria.dueBefore)
331+ return false;
332+ if (criteria.dueAfter && task.dueDate && task.dueDate < criteria.dueAfter)
333+ return false;
334+
335+ return true;
336+ }
337+}
338+
339+class InMemoryUserRepository implements UserRepository {
340+ private users: Map<string, User> = new Map();
341+
342+ findById(id: string): User | null {
343+ const user = this.users.get(id);
344+ return user ? { ...user } : null;
345+ }
346+
347+ findByUsername(username: string): User | null {
348+ for (const user of this.users.values()) {
349+ if (user.username === username) {
350+ return { ...user };
351+ }
352+ }
353+ return null;
354+ }
355+
356+ update(user: User): void {
357+ this.users.set(user.id, { ...user });
358+ }
359+
360+ // Method to add users for testing
361+ add(user: User): void {
362+ this.users.set(user.id, { ...user });
363+ }
364+}
365+
366+class InMemoryProjectRepository implements ProjectRepository {
367+ private projects: Map<string, Project> = new Map();
368+
369+ findById(id: string): Project | null {
370+ const project = this.projects.get(id);
371+ return project ? { ...project } : null;
372+ }
373+
374+ exists(id: string): boolean {
375+ return this.projects.has(id);
376+ }
377+
378+ update(project: Project): void {
379+ this.projects.set(project.id, { ...project });
380+ }
381+
382+ isUserMember(projectId: string, userId: string): boolean {
383+ const project = this.findById(projectId);
384+ return project
385+ ? project.members.includes(userId) || project.createdBy === userId
386+ : false;
387+ }
388+
389+ // Method to add projects for testing
390+ add(project: Project): void {
391+ this.projects.set(project.id, { ...project });
392+ }
393+}
394+
395+// ===== AUTHORIZATION SERVICE =====
396+
397+class AuthorizationError extends Error {
398+ constructor(message: string) {
399+ super(message);
400+ this.name = "AuthorizationError";
401+ }
402+}
403+
404+class TaskAuthorizationService {
405+ constructor(private readonly projectRepository: ProjectRepository) {}
406+
407+ canCreateTask(projectId: string, userId: string): boolean {
408+ return this.projectRepository.isUserMember(projectId, userId);
409+ }
410+
411+ canUpdateTask(task: Task, userId: string, isAdmin: boolean): boolean {
412+ return task.createdBy === userId || task.assignedTo === userId || isAdmin;
413+ }
414+
415+ canDeleteTask(task: Task, userId: string, isAdmin: boolean): boolean {
416+ return task.createdBy === userId || isAdmin;
417+ }
418+
419+ requireCreatePermission(projectId: string, userId: string): void {
420+ if (!this.canCreateTask(projectId, userId)) {
421+ throw new AuthorizationError("You do not have access to this project");
422+ }
423+ }
424+
425+ requireUpdatePermission(task: Task, userId: string, isAdmin: boolean): void {
426+ if (!this.canUpdateTask(task, userId, isAdmin)) {
427+ throw new AuthorizationError(
428+ "You do not have permission to update this task",
429+ );
430+ }
431+ }
432+
433+ requireDeletePermission(task: Task, userId: string, isAdmin: boolean): void {
434+ if (!this.canDeleteTask(task, userId, isAdmin)) {
435+ throw new AuthorizationError(
436+ "Only the creator or an admin can delete a task",
437+ );
438+ }
439+ }
440+}
441+
442+// ===== NOTIFICATION SERVICE =====
443+
444+interface NotificationService {
445+ sendTaskAssigned(task: Task, assignee: User): void;
446+ sendTaskDeleted(task: Task, user: User): void;
447+ sendAchievementEarned(achievement: string, user: User): void;
448+}
449+
450+class ConsoleNotificationService implements NotificationService {
451+ constructor(private readonly config: AppConfig) {}
452+
453+ sendTaskAssigned(task: Task, assignee: User): void {
454+ if (!this.config.enableNotifications) return;
455+ console.log(
456+ `[NOTIFICATION to ${assignee.email}]: You've been assigned a new task: ${task.title}`,
457+ );
458+ }
459+
460+ sendTaskDeleted(task: Task, user: User): void {
461+ if (!this.config.enableNotifications) return;
462+ console.log(
463+ `[NOTIFICATION to ${user.email}]: A task assigned to you was deleted: ${task.title}`,
464+ );
465+ }
466+
467+ sendAchievementEarned(achievement: string, user: User): void {
468+ if (!this.config.enableNotifications) return;
469+ console.log(
470+ `[NOTIFICATION to ${user.email}]: You earned the ${achievement} badge!`,
471+ );
472+ }
473+}
474+
475+// ===== LOGGING SERVICE =====
476+
477+interface Logger {
478+ log(action: string, data: any): void;
479+}
480+
481+class ConsoleLogger implements Logger {
482+ log(action: string, data: any): void {
483+ console.log(`[${new Date().toISOString()}] ${action}:`, data);
484+ }
485+}
486+
487+// ===== DOMAIN SERVICES =====
488+
489+class AchievementService {
490+ constructor(
491+ private readonly userRepository: UserRepository,
492+ private readonly notificationService: NotificationService,
493+ ) {}
494+
495+ checkAndAwardAchievements(user: User): void {
496+ if (
497+ user.completedTasks >= 10 &&
498+ !user.achievements.includes("productive")
499+ ) {
500+ user.achievements = [...user.achievements, "productive"];
501+ this.userRepository.update(user);
502+ this.notificationService.sendAchievementEarned("Productive", user);
503+ }
504+ }
505+}
506+
507+class ProjectUpdateService {
508+ constructor(
509+ private readonly projectRepository: ProjectRepository,
510+ private readonly taskRepository: TaskRepository,
511+ ) {}
512+
513+ updateProjectMetrics(projectId: string): void {
514+ const project = this.projectRepository.findById(projectId);
515+ if (!project) return;
516+
517+ const projectTasks = this.taskRepository.findByProject(projectId);
518+
519+ const updatedProject: Project = {
520+ ...project,
521+ taskCount: projectTasks.length,
522+ progress: ProgressCalculator.calculate(projectTasks),
523+ lastActivity: new Date(),
524+ };
525+
526+ this.projectRepository.update(updatedProject);
527+ }
528+}
529+
530+// ===== MAIN SERVICE =====
531+
532+class TaskService {
533+ constructor(
534+ private readonly taskRepository: TaskRepository,
535+ private readonly userRepository: UserRepository,
536+ private readonly projectRepository: ProjectRepository,
537+ private readonly validator: TaskValidator,
538+ private readonly authService: TaskAuthorizationService,
539+ private readonly notificationService: NotificationService,
540+ private readonly achievementService: AchievementService,
541+ private readonly projectUpdateService: ProjectUpdateService,
542+ private readonly logger: Logger,
543+ private readonly config: AppConfig,
544+ ) {}
545+
546+ createTask(request: CreateTaskRequest, currentUserId: string): Task {
547+ // Validation
548+ this.validator.validateCreateRequest(request);
549+ this.authService.requireCreatePermission(request.projectId, currentUserId);
550+
551+ const assignedUserId = request.assignedTo || currentUserId;
552+ this.validator.validateTaskLimits(assignedUserId);
553+
554+ // Create task
555+ const task: Task = {
556+ id: IdGenerator.generate("task"),
557+ title: request.title.trim(),
558+ description: request.description?.trim() || "",
559+ status: "new",
560+ priority: request.priority || this.config.defaultPriority,
561+ createdAt: new Date(),
562+ createdBy: currentUserId,
563+ assignedTo: assignedUserId,
564+ projectId: request.projectId,
565+ dueDate: request.dueDate || null,
566+ comments: [],
567+ attachments: [],
568+ tags: request.tags || [],
569+ timeSpent: 0,
570+ lastUpdated: new Date(),
571+ reopenCount: 0,
572+ };
573+
574+ // Save task
575+ this.taskRepository.save(task);
576+
577+ // Handle side effects
578+ this.handleTaskCreatedSideEffects(task, currentUserId);
579+
580+ this.logger.log("task_created", { taskId: task.id, title: task.title });
581+
582+ return task;
583+ }
584+
585+ updateTask(
586+ taskId: string,
587+ request: UpdateTaskRequest,
588+ currentUserId: string,
589+ isAdmin: boolean,
590+ ): Task {
591+ // Validation
592+ this.validator.validateUpdateRequest(request);
593+
594+ const existingTask = this.taskRepository.findById(taskId);
595+ if (!existingTask) {
596+ throw new Error("Task not found");
597+ }
598+
599+ this.authService.requireUpdatePermission(
600+ existingTask,
601+ currentUserId,
602+ isAdmin,
603+ );
604+
605+ // Handle status transitions
606+ const updatedTask = this.applyTaskUpdates(
607+ existingTask,
608+ request,
609+ currentUserId,
610+ );
611+
612+ // Save task
613+ this.taskRepository.update(taskId, updatedTask);
614+
615+ // Handle side effects
616+ this.handleTaskUpdatedSideEffects(updatedTask, request, currentUserId);
617+
618+ this.logger.log("task_updated", { taskId, changes: Object.keys(request) });
619+
620+ return updatedTask;
621+ }
622+
623+ deleteTask(taskId: string, currentUserId: string, isAdmin: boolean): void {
624+ const task = this.taskRepository.findById(taskId);
625+ if (!task) {
626+ throw new Error("Task not found");
627+ }
628+
629+ this.authService.requireDeletePermission(task, currentUserId, isAdmin);
630+
631+ // Delete task
632+ this.taskRepository.delete(taskId);
633+
634+ // Handle side effects
635+ this.handleTaskDeletedSideEffects(task, currentUserId);
636+
637+ this.logger.log("task_deleted", { taskId, title: task.title });
638+ }
639+
640+ searchTasks(criteria: TaskSearchCriteria, currentUserId: string): Task[] {
641+ let results = this.taskRepository.search(criteria, currentUserId);
642+
643+ // Apply sorting
644+ if (criteria.sortBy) {
645+ results = TaskSorter.sort(results, criteria.sortBy, criteria.sortDir);
646+ }
647+
648+ // Apply pagination
649+ if (criteria.limit) {
650+ results = Paginator.paginate(results, criteria.page, criteria.limit);
651+ }
652+
653+ this.logger.log("tasks_searched", {
654+ criteria,
655+ resultCount: results.length,
656+ });
657+
658+ return results;
659+ }
660+
661+ private applyTaskUpdates(
662+ task: Task,
663+ request: UpdateTaskRequest,
664+ currentUserId: string,
665+ ): Task {
666+ const updatedTask: Task = { ...task };
667+
668+ // Handle status transitions
669+ if (request.status && request.status !== task.status) {
670+ this.handleStatusTransition(updatedTask, request.status, currentUserId);
671+ }
672+
673+ // Apply other updates
674+ if (request.title !== undefined) updatedTask.title = request.title.trim();
675+ if (request.description !== undefined)
676+ updatedTask.description = request.description.trim();
677+ if (request.priority !== undefined) updatedTask.priority = request.priority;
678+ if (request.assignedTo !== undefined)
679+ updatedTask.assignedTo = request.assignedTo;
680+ if (request.dueDate !== undefined) updatedTask.dueDate = request.dueDate;
681+ if (request.tags !== undefined) updatedTask.tags = request.tags;
682+
683+ updatedTask.lastUpdated = new Date();
684+
685+ return updatedTask;
686+ }
687+
688+ private handleStatusTransition(
689+ task: Task,
690+ newStatus: TaskStatus,
691+ currentUserId: string,
692+ ): void {
693+ if (task.status === "completed" && newStatus !== "completed") {
694+ // Re-opening completed task
695+ task.reopenCount++;
696+ this.logger.log("task_reopened", {
697+ taskId: task.id,
698+ previousStatus: task.status,
699+ });
700+ }
701+
702+ if (newStatus === "completed") {
703+ // Completing task
704+ task.completedAt = new Date();
705+ task.completedBy = currentUserId;
706+
707+ // Update user stats
708+ const user = this.userRepository.findById(currentUserId);
709+ if (user) {
710+ user.completedTasks++;
711+ this.userRepository.update(user);
712+ this.achievementService.checkAndAwardAchievements(user);
713+ }
714+ }
715+
716+ task.status = newStatus;
717+ }
718+
719+ private handleTaskCreatedSideEffects(
720+ task: Task,
721+ currentUserId: string,
722+ ): void {
723+ // Send notification to assignee
724+ if (task.assignedTo !== currentUserId) {
725+ const assignee = this.userRepository.findById(task.assignedTo);
726+ if (assignee) {
727+ this.notificationService.sendTaskAssigned(task, assignee);
728+ }
729+ }
730+
731+ // Update project metrics
732+ this.projectUpdateService.updateProjectMetrics(task.projectId);
733+ }
734+
735+ private handleTaskUpdatedSideEffects(
736+ task: Task,
737+ request: UpdateTaskRequest,
738+ currentUserId: string,
739+ ): void {
740+ // Send notification if assignee changed
741+ if (request.assignedTo && request.assignedTo !== task.assignedTo) {
742+ const assignee = this.userRepository.findById(request.assignedTo);
743+ if (assignee) {
744+ this.notificationService.sendTaskAssigned(task, assignee);
745+ }
746+ }
747+
748+ // Update project metrics
749+ this.projectUpdateService.updateProjectMetrics(task.projectId);
750+ }
751+
752+ private handleTaskDeletedSideEffects(
753+ task: Task,
754+ currentUserId: string,
755+ ): void {
756+ // Send notification to assignee
757+ if (task.assignedTo !== currentUserId) {
758+ const assignee = this.userRepository.findById(task.assignedTo);
759+ if (assignee) {
760+ this.notificationService.sendTaskDeleted(task, assignee);
761+ }
762+ }
763+
764+ // Update project metrics (async to avoid race condition)
765+ setTimeout(() => {
766+ this.projectUpdateService.updateProjectMetrics(task.projectId);
767+ }, 0);
768+ }
769+}
770+
771+// ===== AUTHENTICATION SERVICE =====
772+
773+class AuthenticationError extends Error {
774+ constructor(message: string) {
775+ super(message);
776+ this.name = "AuthenticationError";
777+ }
778+}
779+
780+class AuthenticationService {
781+ constructor(
782+ private readonly userRepository: UserRepository,
783+ private readonly logger: Logger,
784+ ) {}
785+
786+ authenticate(username: string, password: string): User {
787+ const user = this.userRepository.findByUsername(username);
788+
789+ if (!user) {
790+ this.logger.log("auth_failed", { username, reason: "user_not_found" });
791+ throw new AuthenticationError("Invalid credentials");
792+ }
793+
794+ // In a real app, this would use proper password hashing
795+ if ((user as any).password !== password) {
796+ this.logger.log("auth_failed", { username, reason: "invalid_password" });
797+ throw new AuthenticationError("Invalid credentials");
798+ }
799+
800+ this.logger.log("auth_success", { userId: user.id });
801+ return user;
802+ }
803+}
804+
805+// ===== DEPENDENCY INJECTION CONTAINER =====
806+
807+class TaskManagementSystem {
808+ private readonly taskRepository: TaskRepository;
809+ private readonly userRepository: UserRepository;
810+ private readonly projectRepository: ProjectRepository;
811+ private readonly validator: TaskValidator;
812+ private readonly authService: TaskAuthorizationService;
813+ private readonly notificationService: NotificationService;
814+ private readonly achievementService: AchievementService;
815+ private readonly projectUpdateService: ProjectUpdateService;
816+ private readonly logger: Logger;
817+ private readonly taskService: TaskService;
818+ private readonly authenticationService: AuthenticationService;
819+ private readonly config: AppConfig;
820+
821+ private currentUser: User | null = null;
822+
823+ constructor(config: AppConfig = DEFAULT_CONFIG) {
824+ this.config = config;
825+
826+ // Initialize repositories
827+ this.taskRepository = new InMemoryTaskRepository();
828+ this.userRepository = new InMemoryUserRepository();
829+ this.projectRepository = new InMemoryProjectRepository();
830+
831+ // Initialize services
832+ this.logger = new ConsoleLogger();
833+ this.notificationService = new ConsoleNotificationService(config);
834+ this.validator = new TaskValidator(
835+ this.projectRepository,
836+ this.taskRepository,
837+ config,
838+ );
839+ this.authService = new TaskAuthorizationService(this.projectRepository);
840+ this.achievementService = new AchievementService(
841+ this.userRepository,
842+ this.notificationService,
843+ );
844+ this.projectUpdateService = new ProjectUpdateService(
845+ this.projectRepository,
846+ this.taskRepository,
847+ );
848+
849+ // Initialize main services
850+ this.taskService = new TaskService(
851+ this.taskRepository,
852+ this.userRepository,
853+ this.projectRepository,
854+ this.validator,
855+ this.authService,
856+ this.notificationService,
857+ this.achievementService,
858+ this.projectUpdateService,
859+ this.logger,
860+ config,
861+ );
862+
863+ this.authenticationService = new AuthenticationService(
864+ this.userRepository,
865+ this.logger,
866+ );
867+ }
868+
869+ // Public API methods
870+ authenticate(username: string, password: string): User {
871+ this.currentUser = this.authenticationService.authenticate(
872+ username,
873+ password,
874+ );
875+ return this.currentUser;
876+ }
877+
878+ createTask(request: CreateTaskRequest): Task {
879+ this.requireAuthentication();
880+ return this.taskService.createTask(request, this.currentUser!.id);
881+ }
882+
883+ updateTask(taskId: string, request: UpdateTaskRequest): Task {
884+ this.requireAuthentication();
885+ return this.taskService.updateTask(
886+ taskId,
887+ request,
888+ this.currentUser!.id,
889+ this.currentUser!.isAdmin,
890+ );
891+ }
892+
893+ deleteTask(taskId: string): void {
894+ this.requireAuthentication();
895+ this.taskService.deleteTask(
896+ taskId,
897+ this.currentUser!.id,
898+ this.currentUser!.isAdmin,
899+ );
900+ }
901+
902+ searchTasks(criteria: TaskSearchCriteria): Task[] {
903+ this.requireAuthentication();
904+ return this.taskService.searchTasks(criteria, this.currentUser!.id);
905+ }
906+
907+ // Helper methods for testing
908+ addUser(user: User & { password: string }): void {
909+ (this.userRepository as InMemoryUserRepository).add(user);
910+ }
911+
912+ addProject(project: Project): void {
913+ (this.projectRepository as InMemoryProjectRepository).add(project);
914+ }
915+
916+ private requireAuthentication(): void {
917+ if (!this.currentUser) {
918+ throw new AuthenticationError("Not authenticated");
919+ }
920+ }
921+}
922+
923+// ===== USAGE EXAMPLE =====
924+
925+// Initialize the system
926+const taskSystem = new TaskManagementSystem();
927+
928+// Add test data
929+taskSystem.addUser({
930+ id: "user_1",
931+ username: "john_doe",
932+ email: "john@example.com",
933+ password: "password123", // In real app, this would be hashed
934+ isAdmin: false,
935+ completedTasks: 0,
936+ achievements: [],
937+});
938+
939+taskSystem.addProject({
940+ id: "proj_1",
941+ createdBy: "user_1",
942+ members: ["user_1"],
943+ isPublic: false,
944+ taskCount: 0,
945+ progress: 0,
946+ lastActivity: new Date(),
947+});
948+
949+// Usage example
950+try {
951+ // Authenticate
952+ const user = taskSystem.authenticate("john_doe", "password123");
953+ console.log("Authenticated user:", user.username);
954+
955+ // Create a task
956+ const task = taskSystem.createTask({
957+ title: "Implement login feature",
958+ description: "Add user authentication to the application",
959+ projectId: "proj_1",
960+ priority: "high",
961+ tags: ["frontend", "authentication"],
962+ });
963+ console.log("Created task:", task.title);
964+
965+ // Update the task
966+ const updatedTask = taskSystem.updateTask(task.id, {
967+ status: "in_progress",
968+ description: "Updated description with more details",
969+ });
970+ console.log("Updated task status:", updatedTask.status);
971+
972+ // Search tasks
973+ const searchResults = taskSystem.searchTasks({
974+ status: "in_progress",
975+ sortBy: "createdAt",
976+ sortDir: "desc",
977+ });
978+ console.log("Found tasks:", searchResults.length);
979+} catch (error) {
980+ console.error("Error:", error.message);
981+}
982+
983+export default TaskManagementSystem;
984+
985+/*
986+Code Smells Identified
987+
988+Architecture & Design Issues:
989+
990+Global state management with mutable variables scattered throughout
991+Mixed responsibilities - authentication, validation, business logic, and side effects all tangled together
992+Tight coupling between unrelated concerns (DOM manipulation in utilities, notifications in business logic)
993+No separation of concerns or proper layering
994+
995+
996+Code Organization Problems:
997+
998+Utility functions performing side effects and business logic
999+Authentication mixed with data fetching
1000+Validation logic scattered and inconsistent
1001+Business rules hardcoded throughout the application
1002+
1003+
1004+State Management Issues:
1005+
1006+Direct global state mutations everywhere
1007+No centralized state management
1008+Side effects performed synchronously during core operations
1009+Inconsistent data flow patterns
1010+
1011+
1012+Error Handling & Reliability:
1013+
1014+Poor error handling with generic Error objects
1015+No input sanitization or proper validation
1016+Inconsistent permission checking
1017+Race conditions with setTimeout usage
1018+
1019+
1020+Improvements Made
1021+
1022+Architecture & Design Improvements:
1023+
1024+Implemented proper separation of concerns with distinct layers (domain, repository, service)
1025+Applied SOLID principles - single responsibility, dependency injection, interface segregation
1026+Introduced clean architecture with domain models, repositories, and services
1027+Removed tight coupling by using dependency injection and interfaces
1028+Created a proper dependency injection container (TaskManagementSystem)
1029+
1030+
1031+State Management Improvements:
1032+
1033+Eliminated global mutable state - all state is now properly encapsulated in repositories
1034+Implemented immutable data patterns with object spreading and readonly properties
1035+Centralized state management through repository pattern
1036+Removed direct global variable mutations throughout the codebase
1037+Added proper data flow with clear boundaries between layers
1038+
1039+
1040+Error Handling & Validation:
1041+
1042+Created specific error types (TaskValidationError, AuthorizationError, AuthenticationError)
1043+Separated validation logic into dedicated TaskValidator service
1044+Added comprehensive input validation with field-level error reporting
1045+Implemented consistent error handling patterns across all operations
1046+Removed generic Error objects in favor of domain-specific exceptions
1047+
1048+
1049+Business Logic Organization:
1050+
1051+Extracted authentication into dedicated AuthenticationService
1052+Created TaskAuthorizationService for permission checking
1053+Separated achievement logic into AchievementService
1054+Moved project updates into ProjectUpdateService
1055+Centralized task operations in TaskService with clear single responsibility
1056+
1057+
1058+Code Quality & Maintainability:
1059+
1060+Added comprehensive TypeScript interfaces for type safety
1061+Implemented proper method signatures with clear input/output types
1062+Created utility classes (IdGenerator, ProgressCalculator, TaskSorter, Paginator)
1063+Removed code duplication through reusable components
1064+Added consistent naming conventions and clear method purposes
1065+
1066+
1067+Side Effects & Dependencies:
1068+
1069+Isolated notification logic into NotificationService interface
1070+Separated logging into Logger interface with clean abstraction
1071+Removed DOM manipulation from business logic
1072+Made all side effects explicit and controllable through dependency injection
1073+Eliminated setTimeout race conditions with proper async handling
1074+
1075+
1076+Data Access Improvements:
1077+
1078+Implemented repository pattern with clear interfaces
1079+Added proper data encapsulation with immutable returns
1080+Created in-memory implementations that can be easily swapped
1081+Removed direct array mutations in favor of immutable operations
1082+Added proper data validation at repository boundaries
1083+
1084+
1085+Security & Authorization:
1086+
1087+Separated authentication from authorization concerns
1088+Implemented proper permission checking before operations
1089+Added role-based access control (admin vs regular users)
1090+Removed mixed permission logic from business operations
1091+Created centralized authorization service
1092+
1093+
1094+Testing & Extensibility:
1095+
1096+Made all dependencies injectable for easy testing
1097+Created interfaces that allow for easy mocking
1098+Separated configuration into AppConfig interface
1099+Added helper methods for test data setup
1100+Designed for easy extension with new features
1101+
1102+
1103+Performance & Scalability:
1104+
1105+Removed inefficient global array filtering
1106+Implemented proper pagination with Paginator utility
1107+Added efficient sorting with TaskSorter utility
1108+Eliminated redundant calculations in loops
1109+Created reusable calculation utilities (ProgressCalculator)
1110+*/
added manual-testing-sandbox/next-edit/next-edit-10-5.ts +445 −0
@@ -0,0 +1,445 @@
1+// A messy project management application with tangled dependencies and responsibilities
2+// Difficulty: 5/5
3+
4+// Global state
5+let globalTasks: any[] = [];
6+let globalUsers: any[] = [];
7+let globalProjects: any[] = [];
8+let currentUser: any = null;
9+let lastActivityTime = Date.now();
10+let _config = {
11+ maxTasksPerUser: 20,
12+ maxProjectsPerUser: 5,
13+ defaultPriority: "medium",
14+ enableNotifications: true,
15+ serverUrl: "https://api.example.com/v1",
16+};
17+
18+// Mixed utility functions and business logic
19+const util = {
20+ generateId: (prefix: string) =>
21+ `${prefix}_${Math.random().toString(36).substring(2, 15)}${Date.now()}`,
22+ calculateProgress: (tasks: any[]) => {
23+ const completed = tasks.filter((t) => t.status === "completed").length;
24+ return tasks.length ? Math.round((completed / tasks.length) * 100) : 0;
25+ },
26+ sendNotification: (type: string, message: string, user: any) => {
27+ if (!_config.enableNotifications) return;
28+ console.log(`[NOTIFICATION to ${user.email}]: ${message}`);
29+ // Side effects directly inside utility function
30+ if (typeof window !== "undefined") {
31+ // DOM manipulation in utility
32+ const notification = document.createElement("div");
33+ notification.className = `notification ${type}`;
34+ notification.innerText = message;
35+ document.body.appendChild(notification);
36+ setTimeout(() => notification.remove(), 5000);
37+ }
38+ },
39+ logger: (action: string, data: any) => {
40+ console.log(`[${new Date().toISOString()}] ${action}:`, data);
41+ // Side effect - updating activity time
42+ lastActivityTime = Date.now();
43+ },
44+};
45+
46+// Data validation mixed with business logic
47+function validateTask(task: any) {
48+ if (!task.title) throw new Error("Task title is required");
49+ if (!task.projectId) throw new Error("Task must belong to a project");
50+ if (!globalProjects.some((p) => p.id === task.projectId)) {
51+ throw new Error("Project does not exist");
52+ }
53+
54+ // Validation mixed with business rules
55+ const userTasks = globalTasks.filter(
56+ (t) => t.assignedTo === task.assignedTo && t.status !== "completed",
57+ );
58+
59+ if (userTasks.length >= _config.maxTasksPerUser) {
60+ throw new Error(
61+ `User cannot have more than ${_config.maxTasksPerUser} active tasks`,
62+ );
63+ }
64+
65+ return true;
66+}
67+
68+// Authentication mixed with data fetching
69+function authenticate(username: string, password: string) {
70+ // Direct data manipulation and mocked authentication
71+ const user = globalUsers.find((u) => u.username === username);
72+ if (!user || user.password !== password) {
73+ util.logger("auth_failed", { username });
74+ throw new Error("Invalid credentials");
75+ }
76+
77+ currentUser = user;
78+ util.logger("auth_success", { userId: user.id });
79+
80+ // Mixing data fetching with authentication
81+ loadUserData(user.id);
82+
83+ return user;
84+}
85+
86+// Data fetching with side effects
87+function loadUserData(userId: string) {
88+ // This would be an API call in real app
89+ console.log(`Loading data for user ${userId}`);
90+
91+ // Direct global state manipulation
92+ globalTasks = globalTasks.filter(
93+ (t) => t.createdBy === userId || t.assignedTo === userId,
94+ );
95+
96+ globalProjects = globalProjects.filter(
97+ (p) => p.members.includes(userId) || p.createdBy === userId,
98+ );
99+
100+ // Direct DOM manipulation
101+ if (typeof document !== "undefined") {
102+ const taskCount = document.getElementById("task-count");
103+ if (taskCount) {
104+ taskCount.innerText = String(globalTasks.length);
105+ }
106+ }
107+}
108+
109+// Task management with mixed responsibilities
110+class TaskManager {
111+ // Creates a task with mixed concerns
112+ createTask(taskData: any) {
113+ if (!currentUser) throw new Error("Not authenticated");
114+
115+ // Authentication check mixed with business logic
116+ if (taskData.projectId) {
117+ const project = globalProjects.find((p) => p.id === taskData.projectId);
118+ if (
119+ !project.members.includes(currentUser.id) &&
120+ project.createdBy !== currentUser.id
121+ ) {
122+ throw new Error("You do not have access to this project");
123+ }
124+ }
125+
126+ const task = {
127+ id: util.generateId("task"),
128+ title: taskData.title,
129+ description: taskData.description || "",
130+ status: "new",
131+ priority: taskData.priority || _config.defaultPriority,
132+ createdAt: new Date(),
133+ createdBy: currentUser.id,
134+ assignedTo: taskData.assignedTo || currentUser.id,
135+ projectId: taskData.projectId,
136+ dueDate: taskData.dueDate || null,
137+ comments: [],
138+ attachments: [],
139+ tags: taskData.tags || [],
140+ timeSpent: 0,
141+ lastUpdated: new Date(),
142+ };
143+
144+ // Validation mixed with creation
145+ validateTask(task);
146+
147+ // Global state mutation
148+ globalTasks.push(task);
149+
150+ // Side effects - email notification mixed with task creation
151+ if (task.assignedTo !== currentUser.id) {
152+ const assignee = globalUsers.find((u) => u.id === task.assignedTo);
153+ if (assignee) {
154+ console.log(
155+ `Sending email to ${assignee.email} about new task assignment`,
156+ );
157+ util.sendNotification(
158+ "task_assigned",
159+ `You've been assigned a new task: ${task.title}`,
160+ assignee,
161+ );
162+ }
163+ }
164+
165+ // More side effects - updating project data
166+ if (task.projectId) {
167+ const project = globalProjects.find((p) => p.id === task.projectId);
168+ if (project) {
169+ project.taskCount = (project.taskCount || 0) + 1;
170+ project.lastActivity = new Date();
171+ // Recalculating project progress on each task addition
172+ const projectTasks = globalTasks.filter(
173+ (t) => t.projectId === project.id,
174+ );
175+ project.progress = util.calculateProgress(projectTasks);
176+ }
177+ }
178+
179+ // Logging
180+ util.logger("task_created", { taskId: task.id, title: task.title });
181+
182+ return task;
183+ }
184+
185+ // Update task with mixed concerns
186+ updateTask(taskId: string, updates: any) {
187+ if (!currentUser) throw new Error("Not authenticated");
188+
189+ const taskIndex = globalTasks.findIndex((t) => t.id === taskId);
190+ if (taskIndex === -1) throw new Error("Task not found");
191+
192+ const task = globalTasks[taskIndex];
193+
194+ // Permission check mixed with update logic
195+ if (
196+ task.createdBy !== currentUser.id &&
197+ task.assignedTo !== currentUser.id &&
198+ !currentUser.isAdmin
199+ ) {
200+ throw new Error("You do not have permission to update this task");
201+ }
202+
203+ // Status transition logic mixed with update
204+ if (updates.status && updates.status !== task.status) {
205+ if (task.status === "completed" && updates.status !== "completed") {
206+ // Re-opening completed task
207+ task.reopenCount = (task.reopenCount || 0) + 1;
208+ util.logger("task_reopened", { taskId, previousStatus: task.status });
209+ }
210+
211+ if (updates.status === "completed") {
212+ // Completing task
213+ task.completedAt = new Date();
214+ task.completedBy = currentUser.id;
215+
216+ // Side effect - updating user stats
217+ const user = globalUsers.find((u) => u.id === currentUser.id);
218+ if (user) {
219+ user.completedTasks = (user.completedTasks || 0) + 1;
220+ // More side effects - achievement system
221+ if (
222+ user.completedTasks >= 10 &&
223+ !user.achievements?.includes("productive")
224+ ) {
225+ user.achievements = [...(user.achievements || []), "productive"];
226+ util.sendNotification(
227+ "achievement",
228+ "You earned the Productive badge!",
229+ user,
230+ );
231+ }
232+ }
233+ }
234+ }
235+
236+ // Main update logic - directly modifying the object
237+ Object.keys(updates).forEach((key) => {
238+ // Skip protected fields
239+ if (!["id", "createdAt", "createdBy"].includes(key)) {
240+ task[key] = updates[key];
241+ }
242+ });
243+
244+ task.lastUpdated = new Date();
245+
246+ // Validation after update (inconsistent)
247+ validateTask(task);
248+
249+ // Update global state
250+ globalTasks[taskIndex] = task;
251+
252+ // More side effects - project update
253+ if (task.projectId) {
254+ const project = globalProjects.find((p) => p.id === task.projectId);
255+ if (project) {
256+ const projectTasks = globalTasks.filter(
257+ (t) => t.projectId === project.id,
258+ );
259+ project.progress = util.calculateProgress(projectTasks);
260+ project.lastActivity = new Date();
261+ }
262+ }
263+
264+ // Notification side effects
265+ if (updates.assignedTo && updates.assignedTo !== task.assignedTo) {
266+ const assignee = globalUsers.find((u) => u.id === updates.assignedTo);
267+ if (assignee) {
268+ util.sendNotification(
269+ "task_assigned",
270+ `You've been assigned to task: ${task.title}`,
271+ assignee,
272+ );
273+ }
274+ }
275+
276+ util.logger("task_updated", { taskId, changes: Object.keys(updates) });
277+
278+ return task;
279+ }
280+
281+ // Delete task with side effects
282+ deleteTask(taskId: string) {
283+ if (!currentUser) throw new Error("Not authenticated");
284+
285+ const taskIndex = globalTasks.findIndex((t) => t.id === taskId);
286+ if (taskIndex === -1) throw new Error("Task not found");
287+
288+ const task = globalTasks[taskIndex];
289+
290+ // Permission check
291+ if (task.createdBy !== currentUser.id && !currentUser.isAdmin) {
292+ throw new Error("Only the creator or an admin can delete a task");
293+ }
294+
295+ // Side effects before deletion
296+ if (task.projectId) {
297+ const project = globalProjects.find((p) => p.id === task.projectId);
298+ if (project) {
299+ project.taskCount = Math.max(0, (project.taskCount || 0) - 1);
300+ project.lastActivity = new Date();
301+ // More side effects - recalculating metrics
302+ setTimeout(() => {
303+ const projectTasks = globalTasks.filter(
304+ (t) => t.projectId === project.id && t.id !== taskId,
305+ );
306+ project.progress = util.calculateProgress(projectTasks);
307+ }, 0);
308+ }
309+ }
310+
311+ // Global state mutation
312+ globalTasks.splice(taskIndex, 1);
313+
314+ // Notification side effects
315+ if (task.assignedTo !== currentUser.id) {
316+ const assignee = globalUsers.find((u) => u.id === task.assignedTo);
317+ if (assignee) {
318+ util.sendNotification(
319+ "task_deleted",
320+ `A task assigned to you was deleted: ${task.title}`,
321+ assignee,
322+ );
323+ }
324+ }
325+
326+ util.logger("task_deleted", { taskId, title: task.title });
327+
328+ return { success: true };
329+ }
330+
331+ // Search with mixed concerns
332+ searchTasks(criteria: any) {
333+ if (!currentUser) throw new Error("Not authenticated");
334+
335+ // Filtering with complex inline logic
336+ let results = globalTasks.filter((task) => {
337+ // Basic visibility check
338+ const isVisible =
339+ task.createdBy === currentUser.id ||
340+ task.assignedTo === currentUser.id ||
341+ (task.projectId &&
342+ globalProjects.some(
343+ (p) =>
344+ p.id === task.projectId &&
345+ (p.members.includes(currentUser.id) || p.isPublic),
346+ ));
347+
348+ if (!isVisible) return false;
349+
350+ // Apply search criteria
351+ if (criteria.status && task.status !== criteria.status) return false;
352+ if (criteria.priority && task.priority !== criteria.priority)
353+ return false;
354+ if (criteria.assignedTo && task.assignedTo !== criteria.assignedTo)
355+ return false;
356+ if (criteria.projectId && task.projectId !== criteria.projectId)
357+ return false;
358+
359+ // Text search
360+ if (criteria.searchText) {
361+ const searchText = criteria.searchText.toLowerCase();
362+ const matchesTitle = task.title.toLowerCase().includes(searchText);
363+ const matchesDescription = task.description
364+ ?.toLowerCase()
365+ .includes(searchText);
366+ const matchesTags = task.tags?.some((tag: string) =>
367+ tag.toLowerCase().includes(searchText),
368+ );
369+
370+ if (!matchesTitle && !matchesDescription && !matchesTags) return false;
371+ }
372+
373+ // Date filters
374+ if (
375+ criteria.createdAfter &&
376+ new Date(task.createdAt) < new Date(criteria.createdAfter)
377+ )
378+ return false;
379+ if (
380+ criteria.createdBefore &&
381+ new Date(task.createdAt) > new Date(criteria.createdBefore)
382+ )
383+ return false;
384+ if (
385+ criteria.dueBefore &&
386+ task.dueDate &&
387+ new Date(task.dueDate) > new Date(criteria.dueBefore)
388+ )
389+ return false;
390+ if (
391+ criteria.dueAfter &&
392+ task.dueDate &&
393+ new Date(task.dueDate) < new Date(criteria.dueAfter)
394+ )
395+ return false;
396+
397+ return true;
398+ });
399+
400+ // Sorting mixed with filtering
401+ if (criteria.sortBy) {
402+ results.sort((a, b) => {
403+ if (criteria.sortBy === "dueDate") {
404+ if (!a.dueDate) return criteria.sortDir === "asc" ? 1 : -1;
405+ if (!b.dueDate) return criteria.sortDir === "asc" ? -1 : 1;
406+ return criteria.sortDir === "asc"
407+ ? new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime()
408+ : new Date(b.dueDate).getTime() - new Date(a.dueDate).getTime();
409+ }
410+
411+ if (criteria.sortBy === "priority") {
412+ const priorityMap: Record<string, number> = {
413+ high: 3,
414+ medium: 2,
415+ low: 1,
416+ };
417+ return criteria.sortDir === "asc"
418+ ? priorityMap[a.priority] - priorityMap[b.priority]
419+ : priorityMap[b.priority] - priorityMap[a.priority];
420+ }
421+
422+ // Default sort by creation date
423+ return criteria.sortDir === "asc"
424+ ? new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
425+ : new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
426+ });
427+ }
428+
429+ // Pagination mixed with core functionality
430+ if (criteria.limit) {
431+ const page = criteria.page || 1;
432+ const start = (page - 1) * criteria.limit;
433+ results = results.slice(start, start + criteria.limit);
434+ }
435+
436+ util.logger("tasks_searched", { criteria, resultCount: results.length });
437+
438+ return results;
439+ }
440+}
441+
442+// Usage would be like:
443+// const tm = new TaskManager();
444+// tm.createTask({ title: 'Implement login', projectId: 'proj_123', priority: 'high' });
445+// tm.updateTask('task_123', { status: 'in_progress', assignedTo: 'user_456' });
added manual-testing-sandbox/next-edit/next-edit-2-1-sol.ts +142 −0
@@ -0,0 +1,142 @@
1+// A refactored user validation utility following SOLID principles
2+// Solution for next-edit-2-1.ts
3+
4+type UserData = {
5+ id?: number;
6+ name: string;
7+ email: string;
8+ age?: number;
9+ isActive: boolean;
10+};
11+
12+// Define a validation result interface
13+interface ValidationResult {
14+ isValid: boolean;
15+ error?: string;
16+}
17+
18+// Create a validator interface (Interface Segregation Principle)
19+interface Validator {
20+ validate(data: any): ValidationResult;
21+}
22+
23+// Individual validators with single responsibilities (Single Responsibility Principle)
24+class NameValidator implements Validator {
25+ validate(name: string): ValidationResult {
26+ if (name.length < 2) {
27+ return { isValid: false, error: "Name is too short" };
28+ }
29+ return { isValid: true };
30+ }
31+}
32+
33+class EmailValidator implements Validator {
34+ validate(email: string): ValidationResult {
35+ if (!email.includes("@")) {
36+ return { isValid: false, error: "Invalid email format" };
37+ }
38+ return { isValid: true };
39+ }
40+}
41+
42+class AgeValidator implements Validator {
43+ validate(age: number | undefined): ValidationResult {
44+ if (age !== undefined && age < 18) {
45+ return { isValid: false, error: "User must be 18 or older" };
46+ }
47+ return { isValid: true };
48+ }
49+}
50+
51+// Composite validator that uses individual validators (Open/Closed Principle)
52+class UserValidator {
53+ private validators: { [key: string]: Validator } = {
54+ name: new NameValidator(),
55+ email: new EmailValidator(),
56+ age: new AgeValidator(),
57+ };
58+
59+ validate(user: UserData): ValidationResult {
60+ // Validate name
61+ const nameResult = this.validators.name.validate(user.name);
62+ if (!nameResult.isValid) {
63+ return nameResult;
64+ }
65+
66+ // Validate email
67+ const emailResult = this.validators.email.validate(user.email);
68+ if (!emailResult.isValid) {
69+ return emailResult;
70+ }
71+
72+ // Validate age
73+ const ageResult = this.validators.age.validate(user.age);
74+ if (!ageResult.isValid) {
75+ return ageResult;
76+ }
77+
78+ // All validations passed
79+ return { isValid: true };
80+ }
81+}
82+
83+// Example usage
84+const user = {
85+ name: "Jo",
86+ email: "jo.example.com",
87+ age: 25,
88+ isActive: true,
89+};
90+
91+const userValidator = new UserValidator();
92+const result = userValidator.validate(user);
93+
94+if (result.isValid) {
95+ console.log("User is valid");
96+} else {
97+ console.log("Error: " + result.error);
98+}
99+
100+export {
101+ AgeValidator,
102+ EmailValidator,
103+ NameValidator,
104+ UserValidator,
105+ ValidationResult,
106+ Validator,
107+};
108+
109+/*
110+Code Smells:
111+Using global state (validationError variable)
112+Single validation function doing multiple things
113+No clear error handling mechanism
114+Tightly coupled validation logic
115+
116+Fix:
117+1. Single Responsibility Principle (SRP)
118+Created separate validator classes for each validation concern
119+Each validator is responsible for only one type of validation (name, email, age)
120+
121+
122+2. Open/Closed Principle (OCP)
123+The validation system is open for extension (you can add new validators)
124+The core UserValidator class doesn't need to change when adding new validation rules
125+
126+
127+3. Interface Segregation Principle (ISP)
128+Created a clean Validator interface that all validators implement
129+Each validator only needs to implement a single validation method
130+
131+
132+4. Dependency Inversion Principle (DIP)
133+The UserValidator depends on abstractions (the Validator interface)
134+Specific validators are injected into the UserValidator
135+
136+
137+5. Other improvements:
138+Eliminated global state by using return values instead of global variables
139+Created a proper ValidationResult interface for structured error reporting
140+Made the validation logic more modular and testable
141+Each class and function has a clear, single responsibility
142+*/
added manual-testing-sandbox/next-edit/next-edit-2-1.ts +58 −0
@@ -0,0 +1,58 @@
1+// A simple user validation utility with poor organization
2+// Difficulty: 1 - Easy fixes needed
3+
4+type UserData = {
5+ id?: number;
6+ name: string;
7+ email: string;
8+ age?: number;
9+ isActive: boolean;
10+};
11+
12+// Global variable to store error messages
13+let validationError = "";
14+
15+// Function to validate user data
16+function validateUser(data: UserData) {
17+ // Reset error
18+ validationError = "";
19+
20+ // Check name
21+ if (data.name.length < 2) {
22+ validationError = "Name is too short";
23+ return false;
24+ }
25+
26+ // Check email
27+ if (!data.email.includes("@")) {
28+ validationError = "Invalid email format";
29+ return false;
30+ }
31+
32+ // Check age if provided
33+ if (data.age != undefined) {
34+ if (data.age < 18) {
35+ validationError = "User must be 18 or older";
36+ return false;
37+ }
38+ }
39+
40+ // All validations passed
41+ return true;
42+}
43+
44+// Example usage
45+const user = {
46+ name: "Jo",
47+ email: "jo.example.com",
48+ age: 25,
49+ isActive: true,
50+};
51+
52+if (validateUser(user)) {
53+ console.log("User is valid");
54+} else {
55+ console.log("Error: " + validationError);
56+}
57+
58+export { validateUser, validationError };
added manual-testing-sandbox/next-edit/next-edit-3-2-sol.ts +188 −0
@@ -0,0 +1,188 @@
1+// A well-structured todo list manager following SOLID principles
2+// Refactored solution for next-edit-3-2.ts
3+
4+// Define types for better maintainability
5+type Priority = "low" | "medium" | "high";
6+
7+interface Todo {
8+ id: number;
9+ text: string;
10+ completed: boolean;
11+ priority: Priority;
12+}
13+
14+// TodoManager class following Single Responsibility Principle
15+class TodoManager {
16+ private todos: Map<number, Todo> = new Map();
17+ private lastId: number = 0;
18+
19+ // Create a new todo
20+ addTodo(text: string, priority: Priority = "medium"): Todo {
21+ // Input validation
22+ if (!text.trim()) {
23+ throw new Error("Todo text cannot be empty");
24+ }
25+
26+ const newTodo: Todo = {
27+ id: ++this.lastId,
28+ text: text.trim(),
29+ completed: false,
30+ priority,
31+ };
32+
33+ this.todos.set(newTodo.id, newTodo);
34+ return { ...newTodo }; // Return a copy to prevent direct modification
35+ }
36+
37+ // Delete a todo by id
38+ deleteTodo(id: number): boolean {
39+ return this.todos.delete(id);
40+ }
41+
42+ // Toggle todo completion status
43+ toggleTodo(id: number): Todo | null {
44+ const todo = this.todos.get(id);
45+ if (!todo) return null;
46+
47+ const updatedTodo = { ...todo, completed: !todo.completed };
48+ this.todos.set(id, updatedTodo);
49+ return { ...updatedTodo };
50+ }
51+
52+ // Update todo text
53+ updateTodoText(id: number, newText: string): Todo | null {
54+ if (!newText.trim()) {
55+ throw new Error("Todo text cannot be empty");
56+ }
57+
58+ const todo = this.todos.get(id);
59+ if (!todo) return null;
60+
61+ const updatedTodo = { ...todo, text: newText.trim() };
62+ this.todos.set(id, updatedTodo);
63+ return { ...updatedTodo };
64+ }
65+
66+ // Change todo priority
67+ changePriority(id: number, newPriority: Priority): Todo | null {
68+ const todo = this.todos.get(id);
69+ if (!todo) return null;
70+
71+ const updatedTodo = { ...todo, priority: newPriority };
72+ this.todos.set(id, updatedTodo);
73+ return { ...updatedTodo };
74+ }
75+
76+ // Get all todos
77+ getAllTodos(): Todo[] {
78+ return Array.from(this.todos.values()).map((todo) => ({ ...todo }));
79+ }
80+
81+ // Filter todos by various criteria (following Open/Closed Principle)
82+ filterTodos(predicate: (todo: Todo) => boolean): Todo[] {
83+ return this.getAllTodos().filter(predicate);
84+ }
85+
86+ // Helper methods built on top of filterTodos
87+ getCompletedTodos(): Todo[] {
88+ return this.filterTodos((todo) => todo.completed);
89+ }
90+
91+ getActiveTodos(): Todo[] {
92+ return this.filterTodos((todo) => !todo.completed);
93+ }
94+
95+ getTodosByPriority(priority: Priority): Todo[] {
96+ return this.filterTodos((todo) => todo.priority === priority);
97+ }
98+}
99+
100+// Create a singleton instance
101+const todoManager = new TodoManager();
102+
103+// Example usage
104+todoManager.addTodo("Buy groceries", "high");
105+todoManager.addTodo("Clean house");
106+todoManager.addTodo("Pay bills", "high");
107+todoManager.toggleTodo(2);
108+
109+console.log("All todos:", todoManager.getAllTodos());
110+console.log("High priority todos:", todoManager.getTodosByPriority("high"));
111+console.log("Completed todos:", todoManager.getCompletedTodos());
112+
113+// Export the TodoManager class and its instance
114+export { Priority, Todo, TodoManager, todoManager };
115+
116+/*
117+Code Smells in next-edit-3-2.ts:
118+Global state - using global variables for todos and lastId
119+Single Responsibility Principle violation - mixing data management with business logic
120+Duplicated code in several functions that iterate through todos
121+No clear abstraction layers - direct manipulation of the data structure
122+No validation or error handling
123+No proper typing for priority values
124+No encapsulation - direct access to the todos array
125+No use of more efficient data structures (using array iteration instead of maps/objects)
126+
127+Improvements Made in the Refactored Solution:
128+
129+Encapsulation and Data Hiding
130+
131+Created a TodoManager class to encapsulate all operations and data
132+Made todos and lastId private members of the class
133+Used a Map instead of an array for more efficient lookup by id
134+
135+
136+Proper Type Definitions
137+
138+Defined a proper Todo interface
139+Created a union type for Priority with specific allowed values
140+
141+
142+Single Responsibility Principle
143+
144+Each method has a clear, single responsibility
145+Separated data structure management from business logic
146+
147+
148+Open/Closed Principle
149+
150+Introduced a general filterTodos method that accepts a predicate
151+Built specialized filter methods on top of this generic one
152+
153+
154+Data Integrity and Validation
155+
156+Added validation for todo text to prevent empty todos
157+Return copies of todos to prevent direct modification of internal state
158+
159+
160+Reduced Code Duplication
161+
162+Eliminated repeated code for finding todos by id
163+Consolidated filtering logic into a single method
164+
165+
166+Improved Performance
167+
168+Used a Map data structure for O(1) lookups by id instead of O(n) array iterations
169+More efficient todo retrieval and manipulation
170+
171+
172+Better API Design
173+
174+Added more helper methods for common operations
175+Created a consistent interface with descriptive method names
176+Added a method to get all todos instead of directly accessing the array
177+
178+
179+Error Handling
180+
181+Added basic input validation with meaningful error messages
182+
183+
184+Immutability
185+
186+Returned copies of objects rather than references to internal state
187+Used object spread to create new objects when updating
188+*/
added manual-testing-sandbox/next-edit/next-edit-3-2.ts +111 −0
@@ -0,0 +1,111 @@
1+// A poorly structured todo list manager
2+// Difficulty: 2 - Multiple issues to fix
3+
4+// Global variables
5+let todos: {
6+ id: number;
7+ text: string;
8+ completed: boolean;
9+ priority: string;
10+}[] = [];
11+let lastId = 0;
12+
13+// Add a new todo
14+function addTodo(text: string, priority = "medium") {
15+ const newTodo = {
16+ id: ++lastId,
17+ text: text,
18+ completed: false,
19+ priority: priority,
20+ };
21+ todos.push(newTodo);
22+ return newTodo;
23+}
24+
25+// Delete a todo by id
26+function deleteTodo(id: number) {
27+ for (let i = 0; i < todos.length; i++) {
28+ if (todos[i].id === id) {
29+ todos.splice(i, 1);
30+ return true;
31+ }
32+ }
33+ return false;
34+}
35+
36+// Toggle todo completion status
37+function toggleTodo(id: number) {
38+ for (let i = 0; i < todos.length; i++) {
39+ const todo = todos[i];
40+ if (todo.id === id) {
41+ todo.completed = !todo.completed;
42+ return todo;
43+ }
44+ }
45+ return null;
46+}
47+
48+// Update todo text
49+function updateTodoText(id: number, newText: string) {
50+ for (let i = 0; i < todos.length; i++) {
51+ if (todos[i].id === id) {
52+ todos[i].text = newText;
53+ return todos[i];
54+ }
55+ }
56+ return null;
57+}
58+
59+// Change todo priority
60+function changePriority(id: number, newPriority: string) {
61+ for (let i = 0; i < todos.length; i++) {
62+ if (todos[i].id === id) {
63+ todos[i].priority = newPriority;
64+ return todos[i];
65+ }
66+ }
67+ return null;
68+}
69+
70+// Filter todos by status
71+function filterByStatus(completed: boolean) {
72+ const result = [];
73+ for (let i = 0; i < todos.length; i++) {
74+ if (todos[i].completed === completed) {
75+ result.push(todos[i]);
76+ }
77+ }
78+ return result;
79+}
80+
81+// Filter todos by priority
82+function filterByPriority(priority: string) {
83+ const result = [];
84+ for (let i = 0; i < todos.length; i++) {
85+ if (todos[i].priority === priority) {
86+ result.push(todos[i]);
87+ }
88+ }
89+ return result;
90+}
91+
92+// Example usage
93+addTodo("Buy groceries", "high");
94+addTodo("Clean house");
95+addTodo("Pay bills", "high");
96+toggleTodo(2);
97+
98+console.log("All todos:", todos);
99+console.log("High priority todos:", filterByPriority("high"));
100+console.log("Completed todos:", filterByStatus(true));
101+
102+export {
103+ addTodo,
104+ changePriority,
105+ deleteTodo,
106+ filterByPriority,
107+ filterByStatus,
108+ todos,
109+ toggleTodo,
110+ updateTodoText,
111+};
added manual-testing-sandbox/next-edit/next-edit-4-2-sol.ts +323 −0
@@ -0,0 +1,323 @@
1+// Event Tracker System - Refactored Solution
2+// Original: next-edit-4-2.ts
3+// Refactored to follow SOLID principles
4+
5+// Types
6+type EventCategory = "meeting" | "conference" | "workshop" | "other";
7+
8+interface Event {
9+ id: number;
10+ name: string;
11+ date: Date;
12+ attendees: string[];
13+ location?: string;
14+ category?: EventCategory;
15+}
16+
17+// EventRepository - Handles data storage and retrieval
18+class EventRepository {
19+ private events: Event[] = [];
20+ private nextEventId = 1;
21+
22+ getAll(): Event[] {
23+ return [...this.events];
24+ }
25+
26+ getById(eventId: number): Event | undefined {
27+ return this.events.find((event) => event.id === eventId);
28+ }
29+
30+ add(event: Omit<Event, "id">): number {
31+ const newEvent: Event = {
32+ ...event,
33+ id: this.nextEventId++,
34+ };
35+
36+ this.events.push(newEvent);
37+ return newEvent.id;
38+ }
39+
40+ update(eventId: number, eventUpdates: Partial<Omit<Event, "id">>): boolean {
41+ const eventIndex = this.findEventIndex(eventId);
42+ if (eventIndex === -1) return false;
43+
44+ this.events[eventIndex] = {
45+ ...this.events[eventIndex],
46+ ...eventUpdates,
47+ };
48+
49+ return true;
50+ }
51+
52+ remove(eventId: number): boolean {
53+ const eventIndex = this.findEventIndex(eventId);
54+ if (eventIndex === -1) return false;
55+
56+ this.events.splice(eventIndex, 1);
57+ return true;
58+ }
59+
60+ findByDateRange(startDate: Date, endDate: Date): Event[] {
61+ return this.events.filter(
62+ (event) => event.date >= startDate && event.date <= endDate,
63+ );
64+ }
65+
66+ findByCategory(category: EventCategory): Event[] {
67+ return this.events.filter((event) => event.category === category);
68+ }
69+
70+ private findEventIndex(eventId: number): number {
71+ return this.events.findIndex((event) => event.id === eventId);
72+ }
73+}
74+
75+// EventService - Handles business logic
76+class EventService {
77+ constructor(private repository: EventRepository) {}
78+
79+ createEvent(
80+ name: string,
81+ date: Date,
82+ attendees: string[],
83+ location?: string,
84+ category?: EventCategory,
85+ ): number {
86+ return this.repository.add({
87+ name,
88+ date,
89+ attendees,
90+ location,
91+ category,
92+ });
93+ }
94+
95+ updateEvent(eventId: number, updates: Partial<Omit<Event, "id">>): boolean {
96+ return this.repository.update(eventId, updates);
97+ }
98+
99+ removeEvent(eventId: number): boolean {
100+ return this.repository.remove(eventId);
101+ }
102+
103+ addAttendee(eventId: number, attendeeName: string): boolean {
104+ const event = this.repository.getById(eventId);
105+ if (!event) return false;
106+
107+ // Don't add if already exists
108+ if (event.attendees.includes(attendeeName)) {
109+ return false;
110+ }
111+
112+ return this.repository.update(eventId, {
113+ attendees: [...event.attendees, attendeeName],
114+ });
115+ }
116+
117+ removeAttendee(eventId: number, attendeeName: string): boolean {
118+ const event = this.repository.getById(eventId);
119+ if (!event) return false;
120+
121+ const initialCount = event.attendees.length;
122+ const updatedAttendees = event.attendees.filter(
123+ (name) => name !== attendeeName,
124+ );
125+
126+ if (initialCount === updatedAttendees.length) {
127+ return false; // Attendee wasn't in the list
128+ }
129+
130+ return this.repository.update(eventId, {
131+ attendees: updatedAttendees,
132+ });
133+ }
134+
135+ getEventsByDateRange(startDate: Date, endDate: Date): Event[] {
136+ return this.repository.findByDateRange(startDate, endDate);
137+ }
138+
139+ getEventsByCategory(category: EventCategory): Event[] {
140+ return this.repository.findByCategory(category);
141+ }
142+
143+ getAllEvents(): Event[] {
144+ return this.repository.getAll();
145+ }
146+}
147+
148+// Create instances for use
149+const eventRepository = new EventRepository();
150+const eventService = new EventService(eventRepository);
151+
152+// Example usage
153+eventService.createEvent(
154+ "Team Meeting",
155+ new Date("2023-06-15T10:00:00"),
156+ ["Alice", "Bob", "Charlie"],
157+ "Conference Room A",
158+ "meeting",
159+);
160+
161+eventService.createEvent(
162+ "JavaScript Workshop",
163+ new Date("2023-06-20T14:00:00"),
164+ ["David", "Eve"],
165+ "Training Center",
166+ "workshop",
167+);
168+
169+console.log("All events:", eventService.getAllEvents());
170+eventService.addAttendee(1, "Frank");
171+console.log("Events after adding Frank:", eventService.getAllEvents());
172+
173+// Export functions with the same interface as the original for backward compatibility
174+export const events = eventService.getAllEvents();
175+
176+export function add_event(
177+ eventName: string,
178+ eventDate: Date,
179+ attendees: string[],
180+ location?: string,
181+ category?: EventCategory,
182+): number {
183+ return eventService.createEvent(
184+ eventName,
185+ eventDate,
186+ attendees,
187+ location,
188+ category,
189+ );
190+}
191+
192+export function removeEvent(eventId: number): boolean {
193+ return eventService.removeEvent(eventId);
194+}
195+
196+export function updateEvent(
197+ eventId: number,
198+ name?: string,
199+ date?: Date,
200+ attendees?: string[],
201+ location?: string,
202+ category?: EventCategory,
203+): boolean {
204+ return eventService.updateEvent(eventId, {
205+ name,
206+ date,
207+ attendees,
208+ location,
209+ category,
210+ });
211+}
212+
213+export function addAttendeeToEvent(
214+ eventId: number,
215+ attendeeName: string,
216+): boolean {
217+ return eventService.addAttendee(eventId, attendeeName);
218+}
219+
220+export function removeAttendeeFromEvent(
221+ eventId: number,
222+ attendeeName: string,
223+): boolean {
224+ return eventService.removeAttendee(eventId, attendeeName);
225+}
226+
227+export function getEventsByDateRange(startDate: Date, endDate: Date): Event[] {
228+ return eventService.getEventsByDateRange(startDate, endDate);
229+}
230+
231+export function getEventsByCategory(category: EventCategory): Event[] {
232+ return eventService.getEventsByCategory(category);
233+}
234+
235+// For direct use of the service in new code
236+export { Event, EventCategory, EventRepository, EventService };
237+
238+/*
239+Code Smells in next-edit-4-2.ts:
240+Violation of Single Responsibility Principle:
241+
242+The code mixes data storage, business logic, and usage in one flat file
243+Global state management with events array and nextEventId variable
244+Poor Encapsulation:
245+
246+Direct manipulation of the global events array
247+No protection against external modification of data
248+Inconsistent Naming Conventions:
249+
250+Mix of snake_case (add_event) and camelCase (removeEvent)
251+Lack of consistent function naming patterns
252+Duplicated Logic:
253+
254+Repeated event lookup code in multiple functions
255+Multiple loops to find events by ID
256+Inefficient Algorithms:
257+
258+Linear searches through arrays instead of using more efficient methods
259+Manual implementation of array operations that have built-in methods
260+No Separation of Concerns:
261+
262+No distinction between data access and business logic
263+No clear architecture or organization
264+Mutable Shared State:
265+
266+Direct modification of the global events array
267+No immutability principles
268+
269+
270+Improvements Made:
271+
272+Applied SOLID Principles:
273+
274+Single Responsibility: Split into EventRepository (data storage) and EventService (business logic)
275+Open/Closed: Better structure for extending functionality without modifying existing code
276+Interface Segregation: Cleaner interfaces with focused responsibilities
277+Dependency Inversion: Service depends on repository abstraction
278+
279+
280+Improved Encapsulation:
281+
282+Added proper classes with private fields
283+Controlled access to data through methods
284+Immutable return values (using spreads and filters)
285+
286+
287+Consistent Naming:
288+
289+All methods follow camelCase convention
290+More descriptive and consistent naming patterns
291+
292+
293+Removed Duplication:
294+
295+Centralized event lookup in the repository
296+Reused code through proper method calls
297+
298+
299+More Efficient Algorithms:
300+
301+Used built-in array methods (find, filter, etc.) instead of manual loops
302+Simplified attendee management logic
303+
304+
305+Clear Separation of Concerns:
306+
307+Repository handles data access
308+Service handles business logic
309+Maintained backward compatibility with original exports
310+
311+
312+Better Type Definitions:
313+
314+Extracted EventCategory type
315+Used TypeScript features like Partial and Omit for more precise typing
316+Added proper interfaces
317+
318+
319+Maintained Backward Compatibility:
320+
321+Kept original function exports to ensure existing code can work
322+Added additional exports for new usage patterns
323+*/
added manual-testing-sandbox/next-edit/next-edit-4-2.ts +161 −0
@@ -0,0 +1,161 @@
1+// A messy event tracker system
2+// Difficulty: 2 - Multiple issues to fix
3+
4+type Event = {
5+ id: number;
6+ name: string;
7+ date: Date;
8+ attendees: string[];
9+ location?: string;
10+ category?: "meeting" | "conference" | "workshop" | "other";
11+};
12+
13+// Global event store
14+let events: Event[] = [];
15+let nextEventId = 1;
16+
17+// Add event
18+function add_event(
19+ eventName: string,
20+ eventDate: Date,
21+ attendees: string[],
22+ location?: string,
23+ category?: "meeting" | "conference" | "workshop" | "other",
24+) {
25+ const event: Event = {
26+ id: nextEventId++,
27+ name: eventName,
28+ date: eventDate,
29+ attendees: attendees,
30+ location: location,
31+ category: category,
32+ };
33+
34+ events.push(event);
35+ return event.id;
36+}
37+
38+// Remove event
39+function removeEvent(eventId: number) {
40+ let idx = -1;
41+ for (let i = 0; i < events.length; i++) {
42+ if (events[i].id === eventId) {
43+ idx = i;
44+ break;
45+ }
46+ }
47+
48+ if (idx >= 0) {
49+ events.splice(idx, 1);
50+ return true;
51+ }
52+ return false;
53+}
54+
55+// Update event
56+function updateEvent(
57+ eventId: number,
58+ name?: string,
59+ date?: Date,
60+ attendees?: string[],
61+ location?: string,
62+ category?: "meeting" | "conference" | "workshop" | "other",
63+) {
64+ for (let i = 0; i < events.length; i++) {
65+ if (events[i].id === eventId) {
66+ if (name !== undefined) events[i].name = name;
67+ if (date !== undefined) events[i].date = date;
68+ if (attendees !== undefined) events[i].attendees = attendees;
69+ if (location !== undefined) events[i].location = location;
70+ if (category !== undefined) events[i].category = category;
71+ return true;
72+ }
73+ }
74+ return false;
75+}
76+
77+// Add attendee to event
78+function addAttendeeToEvent(eventId: number, attendeeName: string) {
79+ for (let i = 0; i < events.length; i++) {
80+ if (events[i].id === eventId) {
81+ // Check if attendee already exists
82+ let exists = false;
83+ for (let j = 0; j < events[i].attendees.length; j++) {
84+ if (events[i].attendees[j] === attendeeName) {
85+ exists = true;
86+ break;
87+ }
88+ }
89+
90+ if (!exists) {
91+ events[i].attendees.push(attendeeName);
92+ }
93+ return !exists;
94+ }
95+ }
96+ return false;
97+}
98+
99+// Remove attendee from event
100+function removeAttendeeFromEvent(eventId: number, attendeeName: string) {
101+ for (let i = 0; i < events.length; i++) {
102+ if (events[i].id === eventId) {
103+ const initialLength = events[i].attendees.length;
104+ events[i].attendees = events[i].attendees.filter(
105+ (a) => a !== attendeeName,
106+ );
107+ return events[i].attendees.length !== initialLength;
108+ }
109+ }
110+ return false;
111+}
112+
113+// Get events by date range
114+function getEventsByDateRange(startDate: Date, endDate: Date) {
115+ const result = [];
116+ for (let i = 0; i < events.length; i++) {
117+ if (events[i].date >= startDate && events[i].date <= endDate) {
118+ result.push(events[i]);
119+ }
120+ }
121+ return result;
122+}
123+
124+// Get events by category
125+function getEventsByCategory(
126+ category: "meeting" | "conference" | "workshop" | "other",
127+) {
128+ return events.filter((e) => e.category === category);
129+}
130+
131+// Example usage
132+add_event(
133+ "Team Meeting",
134+ new Date("2023-06-15T10:00:00"),
135+ ["Alice", "Bob", "Charlie"],
136+ "Conference Room A",
137+ "meeting",
138+);
139+
140+add_event(
141+ "JavaScript Workshop",
142+ new Date("2023-06-20T14:00:00"),
143+ ["David", "Eve"],
144+ "Training Center",
145+ "workshop",
146+);
147+
148+console.log("All events:", events);
149+addAttendeeToEvent(1, "Frank");
150+console.log("Events after adding Frank:", events);
151+
152+export {
153+ add_event,
154+ addAttendeeToEvent,
155+ events,
156+ getEventsByCategory,
157+ getEventsByDateRange,
158+ removeAttendeeFromEvent,
159+ removeEvent,
160+ updateEvent,
161+};
added manual-testing-sandbox/next-edit/next-edit-5-3-sol.ts +371 −0
@@ -0,0 +1,371 @@
1+// Refactored shopping cart implementation following SOLID principles
2+
3+// Types and interfaces
4+interface Product {
5+ id: number;
6+ name: string;
7+ price: number;
8+ stock: number;
9+ category: string;
10+}
11+
12+interface CartItem {
13+ productId: number;
14+ quantity: number;
15+ price: number;
16+}
17+
18+interface Discount {
19+ percentage: number;
20+ minPurchase: number;
21+ category?: string;
22+}
23+
24+interface UserInfo {
25+ name: string;
26+ email: string;
27+ address?: Address;
28+}
29+
30+interface Address {
31+ street: string;
32+ city: string;
33+ zipCode: string;
34+ country: string;
35+}
36+
37+interface CartSummary {
38+ items: CartItem[];
39+ total: number;
40+ discountCode: string | null;
41+ user: UserInfo | null;
42+}
43+
44+// Product catalog
45+const PRODUCTS: Record<number, Product> = {
46+ 1: {
47+ id: 1,
48+ name: "Laptop",
49+ price: 999.99,
50+ stock: 10,
51+ category: "electronics",
52+ },
53+ 2: {
54+ id: 2,
55+ name: "Smartphone",
56+ price: 699.99,
57+ stock: 15,
58+ category: "electronics",
59+ },
60+ 3: {
61+ id: 3,
62+ name: "Headphones",
63+ price: 149.99,
64+ stock: 20,
65+ category: "electronics",
66+ },
67+ 4: { id: 4, name: "Desk", price: 249.99, stock: 5, category: "furniture" },
68+ 5: { id: 5, name: "Chair", price: 179.99, stock: 8, category: "furniture" },
69+};
70+
71+// Discount codes
72+const DISCOUNT_CODES: Record<string, Discount> = {
73+ SAVE10: { percentage: 10, minPurchase: 0 },
74+ SAVE20: { percentage: 20, minPurchase: 500 },
75+ FURNITURE15: { percentage: 15, minPurchase: 0, category: "furniture" },
76+};
77+
78+// Shopping cart class that follows Single Responsibility Principle
79+class ShoppingCart {
80+ private items: CartItem[] = [];
81+ private total: number = 0;
82+ private discountCode: string | null = null;
83+ private userInfo: UserInfo | null = null;
84+
85+ // Add product to cart
86+ public addToCart(productId: number, quantity: number = 1): boolean {
87+ // Check if product exists
88+ if (!PRODUCTS[productId]) {
89+ console.error("Product not found!");
90+ return false;
91+ }
92+
93+ // Check if enough stock
94+ if (PRODUCTS[productId].stock < quantity) {
95+ console.error("Not enough stock!");
96+ return false;
97+ }
98+
99+ // Check if product already in cart
100+ const existingItemIndex = this.findItemIndex(productId);
101+
102+ if (existingItemIndex !== -1) {
103+ // Update quantity if product already in cart
104+ this.items[existingItemIndex].quantity += quantity;
105+ } else {
106+ // Add new item if not already in cart
107+ this.items.push({
108+ productId,
109+ quantity,
110+ price: PRODUCTS[productId].price,
111+ });
112+ }
113+
114+ // Update stock
115+ PRODUCTS[productId].stock -= quantity;
116+
117+ // Recalculate cart total
118+ this.calculateCartTotal();
119+
120+ return true;
121+ }
122+
123+ // Remove product from cart
124+ public removeFromCart(productId: number, quantity: number = 1): boolean {
125+ const itemIndex = this.findItemIndex(productId);
126+
127+ if (itemIndex === -1) {
128+ console.error("Product not in cart!");
129+ return false;
130+ }
131+
132+ const item = this.items[itemIndex];
133+
134+ // Determine quantity to remove
135+ const qtyToRemove = Math.min(item.quantity, quantity);
136+
137+ // Return stock
138+ PRODUCTS[productId].stock += qtyToRemove;
139+
140+ // Update cart item
141+ item.quantity -= qtyToRemove;
142+
143+ // Remove item if quantity is 0
144+ if (item.quantity === 0) {
145+ this.items.splice(itemIndex, 1);
146+ }
147+
148+ // Recalculate cart total
149+ this.calculateCartTotal();
150+
151+ return true;
152+ }
153+
154+ // Calculate cart total
155+ public calculateCartTotal(): number {
156+ let total = this.calculateSubtotal();
157+
158+ // Apply discount if any
159+ if (this.discountCode) {
160+ total = this.applyDiscountToTotal(total);
161+ }
162+
163+ this.total = total;
164+ return this.total;
165+ }
166+
167+ // Calculate subtotal without discounts
168+ private calculateSubtotal(): number {
169+ return this.items.reduce(
170+ (sum, item) => sum + item.price * item.quantity,
171+ 0,
172+ );
173+ }
174+
175+ // Apply discount to total
176+ private applyDiscountToTotal(total: number): number {
177+ if (!this.discountCode) return total;
178+
179+ const discount = DISCOUNT_CODES[this.discountCode];
180+
181+ // Check if discount applies to specific category
182+ if (discount.category) {
183+ return this.applyCategoryDiscount(total, discount);
184+ } else {
185+ // Apply discount to entire cart
186+ const discountAmount = total * (discount.percentage / 100);
187+ return total - discountAmount;
188+ }
189+ }
190+
191+ // Apply category-specific discount
192+ private applyCategoryDiscount(total: number, discount: Discount): number {
193+ let categoryTotal = 0;
194+
195+ for (const item of this.items) {
196+ if (PRODUCTS[item.productId].category === discount.category) {
197+ categoryTotal += item.price * item.quantity;
198+ }
199+ }
200+
201+ // Apply discount to category total
202+ const discountAmount = categoryTotal * (discount.percentage / 100);
203+ return total - discountAmount;
204+ }
205+
206+ // Apply discount code
207+ public applyDiscountCode(code: string): boolean {
208+ // Check if discount code exists
209+ if (!DISCOUNT_CODES[code]) {
210+ console.error("Invalid discount code!");
211+ return false;
212+ }
213+
214+ const discount = DISCOUNT_CODES[code];
215+
216+ // Check minimum purchase requirement
217+ if (this.total < discount.minPurchase) {
218+ console.error(
219+ `Minimum purchase of $${discount.minPurchase} required for this code!`,
220+ );
221+ return false;
222+ }
223+
224+ // Apply discount code
225+ this.discountCode = code;
226+
227+ // Recalculate total
228+ this.calculateCartTotal();
229+
230+ return true;
231+ }
232+
233+ // Set user information
234+ public setUserInfo(name: string, email: string, address?: Address): boolean {
235+ this.userInfo = { name, email, address };
236+ return true;
237+ }
238+
239+ // Find item index in cart
240+ private findItemIndex(productId: number): number {
241+ return this.items.findIndex((item) => item.productId === productId);
242+ }
243+
244+ // Checkout
245+ public checkout(): boolean {
246+ // Validate cart
247+ if (this.items.length === 0) {
248+ console.error("Cart is empty!");
249+ return false;
250+ }
251+
252+ // Validate user info
253+ if (!this.userInfo || !this.userInfo.name || !this.userInfo.email) {
254+ console.error("User information incomplete!");
255+ return false;
256+ }
257+
258+ // Process payment (simplified)
259+ console.log("Processing payment for $" + this.total);
260+ console.log("Items:", this.items);
261+ console.log("User:", this.userInfo);
262+
263+ // Clear cart after successful checkout
264+ this.clearCart();
265+
266+ return true;
267+ }
268+
269+ // Clear cart
270+ private clearCart(): void {
271+ this.items = [];
272+ this.total = 0;
273+ this.discountCode = null;
274+ }
275+
276+ // Get cart summary
277+ public getCartSummary(): CartSummary {
278+ return {
279+ items: [...this.items], // Return a copy to prevent direct mutation
280+ total: this.total,
281+ discountCode: this.discountCode,
282+ user: this.userInfo,
283+ };
284+ }
285+}
286+
287+// Create cart instance
288+const cart = new ShoppingCart();
289+
290+// Example usage
291+cart.addToCart(1, 2); // Add 2 laptops
292+cart.addToCart(3, 1); // Add 1 headphones
293+cart.applyDiscountCode("SAVE10");
294+cart.setUserInfo("John Doe", "john@example.com", {
295+ street: "123 Main St",
296+ city: "Anytown",
297+ zipCode: "12345",
298+ country: "USA",
299+});
300+
301+console.log(cart.getCartSummary());
302+
303+// Export for module usage
304+export {
305+ Address,
306+ cart,
307+ CartItem,
308+ CartSummary,
309+ Discount,
310+ DISCOUNT_CODES,
311+ Product,
312+ PRODUCTS,
313+ ShoppingCart,
314+ UserInfo,
315+};
316+
317+/*
318+Code Smells in the Original File
319+Global State: The code uses global variables for cart state, making it difficult to track changes and prone to side effects.
320+
321+Lack of Encapsulation: Data and functions are not properly encapsulated, allowing direct manipulation of state from anywhere.
322+
323+No Type Definitions: Lack of proper TypeScript interfaces for the domain entities.
324+
325+Procedural Code: Functions operating on global state rather than object-oriented approach.
326+
327+Poor Data Structure Access: Using for loops with indexes instead of more expressive array methods.
328+
329+Mixed Responsibilities: Functions are handling multiple concerns (validation, business logic, data modification).
330+
331+Duplicated Logic: Same validation and calculation logic repeated in multiple places.
332+
333+No Clear Separation of Concerns: Business logic mixed with presentation logic (console logs).
334+
335+No Protection Against Direct Mutation: The cart data can be modified directly.
336+
337+
338+Improvements Made
339+
340+Created a Class-Based Design: Encapsulated cart functionality in a ShoppingCart class
341+
342+Added Strong Typing: Defined interfaces for all domain entities (Product, CartItem, Discount, UserInfo, Address, CartSummary)
343+
344+Single Responsibility Principle: Separated methods for different concerns (e.g., split discount calculation into multiple methods)
345+
346+Encapsulation: Made cart items and state private, only accessible through methods
347+
348+Immutability: Return copies of data structures to prevent external modification
349+
350+Modern JavaScript/TypeScript Patterns:
351+
352+Used array methods like reduce, findIndex instead of for loops
353+Used parameter defaults, array spread operators
354+
355+
356+Better Method Organization:
357+
358+Split large methods into smaller, focused ones
359+Created private helper methods for internal operations
360+
361+
362+Improved Validation: Centralized validation logic in appropriate methods
363+
364+Better Error Handling: Consistent error reporting approach
365+
366+Code Reusability: Extracted reusable logic into dedicated methods
367+
368+Defensive Programming: Added checks to prevent invalid operations
369+
370+Cleaner API Design: Created a clear public interface for the cart functionality
371+*/
added manual-testing-sandbox/next-edit/next-edit-5-3.ts +262 −0
@@ -0,0 +1,262 @@
1+// A disorganized shopping cart implementation
2+// Difficulty: 3 - Moderate refactoring needed
3+
4+// Product catalog
5+const PRODUCTS = {
6+ 1: {
7+ id: 1,
8+ name: "Laptop",
9+ price: 999.99,
10+ stock: 10,
11+ category: "electronics",
12+ },
13+ 2: {
14+ id: 2,
15+ name: "Smartphone",
16+ price: 699.99,
17+ stock: 15,
18+ category: "electronics",
19+ },
20+ 3: {
21+ id: 3,
22+ name: "Headphones",
23+ price: 149.99,
24+ stock: 20,
25+ category: "electronics",
26+ },
27+ 4: { id: 4, name: "Desk", price: 249.99, stock: 5, category: "furniture" },
28+ 5: { id: 5, name: "Chair", price: 179.99, stock: 8, category: "furniture" },
29+};
30+
31+// Discount codes
32+const DISCOUNT_CODES = {
33+ SAVE10: { percentage: 10, minPurchase: 0 },
34+ SAVE20: { percentage: 20, minPurchase: 500 },
35+ FURNITURE15: { percentage: 15, minPurchase: 0, category: "furniture" },
36+};
37+
38+// Cart state
39+let cartItems: { productId: number; quantity: number; price: number }[] = [];
40+let cartTotal = 0;
41+let appliedDiscountCode: string | null = null;
42+
43+// User info
44+let userInfo: {
45+ name: string;
46+ email: string;
47+ address?: {
48+ street: string;
49+ city: string;
50+ zipCode: string;
51+ country: string;
52+ };
53+} | null = null;
54+
55+// Add product to cart
56+function addToCart(productId: number, quantity: number = 1) {
57+ // Check if product exists
58+ if (!PRODUCTS[productId]) {
59+ console.error("Product not found!");
60+ return false;
61+ }
62+
63+ // Check if enough stock
64+ if (PRODUCTS[productId].stock < quantity) {
65+ console.error("Not enough stock!");
66+ return false;
67+ }
68+
69+ // Check if product already in cart
70+ let existingItem = false;
71+ for (let i = 0; i < cartItems.length; i++) {
72+ if (cartItems[i].productId === productId) {
73+ // Update quantity
74+ cartItems[i].quantity += quantity;
75+ existingItem = true;
76+ break;
77+ }
78+ }
79+
80+ // Add new item if not already in cart
81+ if (!existingItem) {
82+ cartItems.push({
83+ productId,
84+ quantity,
85+ price: PRODUCTS[productId].price,
86+ });
87+ }
88+
89+ // Update stock
90+ PRODUCTS[productId].stock -= quantity;
91+
92+ // Recalculate cart total
93+ calculateCartTotal();
94+
95+ return true;
96+}
97+
98+// Remove product from cart
99+function removeFromCart(productId: number, quantity: number = 1) {
100+ for (let i = 0; i < cartItems.length; i++) {
101+ if (cartItems[i].productId === productId) {
102+ // Determine quantity to remove
103+ const qtyToRemove = Math.min(cartItems[i].quantity, quantity);
104+
105+ // Return stock
106+ PRODUCTS[productId].stock += qtyToRemove;
107+
108+ // Update cart item
109+ cartItems[i].quantity -= qtyToRemove;
110+
111+ // Remove item if quantity is 0
112+ if (cartItems[i].quantity === 0) {
113+ cartItems.splice(i, 1);
114+ }
115+
116+ // Recalculate cart total
117+ calculateCartTotal();
118+
119+ return true;
120+ }
121+ }
122+
123+ console.error("Product not in cart!");
124+ return false;
125+}
126+
127+// Calculate cart total
128+function calculateCartTotal() {
129+ let total = 0;
130+
131+ // Sum all items
132+ for (let i = 0; i < cartItems.length; i++) {
133+ const item = cartItems[i];
134+ total += item.price * item.quantity;
135+ }
136+
137+ // Apply discount if any
138+ if (appliedDiscountCode) {
139+ const discount = DISCOUNT_CODES[appliedDiscountCode];
140+
141+ // Check if discount applies to specific category
142+ if (discount.category) {
143+ let categoryTotal = 0;
144+ for (let i = 0; i < cartItems.length; i++) {
145+ const item = cartItems[i];
146+ if (PRODUCTS[item.productId].category === discount.category) {
147+ categoryTotal += item.price * item.quantity;
148+ }
149+ }
150+
151+ // Apply discount to category total
152+ const discountAmount = categoryTotal * (discount.percentage / 100);
153+ total -= discountAmount;
154+ } else {
155+ // Apply discount to entire cart
156+ const discountAmount = total * (discount.percentage / 100);
157+ total -= discountAmount;
158+ }
159+ }
160+
161+ cartTotal = total;
162+ return cartTotal;
163+}
164+
165+// Apply discount code
166+function applyDiscountCode(code: string) {
167+ // Check if discount code exists
168+ if (!DISCOUNT_CODES[code]) {
169+ console.error("Invalid discount code!");
170+ return false;
171+ }
172+
173+ const discount = DISCOUNT_CODES[code];
174+
175+ // Check minimum purchase requirement
176+ if (cartTotal < discount.minPurchase) {
177+ console.error(
178+ `Minimum purchase of $${discount.minPurchase} required for this code!`,
179+ );
180+ return false;
181+ }
182+
183+ // Apply discount code
184+ appliedDiscountCode = code;
185+
186+ // Recalculate total
187+ calculateCartTotal();
188+
189+ return true;
190+}
191+
192+// Set user information
193+function setUserInfo(
194+ name: string,
195+ email: string,
196+ address?: { street: string; city: string; zipCode: string; country: string },
197+) {
198+ userInfo = { name, email, address };
199+ return true;
200+}
201+
202+// Checkout
203+function checkout() {
204+ // Validate cart
205+ if (cartItems.length === 0) {
206+ console.error("Cart is empty!");
207+ return false;
208+ }
209+
210+ // Validate user info
211+ if (!userInfo || !userInfo.name || !userInfo.email) {
212+ console.error("User information incomplete!");
213+ return false;
214+ }
215+
216+ // Process payment (simplified)
217+ console.log("Processing payment for $" + cartTotal);
218+ console.log("Items:", cartItems);
219+ console.log("User:", userInfo);
220+
221+ // Clear cart after successful checkout
222+ cartItems = [];
223+ cartTotal = 0;
224+ appliedDiscountCode = null;
225+
226+ return true;
227+}
228+
229+// Get cart summary
230+function getCartSummary() {
231+ return {
232+ items: cartItems,
233+ total: cartTotal,
234+ discountCode: appliedDiscountCode,
235+ user: userInfo,
236+ };
237+}
238+
239+// Example usage
240+addToCart(1, 2); // Add 2 laptops
241+addToCart(3, 1); // Add 1 headphones
242+applyDiscountCode("SAVE10");
243+setUserInfo("John Doe", "john@example.com", {
244+ street: "123 Main St",
245+ city: "Anytown",
246+ zipCode: "12345",
247+ country: "USA",
248+});
249+
250+console.log(getCartSummary());
251+
252+export {
253+ addToCart,
254+ applyDiscountCode,
255+ calculateCartTotal,
256+ checkout,
257+ DISCOUNT_CODES,
258+ getCartSummary,
259+ PRODUCTS,
260+ removeFromCart,
261+ setUserInfo,
262+};
added manual-testing-sandbox/next-edit/next-edit-6-3-sol.ts +668 −0
@@ -0,0 +1,668 @@
1+// Refactored file upload and management system following SOLID principles
2+// Original: next-edit-6-3.ts
3+
4+// Types
5+interface FileData {
6+ id: string;
7+ name: string;
8+ size: number;
9+ type: string;
10+ uploadDate: Date;
11+ uploadedBy: string;
12+ path: string;
13+ isPublic: boolean;
14+ tags?: string[];
15+ metadata?: Record<string, any>;
16+}
17+
18+interface User {
19+ id: string;
20+ name: string;
21+ email: string;
22+ role: "admin" | "user" | "guest";
23+}
24+
25+interface FileQuery {
26+ name?: string;
27+ type?: string;
28+ tags?: string[];
29+ uploadedBy?: string;
30+ isPublic?: boolean;
31+ minSize?: number;
32+ maxSize?: number;
33+ uploadedAfter?: Date;
34+ uploadedBefore?: Date;
35+}
36+
37+interface FileMetadataUpdate {
38+ name?: string;
39+ isPublic?: boolean;
40+ tags?: string[];
41+ metadata?: Record<string, any>;
42+}
43+
44+interface StorageStats {
45+ used: number;
46+ total: number;
47+ available: number;
48+ fileCount: number;
49+}
50+
51+// Constants
52+const MAX_STORAGE = 1024 * 1024 * 1024; // 1GB
53+const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
54+
55+// User Management
56+class UserManager {
57+ private users: Record<string, User>;
58+ private currentUser: string | null = null;
59+
60+ constructor(initialUsers: Record<string, User> = {}) {
61+ this.users = initialUsers;
62+ }
63+
64+ login(userId: string): boolean {
65+ if (this.users[userId]) {
66+ this.currentUser = userId;
67+ console.log(`Logged in as ${this.users[userId].name}`);
68+ return true;
69+ } else {
70+ console.error("User not found");
71+ return false;
72+ }
73+ }
74+
75+ logout(): boolean {
76+ this.currentUser = null;
77+ console.log("Logged out");
78+ return true;
79+ }
80+
81+ getCurrentUser(): string | null {
82+ return this.currentUser;
83+ }
84+
85+ getUser(userId: string): User | null {
86+ return this.users[userId] || null;
87+ }
88+
89+ getCurrentUserData(): User | null {
90+ return this.currentUser ? this.users[this.currentUser] : null;
91+ }
92+
93+ userExists(userId: string): boolean {
94+ return !!this.users[userId];
95+ }
96+}
97+
98+// File Storage Management
99+class FileStorageManager {
100+ private fileStorage: Record<string, FileData> = {};
101+ private storageUsed = 0;
102+ private readonly maxStorage: number;
103+ private readonly maxFileSize: number;
104+ private userManager: UserManager;
105+
106+ constructor(
107+ userManager: UserManager,
108+ maxStorage = MAX_STORAGE,
109+ maxFileSize = MAX_FILE_SIZE,
110+ ) {
111+ this.userManager = userManager;
112+ this.maxStorage = maxStorage;
113+ this.maxFileSize = maxFileSize;
114+ }
115+
116+ uploadFile(
117+ fileName: string,
118+ fileSize: number,
119+ fileType: string,
120+ isPublic = false,
121+ tags: string[] = [],
122+ metadata: Record<string, any> = {},
123+ ): string | false {
124+ const currentUser = this.userManager.getCurrentUser();
125+
126+ // Check if user is logged in
127+ if (!currentUser) {
128+ console.error("User not logged in");
129+ return false;
130+ }
131+
132+ // Check file size
133+ if (!this.validateFileSize(fileSize)) {
134+ return false;
135+ }
136+
137+ // Check available storage
138+ if (!this.hasEnoughStorage(fileSize)) {
139+ return false;
140+ }
141+
142+ // Generate file data
143+ const fileId = this.generateFileId();
144+ const path = this.createFilePath(currentUser, fileId, fileName);
145+ const fileData: FileData = {
146+ id: fileId,
147+ name: fileName,
148+ size: fileSize,
149+ type: fileType,
150+ uploadDate: new Date(),
151+ uploadedBy: currentUser,
152+ path,
153+ isPublic,
154+ tags,
155+ metadata,
156+ };
157+
158+ // Save file and update storage
159+ this.fileStorage[fileId] = fileData;
160+ this.storageUsed += fileSize;
161+
162+ console.log(`File ${fileName} uploaded successfully`);
163+ return fileId;
164+ }
165+
166+ deleteFile(fileId: string): boolean {
167+ const currentUser = this.userManager.getCurrentUser();
168+ const currentUserData = this.userManager.getCurrentUserData();
169+
170+ // Check if user is logged in
171+ if (!currentUser || !currentUserData) {
172+ console.error("User not logged in");
173+ return false;
174+ }
175+
176+ // Check if file exists
177+ const file = this.getFileById(fileId);
178+ if (!file) {
179+ console.error("File not found");
180+ return false;
181+ }
182+
183+ // Check permissions
184+ if (!this.canModifyFile(file, currentUser, currentUserData.role)) {
185+ console.error("Permission denied");
186+ return false;
187+ }
188+
189+ // Update storage and remove file
190+ this.storageUsed -= file.size;
191+ delete this.fileStorage[fileId];
192+
193+ console.log(`File ${file.name} deleted successfully`);
194+ return true;
195+ }
196+
197+ updateFileMetadata(fileId: string, updates: FileMetadataUpdate): boolean {
198+ const currentUser = this.userManager.getCurrentUser();
199+ const currentUserData = this.userManager.getCurrentUserData();
200+
201+ // Check if user is logged in
202+ if (!currentUser || !currentUserData) {
203+ console.error("User not logged in");
204+ return false;
205+ }
206+
207+ // Check if file exists
208+ const file = this.getFileById(fileId);
209+ if (!file) {
210+ console.error("File not found");
211+ return false;
212+ }
213+
214+ // Check permissions
215+ if (!this.canModifyFile(file, currentUser, currentUserData.role)) {
216+ console.error("Permission denied");
217+ return false;
218+ }
219+
220+ // Update file data
221+ if (updates.name !== undefined)
222+ this.fileStorage[fileId].name = updates.name;
223+ if (updates.isPublic !== undefined)
224+ this.fileStorage[fileId].isPublic = updates.isPublic;
225+ if (updates.tags !== undefined)
226+ this.fileStorage[fileId].tags = updates.tags;
227+ if (updates.metadata !== undefined) {
228+ this.fileStorage[fileId].metadata = {
229+ ...this.fileStorage[fileId].metadata,
230+ ...updates.metadata,
231+ };
232+ }
233+
234+ console.log(`File ${file.name} updated successfully`);
235+ return true;
236+ }
237+
238+ getFileData(fileId: string): FileData | null {
239+ // Check if file exists
240+ const file = this.getFileById(fileId);
241+ if (!file) {
242+ console.error("File not found");
243+ return null;
244+ }
245+
246+ const currentUser = this.userManager.getCurrentUser();
247+ const currentUserData = this.userManager.getCurrentUserData();
248+
249+ // Check if user has permission to access
250+ if (
251+ !file.isPublic &&
252+ currentUser !== file.uploadedBy &&
253+ currentUserData?.role !== "admin" &&
254+ !this.isSharedWithUser(file, currentUser)
255+ ) {
256+ console.error("Permission denied");
257+ return null;
258+ }
259+
260+ return file;
261+ }
262+
263+ searchFiles(query: FileQuery): FileData[] {
264+ const currentUser = this.userManager.getCurrentUser();
265+ const currentUserData = this.userManager.getCurrentUserData();
266+
267+ // Check if user is logged in
268+ if (!currentUser || !currentUserData) {
269+ console.error("User not logged in");
270+ return [];
271+ }
272+
273+ const results: FileData[] = [];
274+
275+ // Filter files
276+ for (const fileId in this.fileStorage) {
277+ const file = this.fileStorage[fileId];
278+
279+ // Skip files user doesn't have access to
280+ if (
281+ !file.isPublic &&
282+ file.uploadedBy !== currentUser &&
283+ currentUserData.role !== "admin" &&
284+ !this.isSharedWithUser(file, currentUser)
285+ ) {
286+ continue;
287+ }
288+
289+ if (this.matchesQuery(file, query)) {
290+ results.push(file);
291+ }
292+ }
293+
294+ return results;
295+ }
296+
297+ getStorageStats(): StorageStats {
298+ return {
299+ used: this.storageUsed,
300+ total: this.maxStorage,
301+ available: this.maxStorage - this.storageUsed,
302+ fileCount: Object.keys(this.fileStorage).length,
303+ };
304+ }
305+
306+ shareFile(fileId: string, targetUserId: string): boolean {
307+ const currentUser = this.userManager.getCurrentUser();
308+ const currentUserData = this.userManager.getCurrentUserData();
309+
310+ // Check if user is logged in
311+ if (!currentUser || !currentUserData) {
312+ console.error("User not logged in");
313+ return false;
314+ }
315+
316+ // Check if file exists
317+ const file = this.getFileById(fileId);
318+ if (!file) {
319+ console.error("File not found");
320+ return false;
321+ }
322+
323+ // Check if target user exists
324+ if (!this.userManager.userExists(targetUserId)) {
325+ console.error("Target user not found");
326+ return false;
327+ }
328+
329+ // Check if user has permission
330+ if (!this.canModifyFile(file, currentUser, currentUserData.role)) {
331+ console.error("Permission denied");
332+ return false;
333+ }
334+
335+ // Share file by adding metadata
336+ if (!file.metadata) {
337+ file.metadata = {};
338+ }
339+
340+ if (!file.metadata.sharedWith) {
341+ file.metadata.sharedWith = [];
342+ }
343+
344+ // Check if already shared
345+ if (!file.metadata.sharedWith.includes(targetUserId)) {
346+ file.metadata.sharedWith.push(targetUserId);
347+ }
348+
349+ const targetUser = this.userManager.getUser(targetUserId);
350+ console.log(`File ${file.name} shared with ${targetUser?.name}`);
351+ return true;
352+ }
353+
354+ // Helper methods
355+ private generateFileId(): string {
356+ return "file_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
357+ }
358+
359+ private createFilePath(
360+ userId: string,
361+ fileId: string,
362+ fileName: string,
363+ ): string {
364+ return `/storage/${userId}/${fileId}_${fileName}`;
365+ }
366+
367+ private getFileById(fileId: string): FileData | null {
368+ return this.fileStorage[fileId] || null;
369+ }
370+
371+ private validateFileSize(fileSize: number): boolean {
372+ if (fileSize > this.maxFileSize) {
373+ console.error(
374+ `File too large. Maximum size is ${this.maxFileSize / (1024 * 1024)}MB`,
375+ );
376+ return false;
377+ }
378+ return true;
379+ }
380+
381+ private hasEnoughStorage(fileSize: number): boolean {
382+ if (this.storageUsed + fileSize > this.maxStorage) {
383+ console.error("Not enough storage space");
384+ return false;
385+ }
386+ return true;
387+ }
388+
389+ private canModifyFile(
390+ file: FileData,
391+ userId: string,
392+ userRole: string,
393+ ): boolean {
394+ return file.uploadedBy === userId || userRole === "admin";
395+ }
396+
397+ private isSharedWithUser(file: FileData, userId: string | null): boolean {
398+ if (!userId) return false;
399+ return !!file.metadata?.sharedWith?.includes(userId);
400+ }
401+
402+ private matchesQuery(file: FileData, query: FileQuery): boolean {
403+ // Name filter
404+ if (
405+ query.name &&
406+ !file.name.toLowerCase().includes(query.name.toLowerCase())
407+ ) {
408+ return false;
409+ }
410+
411+ // Type filter
412+ if (query.type && file.type !== query.type) {
413+ return false;
414+ }
415+
416+ // Upload user filter
417+ if (query.uploadedBy && file.uploadedBy !== query.uploadedBy) {
418+ return false;
419+ }
420+
421+ // Public/private filter
422+ if (query.isPublic !== undefined && file.isPublic !== query.isPublic) {
423+ return false;
424+ }
425+
426+ // Size range filter
427+ if (query.minSize !== undefined && file.size < query.minSize) {
428+ return false;
429+ }
430+ if (query.maxSize !== undefined && file.size > query.maxSize) {
431+ return false;
432+ }
433+
434+ // Date range filter
435+ if (query.uploadedAfter && file.uploadDate < query.uploadedAfter) {
436+ return false;
437+ }
438+ if (query.uploadedBefore && file.uploadDate > query.uploadedBefore) {
439+ return false;
440+ }
441+
442+ // Tags filter
443+ if (query.tags && query.tags.length > 0) {
444+ if (!file.tags) {
445+ return false;
446+ } else {
447+ for (const tag of query.tags) {
448+ if (!file.tags.includes(tag)) {
449+ return false;
450+ }
451+ }
452+ }
453+ }
454+
455+ return true;
456+ }
457+
458+ // For testing/export purposes
459+ getFileStorage(): Record<string, FileData> {
460+ return this.fileStorage;
461+ }
462+}
463+
464+// Demo Application
465+// Initialize system with users
466+const initialUsers: Record<string, User> = {
467+ user1: {
468+ id: "user1",
469+ name: "Admin User",
470+ email: "admin@example.com",
471+ role: "admin",
472+ },
473+ user2: {
474+ id: "user2",
475+ name: "Regular User",
476+ email: "user@example.com",
477+ role: "user",
478+ },
479+ user3: {
480+ id: "user3",
481+ name: "Guest User",
482+ email: "guest@example.com",
483+ role: "guest",
484+ },
485+};
486+
487+// Create system instances
488+const userManager = new UserManager(initialUsers);
489+const fileManager = new FileStorageManager(userManager);
490+
491+// Example usage
492+userManager.login("user1");
493+const fileId = fileManager.uploadFile(
494+ "document.pdf",
495+ 1024 * 1024,
496+ "application/pdf",
497+ false,
498+ ["important", "document"],
499+);
500+fileManager.updateFileMetadata(fileId as string, { isPublic: true });
501+fileManager.shareFile(fileId as string, "user2");
502+console.log(fileManager.getFileData(fileId as string));
503+console.log(fileManager.getStorageStats());
504+userManager.logout();
505+
506+// Exported API for backward compatibility
507+export const fileStorage = fileManager.getFileStorage();
508+export const users = initialUsers;
509+export function login(userId: string): boolean {
510+ return userManager.login(userId);
511+}
512+export function logout(): boolean {
513+ return userManager.logout();
514+}
515+export function uploadFile(
516+ fileName: string,
517+ fileSize: number,
518+ fileType: string,
519+ isPublic = false,
520+ tags: string[] = [],
521+ metadata: Record<string, any> = {},
522+): string | false {
523+ return fileManager.uploadFile(
524+ fileName,
525+ fileSize,
526+ fileType,
527+ isPublic,
528+ tags,
529+ metadata,
530+ );
531+}
532+export function deleteFile(fileId: string): boolean {
533+ return fileManager.deleteFile(fileId);
534+}
535+export function updateFileMetadata(
536+ fileId: string,
537+ updates: FileMetadataUpdate,
538+): boolean {
539+ return fileManager.updateFileMetadata(fileId, updates);
540+}
541+export function getFileData(fileId: string): FileData | null {
542+ return fileManager.getFileData(fileId);
543+}
544+export function searchFiles(query: FileQuery): FileData[] {
545+ return fileManager.searchFiles(query);
546+}
547+export function getStorageStats(): StorageStats {
548+ return fileManager.getStorageStats();
549+}
550+export function shareFile(fileId: string, targetUserId: string): boolean {
551+ return fileManager.shareFile(fileId, targetUserId);
552+}
553+
554+export {
555+ FileData,
556+ FileMetadataUpdate,
557+ FileQuery,
558+ FileStorageManager,
559+ StorageStats,
560+ User,
561+ UserManager,
562+};
563+
564+/*
565+Code Smells in the Original File (next-edit-6-3.ts)
566+
567+Violation of Single Responsibility Principle (SRP):
568+
569+The code mixed user management, file storage, permissions, and business logic in a single file with global state.
570+Functions were handling multiple responsibilities (authentication, validation, business logic).
571+
572+
573+Global State and Poor Encapsulation:
574+
575+Used global variables (fileStorage, users, currentUser, storageUsed) instead of encapsulated state.
576+Direct manipulation of shared state led to potential side effects and made testing difficult.
577+
578+
579+Lack of Proper Abstractions:
580+
581+No separation between data access and business logic.
582+No interfaces defined for the different components of the system.
583+
584+
585+Repetitive Code:
586+
587+Authentication and permission checks repeated in every function.
588+File existence validation duplicated across functions.
589+
590+
591+Poor Error Handling:
592+
593+Inconsistent error reporting (some console.error, some boolean returns).
594+No distinction between different types of errors.
595+
596+
597+Primitive Obsession:
598+
599+Using primitive types instead of creating proper domain objects.
600+
601+
602+Tight Coupling:
603+
604+Functions directly depend on global state.
605+No dependency injection making the code hard to test or extend.
606+
607+
608+Improvements Made in the Refactored Solution
609+
610+Applied Single Responsibility Principle:
611+
612+Created separate UserManager and FileStorageManager classes with clear responsibilities.
613+Each method has a single purpose with helper methods for validation and common tasks.
614+
615+
616+Proper Encapsulation:
617+
618+Encapsulated state within classes using private fields.
619+Provided controlled access to state through methods with proper validation.
620+
621+
622+Improved Type Safety:
623+
624+Converted types to interfaces for better type safety.
625+Added specific interfaces for operations (FileQuery, FileMetadataUpdate, etc.).
626+
627+
628+Dependency Injection:
629+
630+FileStorageManager depends on UserManager through constructor injection.
631+Made constants configurable through constructor parameters.
632+
633+
634+Extracted Helper Methods:
635+
636+Created private helper methods for validation logic.
637+Extracted common operations like canModifyFile, isSharedWithUser, etc.
638+
639+
640+Improved Code Structure:
641+
642+Organized related functionality into classes.
643+Added proper commenting and documentation.
644+
645+
646+Preserved Backward Compatibility:
647+
648+Maintained the original API through exported functions.
649+Made it easy to migrate existing code to use the new object-oriented approach.
650+
651+
652+Applied Open/Closed Principle:
653+
654+The system is now extensible without modifying existing code.
655+New behaviors can be added by extending or composing with existing classes.
656+
657+
658+Applied Interface Segregation:
659+
660+Split large interfaces into smaller, more specific ones.
661+Created purpose-specific interfaces like FileQuery and FileMetadataUpdate.
662+
663+
664+Improved Error Handling:
665+
666+Consistent error reporting pattern.
667+Clear validation in separate methods.
668+*/
added manual-testing-sandbox/next-edit/next-edit-6-3.ts +406 −0
@@ -0,0 +1,406 @@
1+// A chaotic file upload and management system
2+// Difficulty: 3 - Moderate refactoring needed
3+
4+// Types
5+type FileData = {
6+ id: string;
7+ name: string;
8+ size: number;
9+ type: string;
10+ uploadDate: Date;
11+ uploadedBy: string;
12+ path: string;
13+ isPublic: boolean;
14+ tags?: string[];
15+ metadata?: Record<string, any>;
16+};
17+
18+type User = {
19+ id: string;
20+ name: string;
21+ email: string;
22+ role: "admin" | "user" | "guest";
23+};
24+
25+// Global storage
26+const fileStorage: Record<string, FileData> = {};
27+const users: Record<string, User> = {
28+ user1: {
29+ id: "user1",
30+ name: "Admin User",
31+ email: "admin@example.com",
32+ role: "admin",
33+ },
34+ user2: {
35+ id: "user2",
36+ name: "Regular User",
37+ email: "user@example.com",
38+ role: "user",
39+ },
40+ user3: {
41+ id: "user3",
42+ name: "Guest User",
43+ email: "guest@example.com",
44+ role: "guest",
45+ },
46+};
47+let currentUser: string | null = null;
48+let storageUsed = 0;
49+const MAX_STORAGE = 1024 * 1024 * 1024; // 1GB
50+const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
51+
52+// Login function
53+function login(userId: string) {
54+ if (users[userId]) {
55+ currentUser = userId;
56+ console.log(`Logged in as ${users[userId].name}`);
57+ return true;
58+ } else {
59+ console.error("User not found");
60+ return false;
61+ }
62+}
63+
64+// Logout function
65+function logout() {
66+ currentUser = null;
67+ console.log("Logged out");
68+ return true;
69+}
70+
71+// Upload file
72+function uploadFile(
73+ fileName: string,
74+ fileSize: number,
75+ fileType: string,
76+ isPublic: boolean = false,
77+ tags: string[] = [],
78+ metadata: Record<string, any> = {},
79+) {
80+ // Check if user is logged in
81+ if (!currentUser) {
82+ console.error("User not logged in");
83+ return false;
84+ }
85+
86+ // Check file size
87+ if (fileSize > MAX_FILE_SIZE) {
88+ console.error(
89+ `File too large. Maximum size is ${MAX_FILE_SIZE / (1024 * 1024)}MB`,
90+ );
91+ return false;
92+ }
93+
94+ // Check available storage
95+ if (storageUsed + fileSize > MAX_STORAGE) {
96+ console.error("Not enough storage space");
97+ return false;
98+ }
99+
100+ // Generate ID
101+ const fileId = "file_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
102+
103+ // Create file path
104+ const path = `/storage/${currentUser}/${fileId}_${fileName}`;
105+
106+ // Create file data
107+ const fileData: FileData = {
108+ id: fileId,
109+ name: fileName,
110+ size: fileSize,
111+ type: fileType,
112+ uploadDate: new Date(),
113+ uploadedBy: currentUser,
114+ path: path,
115+ isPublic: isPublic,
116+ tags: tags,
117+ metadata: metadata,
118+ };
119+
120+ // Save file data
121+ fileStorage[fileId] = fileData;
122+
123+ // Update storage used
124+ storageUsed += fileSize;
125+
126+ console.log(`File ${fileName} uploaded successfully`);
127+ return fileId;
128+}
129+
130+// Delete file
131+function deleteFile(fileId: string) {
132+ // Check if user is logged in
133+ if (!currentUser) {
134+ console.error("User not logged in");
135+ return false;
136+ }
137+
138+ // Check if file exists
139+ if (!fileStorage[fileId]) {
140+ console.error("File not found");
141+ return false;
142+ }
143+
144+ // Check if user has permission
145+ const file = fileStorage[fileId];
146+ const user = users[currentUser];
147+ if (file.uploadedBy !== currentUser && user.role !== "admin") {
148+ console.error("Permission denied");
149+ return false;
150+ }
151+
152+ // Update storage used
153+ storageUsed -= file.size;
154+
155+ // Remove file
156+ delete fileStorage[fileId];
157+
158+ console.log(`File ${file.name} deleted successfully`);
159+ return true;
160+}
161+
162+// Update file metadata
163+function updateFileMetadata(
164+ fileId: string,
165+ updates: {
166+ name?: string;
167+ isPublic?: boolean;
168+ tags?: string[];
169+ metadata?: Record<string, any>;
170+ },
171+) {
172+ // Check if user is logged in
173+ if (!currentUser) {
174+ console.error("User not logged in");
175+ return false;
176+ }
177+
178+ // Check if file exists
179+ if (!fileStorage[fileId]) {
180+ console.error("File not found");
181+ return false;
182+ }
183+
184+ // Check if user has permission
185+ const file = fileStorage[fileId];
186+ const user = users[currentUser];
187+ if (file.uploadedBy !== currentUser && user.role !== "admin") {
188+ console.error("Permission denied");
189+ return false;
190+ }
191+
192+ // Update file data
193+ if (updates.name !== undefined) fileStorage[fileId].name = updates.name;
194+ if (updates.isPublic !== undefined)
195+ fileStorage[fileId].isPublic = updates.isPublic;
196+ if (updates.tags !== undefined) fileStorage[fileId].tags = updates.tags;
197+ if (updates.metadata !== undefined) {
198+ fileStorage[fileId].metadata = {
199+ ...fileStorage[fileId].metadata,
200+ ...updates.metadata,
201+ };
202+ }
203+
204+ console.log(`File ${file.name} updated successfully`);
205+ return true;
206+}
207+
208+// Get file data
209+function getFileData(fileId: string) {
210+ // Check if file exists
211+ if (!fileStorage[fileId]) {
212+ console.error("File not found");
213+ return null;
214+ }
215+
216+ const file = fileStorage[fileId];
217+
218+ // Check if user has permission
219+ if (
220+ !file.isPublic &&
221+ currentUser !== file.uploadedBy &&
222+ users[currentUser]?.role !== "admin"
223+ ) {
224+ console.error("Permission denied");
225+ return null;
226+ }
227+
228+ return file;
229+}
230+
231+// Search files
232+function searchFiles(query: {
233+ name?: string;
234+ type?: string;
235+ tags?: string[];
236+ uploadedBy?: string;
237+ isPublic?: boolean;
238+ minSize?: number;
239+ maxSize?: number;
240+ uploadedAfter?: Date;
241+ uploadedBefore?: Date;
242+}) {
243+ // Check if user is logged in
244+ if (!currentUser) {
245+ console.error("User not logged in");
246+ return [];
247+ }
248+
249+ const user = users[currentUser];
250+ const results: FileData[] = [];
251+
252+ // Filter files
253+ for (const fileId in fileStorage) {
254+ const file = fileStorage[fileId];
255+
256+ // Skip files user doesn't have access to
257+ if (
258+ !file.isPublic &&
259+ file.uploadedBy !== currentUser &&
260+ user.role !== "admin"
261+ ) {
262+ continue;
263+ }
264+
265+ // Apply filters
266+ let match = true;
267+
268+ if (
269+ query.name &&
270+ !file.name.toLowerCase().includes(query.name.toLowerCase())
271+ ) {
272+ match = false;
273+ }
274+
275+ if (query.type && file.type !== query.type) {
276+ match = false;
277+ }
278+
279+ if (query.uploadedBy && file.uploadedBy !== query.uploadedBy) {
280+ match = false;
281+ }
282+
283+ if (query.isPublic !== undefined && file.isPublic !== query.isPublic) {
284+ match = false;
285+ }
286+
287+ if (query.minSize !== undefined && file.size < query.minSize) {
288+ match = false;
289+ }
290+
291+ if (query.maxSize !== undefined && file.size > query.maxSize) {
292+ match = false;
293+ }
294+
295+ if (query.uploadedAfter && file.uploadDate < query.uploadedAfter) {
296+ match = false;
297+ }
298+
299+ if (query.uploadedBefore && file.uploadDate > query.uploadedBefore) {
300+ match = false;
301+ }
302+
303+ if (query.tags && query.tags.length > 0) {
304+ if (!file.tags) {
305+ match = false;
306+ } else {
307+ for (const tag of query.tags) {
308+ if (!file.tags.includes(tag)) {
309+ match = false;
310+ break;
311+ }
312+ }
313+ }
314+ }
315+
316+ if (match) {
317+ results.push(file);
318+ }
319+ }
320+
321+ return results;
322+}
323+
324+// Get storage stats
325+function getStorageStats() {
326+ return {
327+ used: storageUsed,
328+ total: MAX_STORAGE,
329+ available: MAX_STORAGE - storageUsed,
330+ fileCount: Object.keys(fileStorage).length,
331+ };
332+}
333+
334+// Share file with user
335+function shareFile(fileId: string, targetUserId: string) {
336+ // Check if user is logged in
337+ if (!currentUser) {
338+ console.error("User not logged in");
339+ return false;
340+ }
341+
342+ // Check if file exists
343+ if (!fileStorage[fileId]) {
344+ console.error("File not found");
345+ return false;
346+ }
347+
348+ // Check if target user exists
349+ if (!users[targetUserId]) {
350+ console.error("Target user not found");
351+ return false;
352+ }
353+
354+ // Check if user has permission
355+ const file = fileStorage[fileId];
356+ if (file.uploadedBy !== currentUser && users[currentUser]?.role !== "admin") {
357+ console.error("Permission denied");
358+ return false;
359+ }
360+
361+ // Share file by adding metadata
362+ if (!file.metadata) {
363+ file.metadata = {};
364+ }
365+
366+ if (!file.metadata.sharedWith) {
367+ file.metadata.sharedWith = [];
368+ }
369+
370+ // Check if already shared
371+ if (!file.metadata.sharedWith.includes(targetUserId)) {
372+ file.metadata.sharedWith.push(targetUserId);
373+ }
374+
375+ console.log(`File ${file.name} shared with ${users[targetUserId].name}`);
376+ return true;
377+}
378+
379+// Example usage
380+login("user1");
381+const fileId = uploadFile(
382+ "document.pdf",
383+ 1024 * 1024,
384+ "application/pdf",
385+ false,
386+ ["important", "document"],
387+);
388+updateFileMetadata(fileId, { isPublic: true });
389+shareFile(fileId, "user2");
390+console.log(getFileData(fileId));
391+console.log(getStorageStats());
392+logout();
393+
394+export {
395+ deleteFile,
396+ fileStorage,
397+ getFileData,
398+ getStorageStats,
399+ login,
400+ logout,
401+ searchFiles,
402+ shareFile,
403+ updateFileMetadata,
404+ uploadFile,
405+ users,
406+};
added manual-testing-sandbox/next-edit/next-edit-7-4-sol.ts +489 −0
@@ -0,0 +1,489 @@
1+// Refactored event processing system with proper separation of concerns
2+// Solution for next-edit-7-4.ts
3+
4+// Types
5+export type EventType =
6+ | "click"
7+ | "hover"
8+ | "scroll"
9+ | "keypress"
10+ | "resize"
11+ | "load";
12+export type EventData = Record<string, any>;
13+export type EventCallback = (data: EventData) => void;
14+export type ThemeType = "light" | "dark";
15+export type PreferenceKey = "theme" | "fontSize" | "notifications";
16+
17+// Event system
18+export interface IEventEmitter {
19+ on(eventType: EventType, callback: EventCallback): void;
20+ emit(eventType: EventType, data: EventData): void;
21+ off(eventType: EventType, callback: EventCallback): void;
22+}
23+
24+export class EventEmitter implements IEventEmitter {
25+ private events: Map<EventType, Set<EventCallback>> = new Map();
26+ private processingQueue: Array<{ type: EventType; data: EventData }> = [];
27+ private isProcessing = false;
28+
29+ constructor() {
30+ // Initialize event collections
31+ this.events.set("click", new Set());
32+ this.events.set("hover", new Set());
33+ this.events.set("scroll", new Set());
34+ this.events.set("keypress", new Set());
35+ this.events.set("resize", new Set());
36+ this.events.set("load", new Set());
37+ }
38+
39+ public on(eventType: EventType, callback: EventCallback): void {
40+ const handlers = this.events.get(eventType) || new Set();
41+ handlers.add(callback);
42+ this.events.set(eventType, handlers);
43+ }
44+
45+ public off(eventType: EventType, callback: EventCallback): void {
46+ const handlers = this.events.get(eventType);
47+ if (handlers) {
48+ handlers.delete(callback);
49+ }
50+ }
51+
52+ public emit(eventType: EventType, data: EventData): void {
53+ if (this.isProcessing) {
54+ this.processingQueue.push({ type: eventType, data });
55+ return;
56+ }
57+
58+ this.isProcessing = true;
59+
60+ try {
61+ this.processEvent(eventType, data);
62+
63+ // Process queue
64+ while (this.processingQueue.length > 0) {
65+ const next = this.processingQueue.shift()!;
66+ this.processEvent(next.type, next.data);
67+ }
68+ } finally {
69+ this.isProcessing = false;
70+ }
71+ }
72+
73+ private processEvent(eventType: EventType, data: EventData): void {
74+ const handlers = this.events.get(eventType) || new Set();
75+ for (const handler of handlers) {
76+ handler(data);
77+ }
78+ }
79+}
80+
81+// State management with proper encapsulation
82+export class AppState {
83+ private _count = 0;
84+ private _lastEvent: {
85+ type: string;
86+ data: EventData;
87+ timestamp: number;
88+ } | null = null;
89+ private _eventHistory: string[] = [];
90+
91+ get count(): number {
92+ return this._count;
93+ }
94+
95+ set count(value: number) {
96+ this._count = value;
97+ }
98+
99+ get lastEvent(): { type: string; data: EventData; timestamp: number } | null {
100+ return this._lastEvent;
101+ }
102+
103+ get eventHistory(): ReadonlyArray<string> {
104+ return [...this._eventHistory];
105+ }
106+
107+ public recordEvent(type: string, data: EventData): void {
108+ this._lastEvent = { type, data, timestamp: Date.now() };
109+ this._eventHistory.push(`${type}:${JSON.stringify(data)}`);
110+ }
111+
112+ public incrementCount(): void {
113+ this._count++;
114+ }
115+
116+ public resetCount(): void {
117+ this._count = 0;
118+ }
119+
120+ public formatEventHistory(): string {
121+ return this._eventHistory
122+ .map((event, index) => `${index + 1}. ${event}`)
123+ .join("\n");
124+ }
125+}
126+
127+// User Authentication - separate concern
128+export interface IAuthService {
129+ login(username: string, password: string): Promise<void>;
130+ logout(): void;
131+ isAuthenticated(): boolean;
132+ getUserData(): any;
133+}
134+
135+export class AuthService implements IAuthService {
136+ private isActive = false;
137+ private token = "";
138+ private userData: any = null;
139+ private username = "";
140+
141+ constructor(private eventEmitter: IEventEmitter) {}
142+
143+ public setUsername(name: string): void {
144+ this.username = name;
145+ }
146+
147+ public getUsername(): string {
148+ return this.username;
149+ }
150+
151+ public async login(username: string, password: string): Promise<void> {
152+ console.log(`Attempting login for ${username}...`);
153+
154+ return new Promise((resolve) => {
155+ // Simulate API call
156+ setTimeout(() => {
157+ this.isActive = true;
158+ this.token = `token-${Math.random().toString(36).substring(7)}`;
159+ this.userData = {
160+ name: username,
161+ role: "user",
162+ loginTime: new Date(),
163+ };
164+
165+ this.eventEmitter.emit("load", { user: username });
166+ resolve();
167+ }, 1000);
168+ });
169+ }
170+
171+ public logout(): void {
172+ this.isActive = false;
173+ this.token = "";
174+ this.userData = null;
175+ this.eventEmitter.emit("load", { user: null });
176+ }
177+
178+ public isAuthenticated(): boolean {
179+ return this.isActive;
180+ }
181+
182+ public getUserData(): any {
183+ return this.userData;
184+ }
185+}
186+
187+// Preferences management - separate concern
188+export class PreferencesManager {
189+ private preferences = {
190+ theme: "light" as ThemeType,
191+ fontSize: 12,
192+ notifications: true,
193+ };
194+
195+ getPreference<K extends keyof typeof this.preferences>(
196+ key: K,
197+ ): (typeof this.preferences)[K] {
198+ return this.preferences[key];
199+ }
200+
201+ updatePreference<K extends keyof typeof this.preferences>(
202+ key: K,
203+ value: (typeof this.preferences)[K],
204+ ): void {
205+ this.preferences[key] = value;
206+ }
207+}
208+
209+// UI management - separate concern
210+export class UIManager {
211+ constructor(
212+ private appState: AppState,
213+ private preferencesManager: PreferencesManager,
214+ private eventEmitter: IEventEmitter,
215+ ) {
216+ // Set up default click handler
217+ this.eventEmitter.on("click", (data) => {
218+ console.log("Default click handler:", data);
219+ this.appState.incrementCount();
220+ this.appState.recordEvent("click", data);
221+ this.updateUI();
222+ });
223+ }
224+
225+ public updateUI(): void {
226+ const countElement = document.getElementById("count");
227+ if (countElement) {
228+ countElement.textContent = String(this.appState.count);
229+ }
230+
231+ // Apply theme
232+ document.body.className = this.preferencesManager.getPreference("theme");
233+
234+ // Update last event display
235+ const lastEventElement = document.getElementById("lastEvent");
236+ if (lastEventElement && this.appState.lastEvent) {
237+ lastEventElement.textContent = JSON.stringify(this.appState.lastEvent);
238+ }
239+ }
240+}
241+
242+// Analytics - separate concern
243+export interface IAnalyticsService {
244+ trackEvent(category: string, action: string, label?: string): void;
245+}
246+
247+export class AnalyticsService implements IAnalyticsService {
248+ constructor(
249+ private appState: AppState,
250+ private authService: IAuthService,
251+ ) {}
252+
253+ public trackEvent(category: string, action: string, label?: string): void {
254+ const eventData = { category, action, label, timestamp: Date.now() };
255+ console.log("Tracking event:", eventData);
256+
257+ this.appState.recordEvent("analytics", eventData);
258+
259+ if (this.authService.isAuthenticated()) {
260+ this.sendToAnalyticsService(eventData);
261+ }
262+ }
263+
264+ private sendToAnalyticsService(data: any): void {
265+ // Pretend API call
266+ console.log("Sending to analytics service:", data);
267+ }
268+}
269+
270+// Application class to orchestrate all components
271+export class Application {
272+ private eventEmitter: IEventEmitter;
273+ private appState: AppState;
274+ private authService: IAuthService;
275+ private preferencesManager: PreferencesManager;
276+ private uiManager: UIManager;
277+ private analyticsService: IAnalyticsService;
278+
279+ constructor() {
280+ // Initialize all components with proper dependencies
281+ this.eventEmitter = new EventEmitter();
282+ this.appState = new AppState();
283+ this.authService = new AuthService(this.eventEmitter);
284+ this.preferencesManager = new PreferencesManager();
285+ this.uiManager = new UIManager(
286+ this.appState,
287+ this.preferencesManager,
288+ this.eventEmitter,
289+ );
290+ this.analyticsService = new AnalyticsService(
291+ this.appState,
292+ this.authService,
293+ );
294+
295+ this.setupEventListeners();
296+ }
297+
298+ private setupEventListeners(): void {
299+ // Setup DOM event listeners
300+ document.addEventListener("DOMContentLoaded", () => {
301+ this.eventEmitter.emit("load", { page: "home" });
302+
303+ document.addEventListener("click", (e) => {
304+ this.eventEmitter.emit("click", {
305+ target: e.target,
306+ x: e.clientX,
307+ y: e.clientY,
308+ });
309+
310+ // Handle login button click
311+ if (e.target && (e.target as HTMLElement).id === "login-button") {
312+ this.authService.login(
313+ this.authService.getUsername(),
314+ "hardcoded-password",
315+ );
316+ }
317+ });
318+
319+ document.addEventListener("keypress", (e) => {
320+ this.eventEmitter.emit("keypress", { key: e.key, code: e.code });
321+ });
322+ });
323+ }
324+
325+ // Public API for application
326+ public on(eventType: EventType, callback: EventCallback): void {
327+ this.eventEmitter.on(eventType, callback);
328+ }
329+
330+ public emit(eventType: EventType, data: EventData): void {
331+ this.eventEmitter.emit(eventType, data);
332+ }
333+
334+ public getCurrentCount(): number {
335+ return this.appState.count;
336+ }
337+
338+ public resetCount(): void {
339+ this.appState.resetCount();
340+ this.eventEmitter.emit("click", { action: "reset" });
341+ this.uiManager.updateUI();
342+ }
343+
344+ public setUsername(name: string): void {
345+ this.authService.setUsername(name);
346+ }
347+
348+ public updatePreference(key: PreferenceKey, value: any): void {
349+ this.preferencesManager.updatePreference(key, value);
350+ this.uiManager.updateUI();
351+ this.analyticsService.trackEvent(
352+ "preferences",
353+ "update",
354+ `${key}:${value}`,
355+ );
356+ }
357+
358+ public trackEvent(category: string, action: string, label?: string): void {
359+ this.analyticsService.trackEvent(category, action, label);
360+ }
361+
362+ public formatEventHistory(): string {
363+ return this.appState.formatEventHistory();
364+ }
365+}
366+
367+// Create and export singleton application instance
368+export const app = new Application();
369+
370+// Simplified API for backward compatibility
371+export function getCurrentCount(): number {
372+ return app.getCurrentCount();
373+}
374+
375+export function resetCount(): void {
376+ app.resetCount();
377+}
378+
379+export function setUsername(name: string): void {
380+ app.setUsername(name);
381+}
382+
383+/*
384+Code Smells in the Original Code
385+
386+Violation of Single Responsibility Principle (SRP):
387+
388+The EventManager class was a "God class" handling events, UI updates, authentication, analytics, and preferences
389+Functions had multiple responsibilities mixed together
390+
391+
392+Global State Abuse:
393+
394+Direct manipulation of a global mutable state object
395+No encapsulation or proper state management
396+
397+
398+Tight Coupling:
399+
400+Direct DOM manipulation in the event manager
401+Hard dependencies between unrelated concerns (events, auth, UI)
402+
403+
404+Poor Extensibility:
405+
406+Singleton pattern limiting testability and flexibility
407+Hardcoded event types and handlers
408+No interface-based design
409+
410+
411+Dependency Issues:
412+
413+Direct instantiation of dependencies
414+No dependency injection
415+High-level modules depending on low-level details
416+
417+
418+Security Concerns:
419+
420+Hardcoded password in code
421+No proper authentication flow
422+
423+
424+Maintainability Problems:
425+
426+Scattered responsibilities making the code hard to maintain
427+Side effects hidden throughout the codebase
428+
429+
430+Improvements Made in the Solution
431+
432+Applied Single Responsibility Principle:
433+
434+Split the monolithic EventManager into specialized classes (EventEmitter, AppState, AuthService, etc.)
435+Each class now has a clear, focused responsibility
436+
437+
438+Improved Encapsulation:
439+
440+Replaced global state with proper encapsulated classes
441+Added getters/setters to control state access
442+Private fields to protect internal state
443+
444+
445+Implemented Interface-based Design:
446+
447+Created interfaces like IEventEmitter, IAuthService, and IAnalyticsService
448+Enables future extension and easier testing
449+
450+
451+Applied Dependency Inversion:
452+
453+Components depend on abstractions rather than concrete implementations
454+Dependencies are injected through constructors
455+High-level modules no longer depend directly on low-level modules
456+
457+
458+Better Organization:
459+
460+Segregated interfaces to follow Interface Segregation Principle
461+Clear separation between UI, state, authentication, and event handling
462+
463+
464+Enhanced Extensibility:
465+
466+Event system now uses Sets instead of Arrays for better performance and to avoid duplicate handlers
467+Added ability to remove event listeners with the off method
468+Created proper type definitions for better type safety
469+
470+
471+Improved State Management:
472+
473+Centralized state in the AppState class with proper access controls
474+Immutable collection returns (using spreads and readonly)
475+Clear state manipulation methods
476+
477+
478+Better Event Processing:
479+
480+Cleaner event queue handling
481+More efficient event processing
482+
483+
484+Application Orchestration:
485+
486+Created an Application class to coordinate all components
487+Maintains backward compatibility with the original API
488+Provides a cleaner facade for all operations
489+*/
added manual-testing-sandbox/next-edit/next-edit-7-4.ts +211 −0
@@ -0,0 +1,211 @@
1+// A messy and tightly coupled event processing system with poor separation of concerns
2+// Difficulty: 4
3+
4+type EventType = "click" | "hover" | "scroll" | "keypress" | "resize" | "load";
5+type EventCallback = (data: any) => void;
6+
7+// Global state - everything is mixed together
8+const globalState = {
9+ count: 0,
10+ lastEvent: null as any,
11+ isActive: false,
12+ username: "",
13+ token: "",
14+ preferences: { theme: "light", fontSize: 12, notifications: true },
15+ eventHistory: [] as string[],
16+ userData: null as any,
17+};
18+
19+// God class that handles everything
20+class EventManager {
21+ private events: Map<EventType, EventCallback[]> = new Map();
22+ private static instance: EventManager;
23+ private isProcessing = false;
24+ private processingQueue: Array<{ type: EventType; data: any }> = [];
25+
26+ private constructor() {
27+ // Initialize default handlers
28+ this.events.set("click", []);
29+ this.events.set("hover", []);
30+ this.events.set("scroll", []);
31+ this.events.set("keypress", []);
32+ this.events.set("resize", []);
33+ this.events.set("load", []);
34+
35+ // Add default behavior
36+ this.on("click", (data) => {
37+ console.log("Default click handler:", data);
38+ globalState.count++;
39+ globalState.lastEvent = { type: "click", data, timestamp: Date.now() };
40+ globalState.eventHistory.push(`click:${JSON.stringify(data)}`);
41+
42+ // Side effects directly in handler
43+ this.updateUI();
44+
45+ // Mixes concerns by also handling auth
46+ if (data.target && data.target.id === "login-button") {
47+ this.login(globalState.username, "hardcoded-password");
48+ }
49+ });
50+ }
51+
52+ // Singleton pattern
53+ public static getInstance(): EventManager {
54+ if (!EventManager.instance) {
55+ EventManager.instance = new EventManager();
56+ }
57+ return EventManager.instance;
58+ }
59+
60+ public on(eventType: EventType, callback: EventCallback): void {
61+ const handlers = this.events.get(eventType) || [];
62+ handlers.push(callback);
63+ this.events.set(eventType, handlers);
64+ }
65+
66+ public emit(eventType: EventType, data: any): void {
67+ globalState.lastEvent = { type: eventType, data, timestamp: Date.now() };
68+
69+ if (this.isProcessing) {
70+ this.processingQueue.push({ type: eventType, data });
71+ return;
72+ }
73+
74+ this.isProcessing = true;
75+
76+ try {
77+ const handlers = this.events.get(eventType) || [];
78+ for (const handler of handlers) {
79+ handler(data);
80+
81+ // Random state modifications scattered throughout code
82+ globalState.eventHistory.push(`${eventType}:${JSON.stringify(data)}`);
83+ }
84+
85+ // UI Update with every event
86+ this.updateUI();
87+
88+ // Process queue
89+ while (this.processingQueue.length > 0) {
90+ const next = this.processingQueue.shift()!;
91+ const queueHandlers = this.events.get(next.type) || [];
92+ for (const handler of queueHandlers) {
93+ handler(next.data);
94+ }
95+ }
96+ } finally {
97+ this.isProcessing = false;
98+ }
99+ }
100+
101+ // Mixed UI concerns with event handling
102+ private updateUI(): void {
103+ // Directly manipulates DOM
104+ const countElement = document.getElementById("count");
105+ if (countElement) {
106+ countElement.textContent = String(globalState.count);
107+ }
108+
109+ // Apply theme
110+ document.body.className = globalState.preferences.theme;
111+
112+ // Update last event display
113+ const lastEventElement = document.getElementById("lastEvent");
114+ if (lastEventElement && globalState.lastEvent) {
115+ lastEventElement.textContent = JSON.stringify(globalState.lastEvent);
116+ }
117+ }
118+
119+ // Authentication logic mixed with event handling
120+ private login(username: string, password: string): void {
121+ console.log(`Attempting login for ${username}...`);
122+
123+ // Simulate API call
124+ setTimeout(() => {
125+ globalState.isActive = true;
126+ globalState.token = `token-${Math.random().toString(36).substring(7)}`;
127+ globalState.userData = {
128+ name: username,
129+ role: "user",
130+ loginTime: new Date(),
131+ };
132+
133+ // Update UI after login
134+ this.updateUI();
135+
136+ // Emit another event
137+ this.emit("load", { user: username });
138+ }, 1000);
139+ }
140+
141+ // Analytics mixed in
142+ public trackEvent(category: string, action: string, label?: string): void {
143+ const eventData = { category, action, label, timestamp: Date.now() };
144+ console.log("Tracking event:", eventData);
145+
146+ // Update global state
147+ globalState.eventHistory.push(`analytics:${JSON.stringify(eventData)}`);
148+
149+ // Send to analytics service
150+ if (globalState.isActive) {
151+ this.sendToAnalyticsService(eventData);
152+ }
153+ }
154+
155+ private sendToAnalyticsService(data: any): void {
156+ // Pretend API call
157+ console.log("Sending to analytics service:", data);
158+ }
159+
160+ // Utility functions mixed in
161+ public formatEventHistory(): string {
162+ return globalState.eventHistory
163+ .map((event, index) => `${index + 1}. ${event}`)
164+ .join("\n");
165+ }
166+
167+ // Settings management mixed in
168+ public updatePreference(
169+ key: "theme" | "fontSize" | "notifications",
170+ value: any,
171+ ): void {
172+ globalState.preferences[key] = value;
173+ this.updateUI();
174+ this.trackEvent("preferences", "update", `${key}:${value}`);
175+ }
176+}
177+
178+// Export singleton
179+export const eventManager = EventManager.getInstance();
180+
181+// Helper functions that directly use global state
182+export function getCurrentCount(): number {
183+ return globalState.count;
184+}
185+
186+export function resetCount(): void {
187+ globalState.count = 0;
188+ eventManager.emit("click", { action: "reset" });
189+}
190+
191+export function setUsername(name: string): void {
192+ globalState.username = name;
193+}
194+
195+// Example usage
196+document.addEventListener("DOMContentLoaded", () => {
197+ eventManager.emit("load", { page: "home" });
198+
199+ // Add event listeners
200+ document.addEventListener("click", (e) => {
201+ eventManager.emit("click", {
202+ target: e.target,
203+ x: e.clientX,
204+ y: e.clientY,
205+ });
206+ });
207+
208+ document.addEventListener("keypress", (e) => {
209+ eventManager.emit("keypress", { key: e.key, code: e.code });
210+ });
211+});
added manual-testing-sandbox/next-edit/next-edit-8-4-sol.ts +697 −0
@@ -0,0 +1,697 @@
1+// User management system refactored with SOLID principles
2+// Original difficulty: 4/5
3+
4+// Types
5+type UserStatus = "active" | "inactive" | "suspended" | "deleted";
6+type LogLevel = "debug" | "info" | "warn" | "error";
7+
8+interface User {
9+ id?: number;
10+ firstName: string;
11+ lastName: string;
12+ email: string;
13+ status?: UserStatus;
14+}
15+
16+interface Logger {
17+ log(message: string, level?: LogLevel): void;
18+}
19+
20+interface Database {
21+ query(sql: string, params?: any[]): Promise<any>;
22+ close(): void;
23+}
24+
25+interface StorageService {
26+ getItem(key: string): string | null;
27+ setItem(key: string, value: string): void;
28+}
29+
30+// Configuration interfaces
31+interface SystemConfig {
32+ debugMode: boolean;
33+ apiToken: string;
34+}
35+
36+// Logger implementation - Single Responsibility
37+class ConsoleLogger implements Logger {
38+ constructor(private notificationService?: NotificationService) {}
39+
40+ log(message: string, level: LogLevel = "info"): void {
41+ const timestamp = new Date().toISOString();
42+ console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
43+
44+ // If error, send notification
45+ if (level === "error" && this.notificationService) {
46+ this.notificationService.sendNotification(message);
47+ }
48+ }
49+}
50+
51+// Storage service implementation
52+class LocalStorageService implements StorageService {
53+ getItem(key: string): string | null {
54+ return localStorage.getItem(key);
55+ }
56+
57+ setItem(key: string, value: string): void {
58+ localStorage.setItem(key, value);
59+ }
60+}
61+
62+// Logger decorator to add persistent storage
63+class PersistentLogger implements Logger {
64+ constructor(
65+ private baseLogger: Logger,
66+ private storageService: StorageService,
67+ ) {}
68+
69+ log(message: string, level: LogLevel = "info"): void {
70+ // First use the base logger
71+ this.baseLogger.log(message, level);
72+
73+ // Then persist the log
74+ const timestamp = new Date().toISOString();
75+ try {
76+ const logs = JSON.parse(
77+ this.storageService.getItem("system_logs") || "[]",
78+ );
79+ logs.push({ timestamp, level, message });
80+ this.storageService.setItem("system_logs", JSON.stringify(logs));
81+ } catch (e) {
82+ this.baseLogger.log("Failed to persist log", "error");
83+ }
84+ }
85+}
86+
87+// Notification service - Single Responsibility
88+class NotificationService {
89+ sendNotification(message: string): void {
90+ console.log(`Sending notification: ${message}`);
91+ // Simulate email sending
92+ setTimeout(() => {
93+ console.log("Notification sent!");
94+ }, 1000);
95+ }
96+}
97+
98+// Database service - Single Responsibility
99+class DatabaseService implements Database {
100+ private logger: Logger;
101+
102+ constructor(logger: Logger) {
103+ this.logger = logger;
104+ this.logger.log("Database service initialized", "debug");
105+ }
106+
107+ query(sql: string, params: any[] = []): Promise<any> {
108+ this.logger.log(`Executing query: ${sql}`, "debug");
109+ // Simulate database query
110+ return Promise.resolve({ rows: [], success: true });
111+ }
112+
113+ close(): void {
114+ this.logger.log("Closing database connection", "debug");
115+ }
116+}
117+
118+// Config service - Single Responsibility
119+class ConfigService {
120+ private config: SystemConfig;
121+ private storageService: StorageService;
122+ private logger: Logger;
123+
124+ constructor(storageService: StorageService, logger: Logger) {
125+ this.storageService = storageService;
126+ this.logger = logger;
127+ this.config = this.loadConfig();
128+ }
129+
130+ private loadConfig(): SystemConfig {
131+ try {
132+ return JSON.parse(
133+ this.storageService.getItem("user_system_config") || "{}",
134+ ) as SystemConfig;
135+ } catch (e) {
136+ this.logger.log("Failed to load configuration", "error");
137+ return { debugMode: false, apiToken: "" };
138+ }
139+ }
140+
141+ getConfig(): SystemConfig {
142+ return { ...this.config }; // Return a copy to prevent direct modification
143+ }
144+}
145+
146+// Authentication service - Single Responsibility
147+class AuthService {
148+ private db: Database;
149+ private logger: Logger;
150+ private storageService: StorageService;
151+ private currentUserId: number | null = null;
152+ private loggedInUsers: User[] = [];
153+
154+ constructor(db: Database, logger: Logger, storageService: StorageService) {
155+ this.db = db;
156+ this.logger = logger;
157+ this.storageService = storageService;
158+ }
159+
160+ async login(email: string, password: string): Promise<boolean> {
161+ try {
162+ const result = await this.db.query(
163+ "SELECT * FROM users WHERE email = ? AND password_hash = ?",
164+ [email, this.hashPassword(password)],
165+ );
166+
167+ if (result.rows.length === 0) {
168+ this.logger.log(`Failed login attempt: ${email}`, "warn");
169+ return false;
170+ }
171+
172+ const user = result.rows[0];
173+ if (user.status !== "active") {
174+ this.logger.log(
175+ `Login attempt from inactive account: ${email}`,
176+ "warn",
177+ );
178+ return false;
179+ }
180+
181+ // Update state
182+ this.currentUserId = user.id;
183+ this.loggedInUsers.push(user);
184+ this.storageService.setItem("current_user", JSON.stringify(user));
185+
186+ return true;
187+ } catch (err: any) {
188+ this.logger.log(`Login error: ${err.message}`, "error");
189+ return false;
190+ }
191+ }
192+
193+ logout(): void {
194+ this.currentUserId = null;
195+ this.storageService.setItem("current_user", "");
196+ }
197+
198+ getCurrentUserId(): number | null {
199+ return this.currentUserId;
200+ }
201+
202+ private hashPassword(password: string): string {
203+ // Not a real hash, just base64 encoding - in a real app, use a proper hashing library
204+ return btoa(password);
205+ }
206+}
207+
208+// User repository - Data access layer
209+class UserRepository {
210+ private db: Database;
211+ private logger: Logger;
212+
213+ constructor(db: Database, logger: Logger) {
214+ this.db = db;
215+ this.logger = logger;
216+ }
217+
218+ async getAllActiveUsers(): Promise<User[]> {
219+ try {
220+ const result = await this.db.query(
221+ 'SELECT * FROM users WHERE status != "deleted"',
222+ );
223+ return result.rows;
224+ } catch (err: any) {
225+ this.logger.log(`Failed to fetch users: ${err.message}`, "error");
226+ throw err;
227+ }
228+ }
229+
230+ async createUser(userData: User): Promise<boolean> {
231+ try {
232+ await this.db.query(
233+ "INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)",
234+ [userData.firstName, userData.lastName, userData.email, "active"],
235+ );
236+ this.logger.log(`User created: ${userData.email}`, "info");
237+ return true;
238+ } catch (err: any) {
239+ this.logger.log(`Failed to create user: ${err.message}`, "error");
240+ throw err;
241+ }
242+ }
243+
244+ async updateUser(userId: number, userData: User): Promise<boolean> {
245+ try {
246+ await this.db.query(
247+ "UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?",
248+ [userData.firstName, userData.lastName, userData.email, userId],
249+ );
250+ this.logger.log(`User updated: ${userId}`, "info");
251+ return true;
252+ } catch (err: any) {
253+ this.logger.log(`Failed to update user: ${err.message}`, "error");
254+ throw err;
255+ }
256+ }
257+
258+ async updateUserStatus(userId: number, status: UserStatus): Promise<boolean> {
259+ try {
260+ await this.db.query("UPDATE users SET status = ? WHERE id = ?", [
261+ status,
262+ userId,
263+ ]);
264+ this.logger.log(`User status updated to ${status}: ${userId}`, "info");
265+ return true;
266+ } catch (err: any) {
267+ this.logger.log(`Failed to update user status: ${err.message}`, "error");
268+ throw err;
269+ }
270+ }
271+}
272+
273+// UI rendering service - Single Responsibility
274+class UserUIService {
275+ private userRepository: UserRepository;
276+ private logger: Logger;
277+
278+ constructor(userRepository: UserRepository, logger: Logger) {
279+ this.userRepository = userRepository;
280+ this.logger = logger;
281+ }
282+
283+ async renderUserList(containerId: string): Promise<void> {
284+ const container = document.getElementById(containerId);
285+ if (!container) {
286+ this.logger.log(`Container ${containerId} not found`, "error");
287+ return;
288+ }
289+
290+ // Clear container
291+ container.innerHTML = "";
292+
293+ try {
294+ // Get users from repository
295+ const users = await this.userRepository.getAllActiveUsers();
296+
297+ // Generate HTML
298+ let html = '<ul class="user-list">';
299+ users.forEach((user) => {
300+ // User status determines CSS class
301+ const statusClass = this.getStatusClass(user.status || "active");
302+
303+ html += `
304+ <li class="user-item ${statusClass}" data-id="${user.id}">
305+ <div class="user-name">${user.firstName} ${user.lastName}</div>
306+ <div class="user-email">${user.email}</div>
307+ <div class="user-actions">
308+ <button onclick="userController.editUser(${user.id})">Edit</button>
309+ <button onclick="userController.deleteUser(${user.id})">Delete</button>
310+ ${
311+ user.status === "active"
312+ ? `<button onclick="userController.suspendUser(${user.id})">Suspend</button>`
313+ : `<button onclick="userController.activateUser(${user.id})">Activate</button>`
314+ }
315+ </div>
316+ </li>
317+ `;
318+ });
319+ html += "</ul>";
320+
321+ container.innerHTML = html;
322+ } catch (err: any) {
323+ this.logger.log(`Failed to render users: ${err.message}`, "error");
324+ container.innerHTML =
325+ "<p>Failed to load users. Please try again later.</p>";
326+ }
327+ }
328+
329+ private getStatusClass(status: UserStatus): string {
330+ switch (status) {
331+ case "active":
332+ return "user-active";
333+ case "inactive":
334+ return "user-inactive";
335+ case "suspended":
336+ return "user-suspended";
337+ default:
338+ return "";
339+ }
340+ }
341+
342+ populateEditForm(form: HTMLFormElement, user: User): void {
343+ if (!form) return;
344+
345+ (form.elements.namedItem("firstName") as HTMLInputElement).value =
346+ user.firstName;
347+ (form.elements.namedItem("lastName") as HTMLInputElement).value =
348+ user.lastName;
349+ (form.elements.namedItem("email") as HTMLInputElement).value = user.email;
350+ (form.elements.namedItem("userId") as HTMLInputElement).value = String(
351+ user.id,
352+ );
353+
354+ // Scroll to form
355+ form.scrollIntoView({ behavior: "smooth" });
356+ }
357+
358+ resetForm(formId: string): void {
359+ const form = document.getElementById(formId) as HTMLFormElement;
360+ if (form) {
361+ form.reset();
362+ (form.elements.namedItem("userId") as HTMLInputElement).value = "";
363+ }
364+ }
365+}
366+
367+// User Controller - Handles UI interactions and coordinates services
368+class UserController {
369+ private userRepository: UserRepository;
370+ private userUIService: UserUIService;
371+ private logger: Logger;
372+ private lastOperation: string = "";
373+
374+ constructor(
375+ userRepository: UserRepository,
376+ userUIService: UserUIService,
377+ logger: Logger,
378+ ) {
379+ this.userRepository = userRepository;
380+ this.userUIService = userUIService;
381+ this.logger = logger;
382+ }
383+
384+ async createUser(userData: User): Promise<void> {
385+ try {
386+ await this.userRepository.createUser(userData);
387+ this.lastOperation = "create";
388+ await this.userUIService.renderUserList("user-container");
389+ this.userUIService.resetForm("user-form");
390+ alert("User created successfully!");
391+ } catch (err: any) {
392+ alert(`Failed to create user: ${err.message}`);
393+ }
394+ }
395+
396+ async updateUser(userId: number, userData: User): Promise<void> {
397+ try {
398+ await this.userRepository.updateUser(userId, userData);
399+ this.lastOperation = "update";
400+ await this.userUIService.renderUserList("user-container");
401+ this.userUIService.resetForm("user-form");
402+ alert("User updated successfully!");
403+ } catch (err: any) {
404+ alert(`Failed to update user: ${err.message}`);
405+ }
406+ }
407+
408+ async editUser(userId: number): Promise<void> {
409+ try {
410+ const users = await this.userRepository.getAllActiveUsers();
411+ const user = users.find((u) => u.id === userId);
412+
413+ if (!user) {
414+ this.logger.log(`User not found: ${userId}`, "error");
415+ return;
416+ }
417+
418+ const form = document.getElementById("user-form") as HTMLFormElement;
419+ this.userUIService.populateEditForm(form, user);
420+ this.lastOperation = "edit";
421+ } catch (err: any) {
422+ this.logger.log(`Failed to edit user: ${err.message}`, "error");
423+ }
424+ }
425+
426+ async suspendUser(userId: number): Promise<void> {
427+ if (!confirm("Are you sure you want to suspend this user?")) {
428+ return;
429+ }
430+
431+ try {
432+ await this.userRepository.updateUserStatus(userId, "suspended");
433+ this.lastOperation = "suspend";
434+ await this.userUIService.renderUserList("user-container");
435+ alert("User suspended successfully!");
436+ } catch (err: any) {
437+ alert(`Failed to suspend user: ${err.message}`);
438+ }
439+ }
440+
441+ async activateUser(userId: number): Promise<void> {
442+ try {
443+ await this.userRepository.updateUserStatus(userId, "active");
444+ this.lastOperation = "activate";
445+ await this.userUIService.renderUserList("user-container");
446+ alert("User activated successfully!");
447+ } catch (err: any) {
448+ alert(`Failed to activate user: ${err.message}`);
449+ }
450+ }
451+
452+ async deleteUser(userId: number): Promise<void> {
453+ if (!confirm("Are you sure you want to delete this user?")) {
454+ return;
455+ }
456+
457+ try {
458+ await this.userRepository.updateUserStatus(userId, "deleted");
459+ this.lastOperation = "delete";
460+ await this.userUIService.renderUserList("user-container");
461+ alert("User deleted successfully!");
462+ } catch (err: any) {
463+ alert(`Failed to delete user: ${err.message}`);
464+ }
465+ }
466+
467+ getLastOperation(): string {
468+ return this.lastOperation;
469+ }
470+}
471+
472+// Application class - Manages services and their lifecycle
473+class UserManagementApp {
474+ private logger: Logger;
475+ private db: Database;
476+ private userRepository: UserRepository;
477+ private userUIService: UserUIService;
478+ private userController: UserController;
479+ private authService: AuthService;
480+ private configService: ConfigService;
481+ private storageService: StorageService;
482+
483+ constructor() {
484+ // Initialize services
485+ this.storageService = new LocalStorageService();
486+ const notificationService = new NotificationService();
487+ const baseLogger = new ConsoleLogger(notificationService);
488+ this.logger = new PersistentLogger(baseLogger, this.storageService);
489+ this.configService = new ConfigService(this.storageService, this.logger);
490+
491+ // Initialize database
492+ this.db = new DatabaseService(this.logger);
493+
494+ // Initialize user repository
495+ this.userRepository = new UserRepository(this.db, this.logger);
496+
497+ // Initialize UI service
498+ this.userUIService = new UserUIService(this.userRepository, this.logger);
499+
500+ // Initialize controller
501+ this.userController = new UserController(
502+ this.userRepository,
503+ this.userUIService,
504+ this.logger,
505+ );
506+
507+ // Initialize auth service
508+ this.authService = new AuthService(
509+ this.db,
510+ this.logger,
511+ this.storageService,
512+ );
513+
514+ // Expose controller to global scope
515+ (window as any).userController = this.userController;
516+
517+ this.setupEventListeners();
518+ this.setupErrorHandlers();
519+ }
520+
521+ private setupEventListeners(): void {
522+ window.addEventListener("load", () => {
523+ const userForm = document.getElementById("user-form");
524+ if (userForm) {
525+ userForm.addEventListener(
526+ "submit",
527+ this.handleUserFormSubmit.bind(this),
528+ );
529+ }
530+
531+ // Initialize user list
532+ this.userUIService.renderUserList("user-container");
533+ });
534+ }
535+
536+ private setupErrorHandlers(): void {
537+ window.onerror = (msg, url, line) => {
538+ this.logger.log(`Global error: ${msg} at ${url}:${line}`, "error");
539+ return false;
540+ };
541+ }
542+
543+ private handleUserFormSubmit(event: Event): void {
544+ event.preventDefault();
545+ const form = event.target as HTMLFormElement;
546+
547+ const userData: User = {
548+ firstName: (form.elements.namedItem("firstName") as HTMLInputElement)
549+ .value,
550+ lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value,
551+ email: (form.elements.namedItem("email") as HTMLInputElement).value,
552+ };
553+
554+ const userId = (form.elements.namedItem("userId") as HTMLInputElement)
555+ .value;
556+
557+ if (userId) {
558+ this.userController.updateUser(parseInt(userId), userData);
559+ } else {
560+ this.userController.createUser(userData);
561+ }
562+ }
563+
564+ async login(email: string, password: string): Promise<boolean> {
565+ const success = await this.authService.login(email, password);
566+ if (success) {
567+ // Redirect to dashboard
568+ window.location.href = "/dashboard.html";
569+ } else {
570+ alert("Invalid email or password");
571+ }
572+ return success;
573+ }
574+
575+ cleanup(): void {
576+ this.logger.log("Cleaning up resources", "debug");
577+ this.db.close();
578+ }
579+}
580+
581+// Initialize the application
582+const app = new UserManagementApp();
583+
584+/*
585+Code Smells in the Original Code
586+
587+Violation of Single Responsibility Principle:
588+
589+UserManager was a "God class" handling database connection, UI rendering, user CRUD operations, authentication, and logging
590+Logger mixed logging with email notifications
591+User operations contained both business logic and UI manipulation
592+
593+Violation of Open/Closed Principle:
594+
595+Hardcoded dependencies that couldn't be extended without modifying code
596+Direct UI manipulations embedded in business logic
597+
598+High Coupling:
599+
600+Direct references to the DOM throughout the codebase
601+Global state used across different operations
602+Direct database access from UI-related methods
603+
604+Code Duplication:
605+
606+Similar code repeated in suspendUser, activateUser, and deleteUser methods
607+Repetitive UI update logic
608+
609+Poor Security Practices:
610+
611+API tokens exposed in console logs
612+Weak password handling (just base64 encoding)
613+Direct SQL queries vulnerable to injection
614+
615+
616+Global Variables and Side Effects:
617+
618+Multiple global variables (currentUserID, loggedInUsers, etc.)
619+Global DOM event handlers
620+
621+
622+Improvements Made
623+
624+Applied Single Responsibility Principle:
625+
626+Created specialized classes for each concern:
627+
628+Logger and PersistentLogger for logging
629+NotificationService for alerts/notifications
630+DatabaseService for database operations
631+UserRepository for user data access
632+UserUIService for rendering UI
633+UserController for handling user actions
634+AuthService for authentication
635+ConfigService for configuration management
636+
637+
638+Applied Open/Closed Principle:
639+
640+Used interfaces (Logger, Database, StorageService) to define contracts
641+Implemented dependency injection to allow for extensions without modifications
642+Created the decorator pattern for logging (base logger + persistent storage)
643+
644+
645+Applied Interface Segregation Principle:
646+
647+Created focused interfaces (e.g., Logger only handles logging)
648+Split large interfaces into smaller, more specific ones
649+
650+
651+Applied Dependency Inversion Principle:
652+
653+High-level modules depend on abstractions, not concrete implementations
654+Dependencies are injected through constructors
655+Centralized service initialization in the UserManagementApp class
656+
657+
658+Applied Liskov Substitution Principle:
659+
660+Classes implementing interfaces fully satisfy their contracts
661+Derived classes (like PersistentLogger) maintain the behavior expected from the base interface
662+
663+
664+Reduced Duplication:
665+
666+Consolidated common user operations in the repository
667+Created reusable UI methods
668+Extracted common logic into shared methods
669+
670+
671+Improved Security:
672+
673+Removed sensitive information from console logs
674+Added proper encapsulation of sensitive data
675+Note: The password hashing is still weak (commented as such) but is separated for easy replacement
676+
677+
678+Better State Management:
679+
680+Eliminated global state
681+Encapsulated state within appropriate classes
682+Provided proper methods for state access
683+
684+
685+Improved Error Handling:
686+
687+Consistent error handling approach
688+Proper propagation of errors
689+Clear error messages
690+
691+
692+Proper Separation of Concerns:
693+
694+UI logic separated from business logic
695+Data access separated from business rules
696+Authentication separated from user management
697+*/
added manual-testing-sandbox/next-edit/next-edit-8-4.ts +409 −0
@@ -0,0 +1,409 @@
1+// User management system with mixed concerns and entangled logic
2+// Difficulty: 4/5
3+
4+type UserStatus = "active" | "inactive" | "suspended" | "deleted";
5+type LogLevel = "debug" | "info" | "warn" | "error";
6+
7+// Global variables
8+let currentUserID: number | null = null;
9+let loggedInUsers: any[] = [];
10+let systemStatus = "online";
11+let DEBUG_MODE = true;
12+
13+// Main user class that handles everything
14+class UserManager {
15+ private users: any[] = [];
16+ private db: any = null;
17+ private logger: any = null;
18+ private apiToken: string = "secret-token-1234";
19+ public lastOperation: string = "";
20+
21+ constructor() {
22+ this.initializeSystem();
23+ // Connect to database directly in constructor
24+ this.connectToDatabase();
25+ console.log("UserManager initialized!");
26+ }
27+
28+ // Mixed responsibility - initialization, logging, and notification
29+ private initializeSystem() {
30+ // Set up logging
31+ this.logger = {
32+ log: function (message: string, level: LogLevel = "info") {
33+ const timestamp = new Date().toISOString();
34+ console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
35+
36+ // Store logs in localStorage too
37+ const logs = JSON.parse(localStorage.getItem("system_logs") || "[]");
38+ logs.push({ timestamp, level, message });
39+ localStorage.setItem("system_logs", JSON.stringify(logs));
40+
41+ // If error, send notification
42+ if (level === "error") {
43+ // Send email notification
44+ this.sendEmailAlert(message);
45+ }
46+ },
47+
48+ sendEmailAlert: function (message: string) {
49+ console.log(`Sending email alert: ${message}`);
50+ // Simulate email sending
51+ setTimeout(() => {
52+ console.log("Email sent!");
53+ }, 1000);
54+ },
55+ };
56+
57+ // Load configuration
58+ let config;
59+ try {
60+ config = JSON.parse(localStorage.getItem("user_system_config") || "{}");
61+ DEBUG_MODE = config.debugMode || DEBUG_MODE;
62+ this.apiToken = config.apiToken || this.apiToken;
63+ } catch (e) {
64+ this.logger.log("Failed to load configuration", "error");
65+ }
66+ }
67+
68+ // Database connection hardcoded
69+ private connectToDatabase() {
70+ this.logger.log("Connecting to database...", "debug");
71+
72+ // Simulate database connection
73+ this.db = {
74+ query: function (sql: string, params: any[] = []) {
75+ console.log(`Executing query: ${sql}`);
76+ console.log("Params:", params);
77+ return Promise.resolve({ rows: [], success: true });
78+ },
79+
80+ close: function () {
81+ console.log("Closing database connection");
82+ },
83+ };
84+
85+ // Log connection info to console in plain text
86+ console.log(`Connected to database with token: ${this.apiToken}`);
87+
88+ // Save connection timestamp
89+ localStorage.setItem("last_db_connection", new Date().toISOString());
90+ }
91+
92+ // UI generation mixed with business logic
93+ public renderUserList(containerId: string) {
94+ const container = document.getElementById(containerId);
95+ if (!container) {
96+ this.logger.log(`Container ${containerId} not found`, "error");
97+ return;
98+ }
99+
100+ // Clear container
101+ container.innerHTML = "";
102+
103+ // Get users - mixing data fetching and rendering
104+ this.db
105+ .query('SELECT * FROM users WHERE status != "deleted"')
106+ .then((result: any) => {
107+ this.users = result.rows;
108+
109+ // Generate HTML - UI logic mixed with business logic
110+ let html = '<ul class="user-list">';
111+ this.users.forEach((user) => {
112+ // User status determines CSS class
113+ let statusClass = "";
114+ switch (user.status) {
115+ case "active":
116+ statusClass = "user-active";
117+ break;
118+ case "inactive":
119+ statusClass = "user-inactive";
120+ break;
121+ case "suspended":
122+ statusClass = "user-suspended";
123+ break;
124+ }
125+
126+ html += `
127+ <li class="user-item ${statusClass}" data-id="${user.id}">
128+ <div class="user-name">${user.firstName} ${user.lastName}</div>
129+ <div class="user-email">${user.email}</div>
130+ <div class="user-actions">
131+ <button onclick="userManager.editUser(${user.id})">Edit</button>
132+ <button onclick="userManager.deleteUser(${user.id})">Delete</button>
133+ ${
134+ user.status === "active"
135+ ? `<button onclick="userManager.suspendUser(${user.id})">Suspend</button>`
136+ : `<button onclick="userManager.activateUser(${user.id})">Activate</button>`
137+ }
138+ </div>
139+ </li>
140+ `;
141+ });
142+ html += "</ul>";
143+
144+ container.innerHTML = html;
145+ })
146+ .catch((err: any) => {
147+ this.logger.log(`Failed to fetch users: ${err.message}`, "error");
148+ container.innerHTML =
149+ "<p>Failed to load users. Please try again later.</p>";
150+ });
151+ }
152+
153+ // No validation, directly manipulating UI and data
154+ public createUser(userData: any) {
155+ // Directly create user without validation
156+ this.db
157+ .query(
158+ "INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)",
159+ [userData.firstName, userData.lastName, userData.email, "active"],
160+ )
161+ .then((result: any) => {
162+ this.logger.log(`User created: ${userData.email}`, "info");
163+
164+ // Update UI directly here
165+ this.renderUserList("user-container");
166+
167+ // Update global state
168+ this.lastOperation = "create";
169+
170+ // Clear form - direct DOM manipulation
171+ document.getElementById("user-form")?.reset();
172+
173+ // Show success message
174+ alert("User created successfully!");
175+ })
176+ .catch((err: any) => {
177+ this.logger.log(`Failed to create user: ${err.message}`, "error");
178+ alert("Failed to create user! " + err.message);
179+ });
180+ }
181+
182+ // Logic duplicated for similar operations
183+ public editUser(userId: number) {
184+ // Directly edit UI elements based on user ID
185+ const userElement = document.querySelector(`li[data-id="${userId}"]`);
186+ if (!userElement) {
187+ this.logger.log(`User element not found: ${userId}`, "error");
188+ return;
189+ }
190+
191+ // Find user data
192+ const user = this.users.find((u) => u.id === userId);
193+ if (!user) {
194+ this.logger.log(`User not found: ${userId}`, "error");
195+ return;
196+ }
197+
198+ // Populate form - direct DOM manipulation
199+ const form = document.getElementById("user-form") as HTMLFormElement;
200+ if (form) {
201+ (form.elements.namedItem("firstName") as HTMLInputElement).value =
202+ user.firstName;
203+ (form.elements.namedItem("lastName") as HTMLInputElement).value =
204+ user.lastName;
205+ (form.elements.namedItem("email") as HTMLInputElement).value = user.email;
206+ (form.elements.namedItem("userId") as HTMLInputElement).value =
207+ String(userId);
208+
209+ // Scroll to form
210+ form.scrollIntoView({ behavior: "smooth" });
211+ }
212+
213+ // Update global state
214+ currentUserID = userId;
215+ this.lastOperation = "edit";
216+ }
217+
218+ // Logic duplicated, similar to deleteUser
219+ public suspendUser(userId: number) {
220+ if (!confirm("Are you sure you want to suspend this user?")) {
221+ return;
222+ }
223+
224+ this.db
225+ .query("UPDATE users SET status = ? WHERE id = ?", ["suspended", userId])
226+ .then((result: any) => {
227+ this.logger.log(`User suspended: ${userId}`, "info");
228+
229+ // Update UI directly
230+ this.renderUserList("user-container");
231+
232+ // Update global state
233+ this.lastOperation = "suspend";
234+
235+ // Show success message
236+ alert("User suspended successfully!");
237+ })
238+ .catch((err: any) => {
239+ this.logger.log(`Failed to suspend user: ${err.message}`, "error");
240+ alert("Failed to suspend user! " + err.message);
241+ });
242+ }
243+
244+ // Nearly identical to suspendUser
245+ public activateUser(userId: number) {
246+ this.db
247+ .query("UPDATE users SET status = ? WHERE id = ?", ["active", userId])
248+ .then((result: any) => {
249+ this.logger.log(`User activated: ${userId}`, "info");
250+
251+ // Update UI directly
252+ this.renderUserList("user-container");
253+
254+ // Update global state
255+ this.lastOperation = "activate";
256+
257+ // Show success message
258+ alert("User activated successfully!");
259+ })
260+ .catch((err: any) => {
261+ this.logger.log(`Failed to activate user: ${err.message}`, "error");
262+ alert("Failed to activate user! " + err.message);
263+ });
264+ }
265+
266+ // Logic duplicated again
267+ public deleteUser(userId: number) {
268+ if (!confirm("Are you sure you want to delete this user?")) {
269+ return;
270+ }
271+
272+ // Actually just updating status to 'deleted'
273+ this.db
274+ .query("UPDATE users SET status = ? WHERE id = ?", ["deleted", userId])
275+ .then((result: any) => {
276+ this.logger.log(`User deleted: ${userId}`, "info");
277+
278+ // Update UI directly
279+ this.renderUserList("user-container");
280+
281+ // Update global state
282+ this.lastOperation = "delete";
283+
284+ // Show success message
285+ alert("User deleted successfully!");
286+ })
287+ .catch((err: any) => {
288+ this.logger.log(`Failed to delete user: ${err.message}`, "error");
289+ alert("Failed to delete user! " + err.message);
290+ });
291+ }
292+
293+ // Authentication mixed with user management
294+ public login(email: string, password: string) {
295+ // Directly query with credentials
296+ this.db
297+ .query("SELECT * FROM users WHERE email = ? AND password_hash = ?", [
298+ email,
299+ this.hashPassword(password),
300+ ])
301+ .then((result: any) => {
302+ if (result.rows.length === 0) {
303+ this.logger.log(`Failed login attempt: ${email}`, "warn");
304+ alert("Invalid email or password");
305+ return;
306+ }
307+
308+ const user = result.rows[0];
309+ if (user.status !== "active") {
310+ this.logger.log(
311+ `Login attempt from inactive account: ${email}`,
312+ "warn",
313+ );
314+ alert("Your account is not active");
315+ return;
316+ }
317+
318+ // Update global state
319+ currentUserID = user.id;
320+ loggedInUsers.push(user);
321+ this.lastOperation = "login";
322+
323+ // Store in localStorage
324+ localStorage.setItem("current_user", JSON.stringify(user));
325+
326+ // Redirect to dashboard
327+ window.location.href = "/dashboard.html";
328+ })
329+ .catch((err: any) => {
330+ this.logger.log(`Login error: ${err.message}`, "error");
331+ alert("Login failed! " + err.message);
332+ });
333+ }
334+
335+ // Utility function with security implications
336+ private hashPassword(password: string): string {
337+ // Not a real hash, just base64 encoding
338+ return btoa(password);
339+ }
340+
341+ // Cleanup that's never called
342+ public cleanup() {
343+ this.logger.log("Cleaning up resources", "debug");
344+ this.db.close();
345+ this.users = [];
346+ currentUserID = null;
347+ }
348+}
349+
350+// Instantiate globally
351+const userManager = new UserManager();
352+
353+// Event handlers directly in global scope
354+function handleUserFormSubmit(event: Event) {
355+ event.preventDefault();
356+ const form = event.target as HTMLFormElement;
357+
358+ const userData = {
359+ firstName: (form.elements.namedItem("firstName") as HTMLInputElement).value,
360+ lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value,
361+ email: (form.elements.namedItem("email") as HTMLInputElement).value,
362+ };
363+
364+ const userId = (form.elements.namedItem("userId") as HTMLInputElement).value;
365+
366+ if (userId) {
367+ // Should call an update method, but directly calls the database
368+ userManager.db
369+ .query(
370+ "UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?",
371+ [userData.firstName, userData.lastName, userData.email, userId],
372+ )
373+ .then(() => {
374+ alert("User updated successfully!");
375+ userManager.renderUserList("user-container");
376+ form.reset();
377+ (form.elements.namedItem("userId") as HTMLInputElement).value = "";
378+ })
379+ .catch((err: any) => {
380+ alert("Failed to update user: " + err.message);
381+ });
382+ } else {
383+ userManager.createUser(userData);
384+ }
385+}
386+
387+// Global initialization
388+window.onload = function () {
389+ console.log("Window loaded!");
390+
391+ // Set up event listeners
392+ const userForm = document.getElementById("user-form");
393+ if (userForm) {
394+ userForm.addEventListener("submit", handleUserFormSubmit);
395+ }
396+
397+ // Initialize user list
398+ userManager.renderUserList("user-container");
399+
400+ // Set up some global error handlers
401+ window.onerror = function (msg, url, line) {
402+ userManager.logger.log(`Global error: ${msg} at ${url}:${line}`, "error");
403+ return false;
404+ };
405+};
406+
407+// Global exports
408+(window as any).userManager = userManager;
409+(window as any).handleUserFormSubmit = handleUserFormSubmit;
added manual-testing-sandbox/next-edit/next-edit-9-5-sol.ts +654 −0
@@ -0,0 +1,654 @@
1+// Clean implementation of e-commerce product management system
2+// Following SOLID principles
3+
4+// Types and Interfaces
5+type ProductStatus =
6+ | "active"
7+ | "inactive"
8+ | "discontinued"
9+ | "out_of_stock"
10+ | "backorder";
11+type UserRole = "admin" | "manager" | "staff" | "customer";
12+
13+interface Product {
14+ id: string;
15+ name: string;
16+ price: number;
17+ description: string;
18+ image: string;
19+ category: string;
20+ status: ProductStatus;
21+ created: Date;
22+ createdBy: string;
23+ stock: number;
24+ ratings: any[];
25+ tags: string[];
26+ lastModified: Date;
27+ lastModifiedBy?: string;
28+}
29+
30+interface User {
31+ id: string;
32+ username: string;
33+ role: UserRole;
34+}
35+
36+interface CartItem {
37+ productId: string;
38+ quantity: number;
39+ price: number;
40+ name: string;
41+ addedAt: Date;
42+}
43+
44+interface Notification {
45+ type: string;
46+ message: string;
47+ timestamp: Date;
48+}
49+
50+interface LogEntry {
51+ timestamp: string;
52+ action: string;
53+ data: any;
54+ user: string;
55+}
56+
57+interface SearchFilters {
58+ category?: string;
59+ minPrice?: number;
60+ maxPrice?: number;
61+ status?: ProductStatus;
62+}
63+
64+// Database abstraction - Single Responsibility for data persistence
65+class Database {
66+ private products: Map<string, Product> = new Map();
67+ private users: Map<string, User> = new Map();
68+ private cart: Map<string, CartItem[]> = new Map();
69+ private orders: any[] = [];
70+ private logs: LogEntry[] = [];
71+ private sessions: Map<string, any> = new Map();
72+ private config = { taxRate: 0.08, discountThreshold: 1000 };
73+
74+ // Product repository methods
75+ getProduct(id: string): Product | undefined {
76+ return this.products.get(id);
77+ }
78+
79+ saveProduct(product: Product): void {
80+ this.products.set(product.id, product);
81+ }
82+
83+ removeProduct(id: string): boolean {
84+ return this.products.delete(id);
85+ }
86+
87+ getAllProducts(): Product[] {
88+ return Array.from(this.products.values());
89+ }
90+
91+ // Cart repository methods
92+ getCart(userId: string): CartItem[] {
93+ return this.cart.get(userId) || [];
94+ }
95+
96+ saveCart(userId: string, cart: CartItem[]): void {
97+ this.cart.set(userId, cart);
98+ }
99+
100+ // Logging method
101+ addLog(logEntry: LogEntry): void {
102+ this.logs.push(logEntry);
103+ }
104+}
105+
106+// Authentication service - Single Responsibility for user management
107+class AuthService {
108+ private currentUser: User | null = null;
109+
110+ constructor(private database: Database) {}
111+
112+ getCurrentUser(): User | null {
113+ return this.currentUser;
114+ }
115+
116+ setCurrentUser(user: User): void {
117+ this.currentUser = user;
118+ }
119+
120+ logout(): void {
121+ this.currentUser = null;
122+ }
123+
124+ hasPermission(allowedRoles: UserRole[]): boolean {
125+ if (!this.currentUser) return false;
126+ return allowedRoles.includes(this.currentUser.role);
127+ }
128+}
129+
130+// Utility service - Single Responsibility for common functions
131+class UtilityService {
132+ generateId(prefix: string): string {
133+ return `${prefix}_${Math.random().toString(36).substring(2, 9)}`;
134+ }
135+}
136+
137+// Logger service - Single Responsibility for logging
138+class LoggingService {
139+ constructor(
140+ private database: Database,
141+ private authService: AuthService,
142+ ) {}
143+
144+ log(action: string, data: any): void {
145+ const timestamp = new Date().toISOString();
146+ const logEntry: LogEntry = {
147+ timestamp,
148+ action,
149+ data,
150+ user: this.authService.getCurrentUser()?.username || "system",
151+ };
152+
153+ this.database.addLog(logEntry);
154+ console.log(`[${timestamp}] ${action}:`, data);
155+ }
156+}
157+
158+// Notification service - Single Responsibility for notifications
159+class NotificationService {
160+ private notifications: Notification[] = [];
161+
162+ addNotification(type: string, message: string): void {
163+ this.notifications.push({
164+ type,
165+ message,
166+ timestamp: new Date(),
167+ });
168+ }
169+
170+ getNotifications(): Notification[] {
171+ return [...this.notifications];
172+ }
173+}
174+
175+// Email service - Single Responsibility for email communication
176+class EmailService {
177+ sendEmailToSubscribers(
178+ productName: string,
179+ subject: string,
180+ body: string,
181+ ): void {
182+ console.log(`Sending email about ${productName} to subscribers`);
183+ // Actual email sending logic would go here
184+ }
185+}
186+
187+// Product validation - Single Responsibility for product validation
188+class ProductValidator {
189+ validate(name: string, price: number): boolean {
190+ return name !== "" && price > 0;
191+ }
192+}
193+
194+// Auth middleware interface - Open/Closed Principle
195+interface AuthorizationMiddleware {
196+ checkAuthorization(operation: string): boolean;
197+}
198+
199+// Product authorization - Single Responsibility for product auth
200+class ProductAuthorizationMiddleware implements AuthorizationMiddleware {
201+ constructor(private authService: AuthService) {}
202+
203+ checkAuthorization(operation: string): boolean {
204+ const currentUser = this.authService.getCurrentUser();
205+ if (!currentUser) return false;
206+
207+ switch (operation) {
208+ case "create":
209+ case "update":
210+ return this.authService.hasPermission(["admin", "manager"]);
211+ case "delete":
212+ return this.authService.hasPermission(["admin"]);
213+ case "view":
214+ return true;
215+ default:
216+ return false;
217+ }
218+ }
219+}
220+
221+// Product service - Core business logic with proper separation of concerns
222+class ProductService {
223+ constructor(
224+ private database: Database,
225+ private utilityService: UtilityService,
226+ private loggingService: LoggingService,
227+ private notificationService: NotificationService,
228+ private emailService: EmailService,
229+ private validator: ProductValidator,
230+ private authMiddleware: AuthorizationMiddleware,
231+ ) {}
232+
233+ createProduct(
234+ name: string,
235+ price: number,
236+ description: string,
237+ image: string,
238+ category: string,
239+ initialStock: number = 100,
240+ ): string {
241+ // Authorization check
242+ if (!this.authMiddleware.checkAuthorization("create")) {
243+ throw new Error("Unauthorized access");
244+ }
245+
246+ // Validation
247+ if (!this.validator.validate(name, price)) {
248+ throw new Error("Invalid product data");
249+ }
250+
251+ const currentUser = this.database.getUsers()[0]; // This is a placeholder - we'd use proper auth in a real app
252+ const id = this.utilityService.generateId("prod");
253+ const tags = category.split(",").map((t) => t.trim());
254+
255+ // Create product object
256+ const product: Product = {
257+ id,
258+ name,
259+ price,
260+ description,
261+ image,
262+ category,
263+ status: "active" as ProductStatus,
264+ created: new Date(),
265+ createdBy: currentUser.id,
266+ stock: initialStock,
267+ ratings: [],
268+ tags,
269+ lastModified: new Date(),
270+ };
271+
272+ // Save to database
273+ this.database.saveProduct(product);
274+
275+ // Logging
276+ this.loggingService.log("product_added", { id, name, price });
277+
278+ // Notification
279+ this.notificationService.addNotification(
280+ "product_added",
281+ `New product added: ${name}`,
282+ );
283+
284+ return id;
285+ }
286+
287+ updateProduct(id: string, data: Partial<Product>): Product {
288+ // Authorization check
289+ if (!this.authMiddleware.checkAuthorization("update")) {
290+ throw new Error("Unauthorized access");
291+ }
292+
293+ const product = this.database.getProduct(id);
294+ if (!product) {
295+ throw new Error("Product not found");
296+ }
297+
298+ // Create updated product - preventing modification of protected fields
299+ const updatedProduct = { ...product };
300+
301+ Object.keys(data).forEach((key) => {
302+ if (key !== "id" && key !== "created" && key !== "createdBy") {
303+ updatedProduct[key as keyof Product] = data[
304+ key as keyof Product
305+ ] as any;
306+ }
307+ });
308+
309+ const currentUser = this.database.getUsers()[0]; // Placeholder
310+ updatedProduct.lastModified = new Date();
311+ updatedProduct.lastModifiedBy = currentUser.id;
312+
313+ // Save to database
314+ this.database.saveProduct(updatedProduct);
315+
316+ // Logging
317+ this.loggingService.log("product_updated", { id, changes: data });
318+
319+ // Notification
320+ this.notificationService.addNotification(
321+ "product_updated",
322+ `Product updated: ${updatedProduct.name}`,
323+ );
324+
325+ // Handle special status changes
326+ if (data.status === "discontinued") {
327+ this.emailService.sendEmailToSubscribers(
328+ updatedProduct.name,
329+ "Product Discontinued",
330+ `The product ${updatedProduct.name} has been discontinued.`,
331+ );
332+ }
333+
334+ return updatedProduct;
335+ }
336+
337+ deleteProduct(id: string): boolean {
338+ // Authorization check
339+ if (!this.authMiddleware.checkAuthorization("delete")) {
340+ throw new Error("Unauthorized access");
341+ }
342+
343+ const product = this.database.getProduct(id);
344+ if (!product) {
345+ throw new Error("Product not found");
346+ }
347+
348+ // Business rule validation
349+ if (product.status === "active" && product.stock > 0) {
350+ throw new Error("Cannot delete active product with stock");
351+ }
352+
353+ // Delete from database
354+ const result = this.database.removeProduct(id);
355+
356+ // Logging
357+ this.loggingService.log("product_deleted", { id, name: product.name });
358+
359+ // Notification
360+ this.notificationService.addNotification(
361+ "product_deleted",
362+ `Product deleted: ${product.name}`,
363+ );
364+
365+ return result;
366+ }
367+
368+ searchProducts(query: string, filters: SearchFilters = {}): Product[] {
369+ const products = this.database.getAllProducts();
370+ const results = products.filter((product) => {
371+ // Match text search
372+ const matches =
373+ product.name.toLowerCase().includes(query.toLowerCase()) ||
374+ product.description.toLowerCase().includes(query.toLowerCase());
375+
376+ if (!matches) return false;
377+
378+ // Apply filters
379+ if (filters.category && product.category !== filters.category) {
380+ return false;
381+ }
382+
383+ if (filters.minPrice && product.price < filters.minPrice) {
384+ return false;
385+ }
386+
387+ if (filters.maxPrice && product.price > filters.maxPrice) {
388+ return false;
389+ }
390+
391+ if (filters.status && product.status !== filters.status) {
392+ return false;
393+ }
394+
395+ return true;
396+ });
397+
398+ // Log search results
399+ this.loggingService.log("product_search", {
400+ query,
401+ filters,
402+ resultCount: results.length,
403+ });
404+
405+ return results;
406+ }
407+}
408+
409+// Cart service - Single Responsibility for shopping cart functionality
410+class CartService {
411+ constructor(
412+ private database: Database,
413+ private authService: AuthService,
414+ private loggingService: LoggingService,
415+ ) {}
416+
417+ addToCart(productId: string, quantity: number = 1): CartItem[] {
418+ const currentUser = this.authService.getCurrentUser();
419+ if (!currentUser) {
420+ throw new Error("Must be logged in to add to cart");
421+ }
422+
423+ const product = this.database.getProduct(productId);
424+ if (!product) {
425+ throw new Error("Product not found");
426+ }
427+
428+ if (product.status !== "active") {
429+ throw new Error("Product is not available");
430+ }
431+
432+ if (product.stock < quantity) {
433+ throw new Error("Not enough stock");
434+ }
435+
436+ // Get current cart
437+ const cart = this.database.getCart(currentUser.id);
438+
439+ // Update or add item
440+ const existingItemIndex = cart.findIndex(
441+ (item) => item.productId === productId,
442+ );
443+
444+ if (existingItemIndex >= 0) {
445+ cart[existingItemIndex].quantity += quantity;
446+ } else {
447+ cart.push({
448+ productId,
449+ quantity,
450+ price: product.price,
451+ name: product.name,
452+ addedAt: new Date(),
453+ });
454+ }
455+
456+ // Update product stock
457+ product.stock -= quantity;
458+ this.database.saveProduct(product);
459+
460+ // Save cart
461+ this.database.saveCart(currentUser.id, cart);
462+
463+ // Log action
464+ this.loggingService.log("cart_add", {
465+ productId,
466+ quantity,
467+ userId: currentUser.id,
468+ });
469+
470+ return cart;
471+ }
472+}
473+
474+// Service Factory - Creates and wires up the services
475+class ServiceFactory {
476+ static createProductService(): ProductService {
477+ const database = new Database();
478+ const authService = new AuthService(database);
479+ const utilityService = new UtilityService();
480+ const loggingService = new LoggingService(database, authService);
481+ const notificationService = new NotificationService();
482+ const emailService = new EmailService();
483+ const productValidator = new ProductValidator();
484+ const authMiddleware = new ProductAuthorizationMiddleware(authService);
485+
486+ return new ProductService(
487+ database,
488+ utilityService,
489+ loggingService,
490+ notificationService,
491+ emailService,
492+ productValidator,
493+ authMiddleware,
494+ );
495+ }
496+
497+ static createCartService(): CartService {
498+ const database = new Database();
499+ const authService = new AuthService(database);
500+ const loggingService = new LoggingService(database, authService);
501+
502+ return new CartService(database, authService, loggingService);
503+ }
504+}
505+
506+// Example usage:
507+/*
508+const productService = ServiceFactory.createProductService();
509+const cartService = ServiceFactory.createCartService();
510+
511+// Create a product
512+const productId = productService.createProduct(
513+ 'Gaming Laptop',
514+ 1299.99,
515+ 'High performance gaming laptop',
516+ 'laptop.jpg',
517+ 'Electronics,Computers',
518+ 100
519+);
520+
521+// Add to cart
522+cartService.addToCart(productId, 2);
523+*/
524+
525+/*
526+Original Code Smells:
527+
528+Violation of Single Responsibility Principle (SRP)
529+
530+ProductManager class handles product management, cart operations, email sending, UI updates, and analytics
531+Database operations, validation, logging, and notifications are all mixed together
532+
533+
534+Violation of Open/Closed Principle (OCP)
535+
536+Code is not structured to be easily extended without modification
537+Hard-coded business rules and functionality
538+
539+
540+Poor Encapsulation
541+
542+Global variables (DATABASE, CURRENT_USER, NOTIFICATIONS)
543+Direct manipulation of shared state
544+
545+
546+Tight Coupling
547+
548+Business logic directly depends on UI elements (document, window)
549+Authentication checks embedded in business methods
550+
551+
552+Singleton Anti-pattern Misuse
553+
554+Incorrect implementation of the Singleton pattern
555+
556+
557+Lack of Proper Interfaces and Abstraction
558+
559+No clear contracts between components
560+No separation between data access and business logic
561+
562+
563+Code Duplication
564+
565+Authentication checks duplicated across methods
566+Notification and logging logic repeated
567+
568+
569+Poor Error Handling
570+
571+Inconsistent error handling
572+Mixed validation with business operations
573+
574+
575+UI Manipulation in Business Logic
576+
577+Direct DOM manipulation in product methods
578+
579+
580+Hard-coded Values
581+
582+Default stock values
583+Business rules embedded in methods
584+
585+
586+Improvements Made:
587+
588+Applied Single Responsibility Principle (SRP)
589+
590+Created separate classes for distinct responsibilities:
591+Database for data storage
592+AuthService for authentication
593+LoggingService for logging
594+NotificationService for notifications
595+EmailService for email communication
596+ProductService for product business logic
597+CartService for cart operations
598+ProductValidator for validation
599+UtilityService for utility functions
600+
601+
602+Applied Open/Closed Principle (OCP)
603+
604+Used interfaces for extensibility (e.g., AuthorizationMiddleware)
605+Created classes that can be extended without modifying existing code
606+
607+
608+Applied Interface Segregation Principle (ISP)
609+
610+Created focused interfaces for different functionalities
611+Ensured clients only depend on methods they use
612+
613+
614+Applied Dependency Inversion Principle (DIP)
615+
616+High-level modules depend on abstractions
617+Used dependency injection to provide implementations
618+
619+
620+Proper Encapsulation
621+
622+Removed global variables
623+Encapsulated state within appropriate classes
624+
625+
626+Reduced Coupling
627+
628+Removed direct UI manipulation from business logic
629+Used dependency injection for loosely coupled components
630+
631+
632+Implemented Factory Pattern
633+
634+Added ServiceFactory to create and wire up services
635+Simplified client code by hiding implementation details
636+
637+
638+Added Type Safety
639+
640+Created proper interfaces for data structures
641+Used TypeScript types effectively
642+
643+
644+Improved Error Handling
645+
646+Consistent error checking across methods
647+Validation separated from business logic
648+
649+
650+Removed Code Duplication
651+
652+Centralized authentication checks
653+Reused code through proper abstraction
654+*/
added manual-testing-sandbox/next-edit/next-edit-9-5.ts +302 −0
@@ -0,0 +1,302 @@
1+// A messy e-commerce product management system with tangled responsibilities
2+// Difficulty: 5/5
3+
4+type ProductStatus =
5+ | "active"
6+ | "inactive"
7+ | "discontinued"
8+ | "out_of_stock"
9+ | "backorder";
10+type UserRole = "admin" | "manager" | "staff" | "customer";
11+let DATABASE: any = {
12+ products: new Map(),
13+ users: new Map(),
14+ cart: new Map(),
15+ orders: [],
16+ logs: [],
17+ sessions: new Map(),
18+ config: { taxRate: 0.08, discountThreshold: 1000 },
19+};
20+let CURRENT_USER: any = null;
21+let NOTIFICATIONS: any[] = [];
22+
23+// Global function to generate IDs (mixes concerns and not encapsulated)
24+function generateId(prefix: string) {
25+ return `${prefix}_${Math.random().toString(36).substring(2, 9)}`;
26+}
27+
28+// Global function for logging (mixed with business logic)
29+function log(action: string, data: any) {
30+ const timestamp = new Date().toISOString();
31+ DATABASE.logs.push({
32+ timestamp,
33+ action,
34+ data,
35+ user: CURRENT_USER?.username || "system",
36+ });
37+ console.log(`[${timestamp}] ${action}:`, data);
38+}
39+
40+class ProductManager {
41+ // This class does way too much - violates SRP
42+ static instance: ProductManager;
43+ private constructor() {}
44+
45+ // Singleton pattern used incorrectly
46+ static getInstance() {
47+ if (!ProductManager.instance) {
48+ ProductManager.instance = new ProductManager();
49+ }
50+ return ProductManager.instance;
51+ }
52+
53+ addProduct(
54+ name: string,
55+ price: number,
56+ desc: string,
57+ img: string,
58+ category: string,
59+ ) {
60+ // Validation mixed with business logic
61+ if (!name || price <= 0) {
62+ throw new Error("Invalid product data");
63+ }
64+
65+ // Authentication check shouldn't be here
66+ if (
67+ !CURRENT_USER ||
68+ (CURRENT_USER.role !== "admin" && CURRENT_USER.role !== "manager")
69+ ) {
70+ throw new Error("Unauthorized access");
71+ }
72+
73+ const id = generateId("prod");
74+
75+ // Direct database manipulation and notification logic mixed together
76+ DATABASE.products.set(id, {
77+ id,
78+ name,
79+ price,
80+ description: desc,
81+ image: img,
82+ category,
83+ status: "active",
84+ created: new Date(),
85+ createdBy: CURRENT_USER.id,
86+ stock: 100, // Default hardcoded
87+ ratings: [],
88+ tags: category.split(",").map((t: string) => t.trim()),
89+ lastModified: new Date(),
90+ });
91+
92+ // Notification logic should be separated
93+ NOTIFICATIONS.push({
94+ type: "product_added",
95+ message: `New product added: ${name}`,
96+ timestamp: new Date(),
97+ });
98+
99+ // Logging should be a cross-cutting concern
100+ log("product_added", { id, name, price });
101+
102+ // UI manipulation mixed with business logic
103+ if (document) {
104+ const productList = document.getElementById("product-list");
105+ if (productList) {
106+ const productEl = document.createElement("div");
107+ productEl.innerHTML = `<div class="product">${name} - $${price}</div>`;
108+ productList.appendChild(productEl);
109+ }
110+ }
111+
112+ // Analytics tracking mixed in with product creation
113+ if (window) {
114+ try {
115+ (window as any).ga("send", "event", "Products", "Create", name);
116+ } catch (e) {
117+ console.error("Analytics error", e);
118+ }
119+ }
120+
121+ return id;
122+ }
123+
124+ updateProduct(id: string, data: any) {
125+ if (!DATABASE.products.has(id)) {
126+ throw new Error("Product not found");
127+ }
128+
129+ // Authentication check duplicated
130+ if (
131+ !CURRENT_USER ||
132+ (CURRENT_USER.role !== "admin" && CURRENT_USER.role !== "manager")
133+ ) {
134+ throw new Error("Unauthorized access");
135+ }
136+
137+ const product = DATABASE.products.get(id);
138+
139+ // Updating with direct object manipulation
140+ Object.keys(data).forEach((key) => {
141+ if (key !== "id" && key !== "created" && key !== "createdBy") {
142+ product[key] = data[key];
143+ }
144+ });
145+
146+ product.lastModified = new Date();
147+ product.lastModifiedBy = CURRENT_USER.id;
148+
149+ DATABASE.products.set(id, product);
150+
151+ // More mixed responsibilities
152+ log("product_updated", { id, changes: data });
153+
154+ // Duplicated notification logic
155+ NOTIFICATIONS.push({
156+ type: "product_updated",
157+ message: `Product updated: ${product.name}`,
158+ timestamp: new Date(),
159+ });
160+
161+ // Email notification logic mixed in
162+ if (product.status === "discontinued") {
163+ this.sendEmailToSubscribers(
164+ product.id,
165+ "Product Discontinued",
166+ `The product ${product.name} has been discontinued.`,
167+ );
168+ }
169+
170+ return product;
171+ }
172+
173+ deleteProduct(id: string) {
174+ // More authentication mixed in business logic
175+ if (!CURRENT_USER || CURRENT_USER.role !== "admin") {
176+ throw new Error("Only admins can delete products");
177+ }
178+
179+ if (!DATABASE.products.has(id)) {
180+ throw new Error("Product not found");
181+ }
182+
183+ const product = DATABASE.products.get(id);
184+
185+ // Business rules mixed with deletion logic
186+ if (product.status === "active" && product.stock > 0) {
187+ throw new Error("Cannot delete active product with stock");
188+ }
189+
190+ // More mixed concerns
191+ log("product_deleted", { id, name: product.name });
192+ NOTIFICATIONS.push({
193+ type: "product_deleted",
194+ message: `Product deleted: ${product.name}`,
195+ timestamp: new Date(),
196+ });
197+
198+ DATABASE.products.delete(id);
199+
200+ // Cache clearing mixed with business logic
201+ if (window && (window as any).cache) {
202+ (window as any).cache.invalidate("products");
203+ }
204+
205+ return true;
206+ }
207+
208+ // Email functionality mixed in the product manager
209+ sendEmailToSubscribers(productId: string, subject: string, body: string) {
210+ const product = DATABASE.products.get(productId);
211+ if (!product) return;
212+
213+ // Email sending logic mixed with product management
214+ console.log(`Sending email about ${product.name} to subscribers`);
215+ // Imagine API call to email service here
216+ }
217+
218+ // Search functionality mixed in the same class
219+ searchProducts(query: string, filters: any = {}) {
220+ let results: any[] = [];
221+
222+ DATABASE.products.forEach((product: any) => {
223+ let matches =
224+ product.name.toLowerCase().includes(query.toLowerCase()) ||
225+ product.description.toLowerCase().includes(query.toLowerCase());
226+
227+ if (!matches) return;
228+
229+ // Filter logic mixed in search
230+ if (filters.category && product.category !== filters.category) {
231+ return;
232+ }
233+
234+ if (filters.minPrice && product.price < filters.minPrice) {
235+ return;
236+ }
237+
238+ if (filters.maxPrice && product.price > filters.maxPrice) {
239+ return;
240+ }
241+
242+ if (filters.status && product.status !== filters.status) {
243+ return;
244+ }
245+
246+ results.push({ ...product });
247+ });
248+
249+ // Logging mixed with search functionality
250+ log("product_search", { query, filters, resultCount: results.length });
251+
252+ return results;
253+ }
254+
255+ // Cart functionality shouldn't be in product manager
256+ addToCart(productId: string, quantity: number = 1) {
257+ if (!CURRENT_USER) {
258+ throw new Error("Must be logged in to add to cart");
259+ }
260+
261+ const product = DATABASE.products.get(productId);
262+ if (!product) {
263+ throw new Error("Product not found");
264+ }
265+
266+ if (product.status !== "active") {
267+ throw new Error("Product is not available");
268+ }
269+
270+ if (product.stock < quantity) {
271+ throw new Error("Not enough stock");
272+ }
273+
274+ let cart = DATABASE.cart.get(CURRENT_USER.id) || [];
275+ const existingItem = cart.find((item: any) => item.productId === productId);
276+
277+ if (existingItem) {
278+ existingItem.quantity += quantity;
279+ } else {
280+ cart.push({
281+ productId,
282+ quantity,
283+ price: product.price,
284+ name: product.name,
285+ addedAt: new Date(),
286+ });
287+ }
288+
289+ DATABASE.cart.set(CURRENT_USER.id, cart);
290+ product.stock -= quantity;
291+ DATABASE.products.set(productId, product);
292+
293+ log("cart_add", { productId, quantity, userId: CURRENT_USER.id });
294+
295+ return cart;
296+ }
297+}
298+
299+// Usage would be something like:
300+// const pm = ProductManager.getInstance();
301+// pm.addProduct('Gaming Laptop', 1299.99, 'High performance gaming laptop', 'laptop.jpg', 'Electronics,Computers');
302+// pm.addToCart('prod_1abc123', 2);
added manual-testing-sandbox/next-edit/next-edit-test-1.ts +3 −0
@@ -0,0 +1,3 @@
1+function foo(a: string, b: string, c: string) {
2+ return `${a} ${b.length} ${c.length}`;
3+}
added manual-testing-sandbox/next-edit/next-edit-test-2.ts +91 −0
@@ -0,0 +1,91 @@
1+type DocumentNode = ParagraphNode | ListNode;
2+
3+abstract class Node {
4+ abstract render(): string;
5+}
6+
7+class ParagraphNode extends Node {
8+ constructor(public text: string) {
9+ super();
10+ }
11+
12+ render(): string {
13+ return `<p>${this.text}</p>`;
14+ }
15+}
16+
17+class ListNode extends Node {
18+ constructor(public items: string[]) {
19+ super();
20+ }
21+
22+ render(): string {
23+ return `<ul>${this.items.map((item) => `<li>${item}</li>`).join("")}</ul>`;
24+ }
25+}
26+
27+interface Command {
28+ execute(): void;
29+ undo(): void;
30+}
31+
32+interface Observer {
33+ update(doc: DocumentEditor): void;
34+}
35+
36+class DocumentEditor {
37+ private nodes: DocumentNode[] = [];
38+ private undoStack: Command[] = [];
39+ private redoStack: Command[] = [];
40+ private observers: Observer[] = [];
41+
42+ addNode(node: DocumentNode) {
43+ this.nodes.push(node);
44+ this.notify();
45+ }
46+
47+ executeCommand(command: Command) {
48+ command.execute();
49+ this.undoStack.push(command);
50+ this.redoStack = [];
51+ this.notify();
52+ }
53+
54+ undo() {
55+ const cmd = this.undoStack.pop();
56+ if (cmd) {
57+ cmd.undo();
58+ this.redoStack.push(cmd);
59+ this.notify();
60+ }
61+ }
62+
63+ redo() {
64+ const cmd = this.redoStack.pop();
65+ if (cmd) {
66+ cmd.execute();
67+ this.undoStack.push(cmd);
68+ this.notify();
69+ }
70+ }
71+
72+ getContent(): string {
73+ return this.nodes.map((n) => n.render()).join("\n");
74+ }
75+
76+ getNodes(): DocumentNode[] {
77+ return this.nodes;
78+ }
79+
80+ setNodes(nodes: DocumentNode[]) {
81+ this.nodes = nodes;
82+ }
83+
84+ subscribe(observer: Observer) {
85+ this.observers.push(observer);
86+ }
87+
88+ private notify() {
89+ this.observers.forEach((o) => o.update(this));
90+ }
91+}
modified packages/config-yaml/src/schemas/data/index.ts +24 −0
@@ -28,6 +28,16 @@
2828 editInteractionEventSchema_0_2_0,
2929 editInteractionEventSchema_0_2_0_noCode,
3030 } from "./editInteraction/v0.2.0.js";
31+import { editOutcomeEventAllSchema } from "./editOutcome/index.js";
32+import {
33+ editOutcomeEventSchema_0_2_0,
34+ editOutcomeEventSchema_0_2_0_noCode,
35+} from "./editOutcome/v0.2.0.js";
36+import { nextEditEventAllSchema } from "./nextEdit/index.js";
37+import {
38+ nextEditEventSchema_0_2_0,
39+ nextEditEventSchema_0_2_0_noCode,
40+} from "./nextEdit/v0.2.0.js";
3141 import { quickEditEventAllSchema } from "./quickEdit/index.js";
3242 import {
3343 quickEditEventSchema_0_1_0,
@@ -42,6 +52,11 @@
4252 tokensGeneratedEventSchema_0_2_0,
4353 tokensGeneratedEventSchema_0_2_0_noCode,
4454 } from "./tokensGenerated/v0.2.0.js";
55+import { toolUsageEventAllSchema } from "./toolUsage/index.js";
56+import {
57+ toolUsageEventSchema_0_2_0,
58+ toolUsageEventSchema_0_2_0_noCode,
59+} from "./toolUsage/v0.2.0.js";
4560
4661 const semverRegex =
4762 /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
@@ -72,6 +87,9 @@
7287 tokensGenerated: tokensGeneratedEventAllSchema,
7388 chatInteraction: chatInteractionEventAllSchema,
7489 editInteraction: editInteractionEventAllSchema,
90+ editOutcome: editOutcomeEventAllSchema,
91+ nextEdit: nextEditEventAllSchema,
92+ toolUsage: toolUsageEventAllSchema,
7593 });
7694
7795 // Version and level specific schemas are organized here
@@ -97,6 +115,9 @@
97115 tokensGenerated: tokensGeneratedEventSchema_0_2_0,
98116 chatInteraction: chatInteractionEventSchema_0_2_0,
99117 editInteraction: editInteractionEventSchema_0_2_0,
118+ editOutcome: editOutcomeEventSchema_0_2_0,
119+ nextEdit: nextEditEventSchema_0_2_0,
120+ toolUsage: toolUsageEventSchema_0_2_0,
100121 },
101122 noCode: {
102123 autocomplete: autocompleteEventSchema_0_2_0_noCode,
@@ -104,6 +125,9 @@
104125 tokensGenerated: tokensGeneratedEventSchema_0_2_0_noCode,
105126 chatInteraction: chatInteractionEventSchema_0_2_0_noCode,
106127 editInteraction: editInteractionEventSchema_0_2_0_noCode,
128+ editOutcome: editOutcomeEventSchema_0_2_0_noCode,
129+ nextEdit: nextEditEventSchema_0_2_0_noCode,
130+ toolUsage: toolUsageEventSchema_0_2_0_noCode,
107131 },
108132 },
109133 };
added packages/config-yaml/src/schemas/data/nextEdit/index.ts +12 −0
@@ -0,0 +1,12 @@
1+import { z } from "zod";
2+import { baseDevDataAllSchema } from "../base.js";
3+
4+export const nextEditEventAllSchema = baseDevDataAllSchema.extend({
5+ fileURI: z.string(),
6+ workspaceDirURI: z.string(),
7+ beforeContent: z.string(),
8+ afterContent: z.string(),
9+ beforeCursorPos: z.object({ line: z.number(), character: z.number() }),
10+ afterCursorPos: z.object({ line: z.number(), character: z.number() }),
11+ context: z.string(),
12+});
added packages/config-yaml/src/schemas/data/nextEdit/v0.2.0.ts +28 −0
@@ -0,0 +1,28 @@
1+import { nextEditEventAllSchema } from "./index.js";
2+
3+export const nextEditEventSchema_0_2_0 = nextEditEventAllSchema.pick({
4+ // base
5+ timestamp: true,
6+ userId: true,
7+ userAgent: true,
8+ selectedProfileId: true,
9+ eventName: true,
10+ schema: true,
11+
12+ // nextedit-specific
13+ fileURI: true,
14+ workspaceDirURI: true,
15+ beforeContent: true,
16+ afterContent: true,
17+ beforeCursorPos: true,
18+ afterCursorPos: true,
19+ context: true,
20+});
21+
22+export const nextEditEventSchema_0_2_0_noCode = nextEditEventSchema_0_2_0.omit({
23+ fileURI: true,
24+ workspaceDirURI: true,
25+ beforeContent: true,
26+ afterContent: true,
27+ context: true,
28+});
added packages/config-yaml/src/schemas/data/toolUsage/index.ts +12 −0
@@ -0,0 +1,12 @@
1+import { z } from "zod";
2+import { baseDevDataAllSchema } from "../base.js";
3+
4+export const toolUsageEventAllSchema = baseDevDataAllSchema.extend({
5+ toolCallId: z.string(),
6+ functionName: z.string(),
7+ functionArgs: z.string(),
8+ toolCallArgs: z.any(),
9+ parsedArgs: z.any(),
10+ succeeded: z.boolean(),
11+ output: z.array(z.any()).optional(),
12+});
added packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts +27 −0
@@ -0,0 +1,27 @@
1+import { toolUsageEventAllSchema } from "./index.js";
2+
3+export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({
4+ // base
5+ timestamp: true,
6+ userId: true,
7+ userAgent: true,
8+ selectedProfileId: true,
9+ eventName: true,
10+ schema: true,
11+
12+ // tool-usage-specific
13+ toolCallId: true,
14+ functionName: true,
15+ functionArgs: true,
16+ toolCallArgs: true,
17+ parsedArgs: true,
18+ succeeded: true,
19+ output: true,
20+});
21+
22+export const toolUsageEventSchema_0_2_0_noCode =
23+ toolUsageEventSchema_0_2_0.omit({
24+ functionArgs: true,
25+ parsedArgs: true,
26+ output: true,
27+ });
modified packages/config-yaml/src/schemas/models.ts +3 −0
@@ -45,6 +45,9 @@
4545 temperature: z.number().optional(),
4646 topP: z.number().optional(),
4747 topK: z.number().optional(),
48+ minP: z.number().optional(),
49+ presencePenalty: z.number().optional(),
50+ frequencyPenalty: z.number().optional(),
4851 stop: z.array(z.string()).optional(),
4952 n: z.number().optional(),
5053 reasoning: z.boolean().optional(),