Changesets · Branches · Tags · Compare
| Changeset | e1f06c4b50bfc612d2482ccda0461e963472a704933b6a28f5952fc2a8ad41b5 |
|---|---|
| Author | Kai Wu <wukaixingxp@gmail.com> · 2025-07-02 09:08 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-07-02 09:08 -07:00 |
| Parents | 03b3165c926f, fc1d06ba6663 |
80 files changed
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 | +}); |
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 | +}); |
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 | -}); |
modified core/config/util.ts +1 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | JSONModelDescription, |
| 11 | 11 | PromptTemplate, |
| 12 | 12 | } from "../"; |
| 13 | -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; | |
| 13 | +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; | |
| 14 | 14 | import { GlobalContext } from "../util/GlobalContext"; |
| 15 | 15 | import { editConfigFile } from "../util/paths"; |
| 16 | 16 |
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 | +}); |
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 +9 −1
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { BaseContextProvider } from "../"; |
| 2 | 2 | import { ContextProviderName } from "../../"; |
| 3 | +import { Telemetry } from "../../util/posthog"; | |
| 3 | 4 | |
| 4 | 5 | import ClipboardContextProvider from "./ClipboardContextProvider"; |
| 5 | 6 | import CodebaseContextProvider from "./CodebaseContextProvider"; |
| @@ -75,5 +76,12 @@ | ||
| 75 | 76 | export function contextProviderClassFromName( |
| 76 | 77 | name: ContextProviderName, |
| 77 | 78 | ): typeof BaseContextProvider | undefined { |
| 78 | - 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; | |
| 79 | 87 | } |
modified core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +1 −1
| @@ -107,7 +107,7 @@ | ||
| 107 | 107 | chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); |
| 108 | 108 | |
| 109 | 109 | results.sort( |
| 110 | - (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], | |
| 110 | + (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!], | |
| 111 | 111 | ); |
| 112 | 112 | results = results.slice(-this.options.nFinal); |
| 113 | 113 | 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 +7 −1
| @@ -872,7 +872,7 @@ | ||
| 872 | 872 | this.messenger.send("toolCallPartialOutput", params); |
| 873 | 873 | }; |
| 874 | 874 | |
| 875 | - return await callTool(tool, toolCall, { | |
| 875 | + const result = await callTool(tool, toolCall, { | |
| 876 | 876 | config, |
| 877 | 877 | ide: this.ide, |
| 878 | 878 | llm: config.selectedModelByRole.chat, |
| @@ -883,6 +883,8 @@ | ||
| 883 | 883 | onPartialOutput, |
| 884 | 884 | codeBaseIndexer: this.codeBaseIndexer, |
| 885 | 885 | }); |
| 886 | + | |
| 887 | + return result; | |
| 886 | 888 | } |
| 887 | 889 | |
| 888 | 890 | private async isItemTooBig(item: ContextItemWithId) { |
| @@ -1105,6 +1107,10 @@ | ||
| 1105 | 1107 | itemId: uuidv4(), |
| 1106 | 1108 | }; |
| 1107 | 1109 | |
| 1110 | + void Telemetry.capture("context_provider_get_context_items", { | |
| 1111 | + name: provider.description.title, | |
| 1112 | + }); | |
| 1113 | + | |
| 1108 | 1114 | const items = await provider.getContextItems(query, { |
| 1109 | 1115 | config, |
| 1110 | 1116 | llm, |
modified core/edit/streamDiffLines.ts +2 −2
| @@ -112,7 +112,7 @@ | ||
| 112 | 112 | // If any rules are present this will result in using chat instead of legacy completion |
| 113 | 113 | const systemMessage = rulesToInclude |
| 114 | 114 | ? getSystemMessageWithRules({ |
| 115 | - rules: rulesToInclude, | |
| 115 | + availableRules: rulesToInclude, | |
| 116 | 116 | userMessage: |
| 117 | 117 | typeof prompt === "string" |
| 118 | 118 | ? ({ |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | ) as UserChatMessage | ToolResultChatMessage | undefined), |
| 126 | 126 | baseSystemMessage: undefined, |
| 127 | 127 | contextItems: [], |
| 128 | - }) | |
| 128 | + }).systemMessage | |
| 129 | 129 | : undefined; |
| 130 | 130 | |
| 131 | 131 | if (systemMessage) { |
deleted core/llm/constructMessages.ts +0 −187
| @@ -1,187 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - ChatHistoryItem, | |
| 3 | - ChatMessage, | |
| 4 | - ContextItemWithId, | |
| 5 | - RuleWithSource, | |
| 6 | - TextMessagePart, | |
| 7 | - ToolResultChatMessage, | |
| 8 | - UserChatMessage, | |
| 9 | -} from "../"; | |
| 10 | -import { findLast } from "../util/findLast"; | |
| 11 | -import { normalizeToMessageParts } from "../util/messageContent"; | |
| 12 | -import { isUserOrToolMsg } from "./messages"; | |
| 13 | -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; | |
| 14 | -import { RulePolicies } from "./rules/types"; | |
| 15 | - | |
| 16 | -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = | |
| 17 | - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; | |
| 18 | - | |
| 19 | -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = | |
| 20 | - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; | |
| 21 | - | |
| 22 | -export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ | |
| 23 | - Always include the language and file name in the info string when you write code blocks. | |
| 24 | - If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' | |
| 25 | -`; | |
| 26 | - | |
| 27 | -export const EDIT_CODE_INSTRUCTIONS = `\ | |
| 28 | - When addressing code modification requests, present a concise code snippet that | |
| 29 | - emphasizes only the necessary changes and uses abbreviated placeholders for | |
| 30 | - unmodified sections. For example: | |
| 31 | - | |
| 32 | - \`\`\`language /path/to/file | |
| 33 | - // ... existing code ... | |
| 34 | - | |
| 35 | - {{ modified code here }} | |
| 36 | - | |
| 37 | - // ... existing code ... | |
| 38 | - | |
| 39 | - {{ another modification }} | |
| 40 | - | |
| 41 | - // ... rest of code ... | |
| 42 | - \`\`\` | |
| 43 | - | |
| 44 | - In existing files, you should always restate the function or class that the snippet belongs to: | |
| 45 | - | |
| 46 | - \`\`\`language /path/to/file | |
| 47 | - // ... existing code ... | |
| 48 | - | |
| 49 | - function exampleFunction() { | |
| 50 | - // ... existing code ... | |
| 51 | - | |
| 52 | - {{ modified code here }} | |
| 53 | - | |
| 54 | - // ... rest of function ... | |
| 55 | - } | |
| 56 | - | |
| 57 | - // ... rest of code ... | |
| 58 | - \`\`\` | |
| 59 | - | |
| 60 | - Since users have access to their complete file, they prefer reading only the | |
| 61 | - relevant modifications. It's perfectly acceptable to omit unmodified portions | |
| 62 | - at the beginning, middle, or end of files using these "lazy" comments. Only | |
| 63 | - provide the complete file when explicitly requested. Include a concise explanation | |
| 64 | - of changes unless the user specifically asks for code only. | |
| 65 | -`; | |
| 66 | - | |
| 67 | -export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ | |
| 68 | -<important_rules> | |
| 69 | - You are in chat mode. | |
| 70 | - | |
| 71 | - If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. | |
| 72 | - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. | |
| 73 | - | |
| 74 | -${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 75 | -${EDIT_CODE_INSTRUCTIONS} | |
| 76 | -</important_rules>`; | |
| 77 | - | |
| 78 | -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ | |
| 79 | -<important_rules> | |
| 80 | - You are in agent mode. | |
| 81 | - | |
| 82 | -${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 83 | -</important_rules>`; | |
| 84 | - | |
| 85 | -/** | |
| 86 | - * Helper function to get the context items for a user message | |
| 87 | - */ | |
| 88 | -function getUserContextItems( | |
| 89 | - userMsg: UserChatMessage | ToolResultChatMessage | undefined, | |
| 90 | - history: ChatHistoryItem[], | |
| 91 | -): ContextItemWithId[] { | |
| 92 | - if (!userMsg) return []; | |
| 93 | - | |
| 94 | - // Find the history item that contains the userMsg | |
| 95 | - const historyItem = history.find((item) => { | |
| 96 | - // Check if the message ID matches | |
| 97 | - if ("id" in userMsg && "id" in item.message) { | |
| 98 | - return (item.message as any).id === (userMsg as any).id; | |
| 99 | - } | |
| 100 | - // Fallback to content comparison | |
| 101 | - return ( | |
| 102 | - item.message.content === userMsg.content && | |
| 103 | - item.message.role === userMsg.role | |
| 104 | - ); | |
| 105 | - }); | |
| 106 | - | |
| 107 | - return historyItem?.contextItems || []; | |
| 108 | -} | |
| 109 | - | |
| 110 | -export function constructMessages( | |
| 111 | - messageMode: string, | |
| 112 | - history: ChatHistoryItem[], | |
| 113 | - baseChatOrAgentSystemMessage: string | undefined, | |
| 114 | - rules: RuleWithSource[], | |
| 115 | - rulePolicies?: RulePolicies, | |
| 116 | -): ChatMessage[] { | |
| 117 | - const filteredHistory = history.filter( | |
| 118 | - (item) => item.message.role !== "system", | |
| 119 | - ); | |
| 120 | - const msgs: ChatMessage[] = []; | |
| 121 | - | |
| 122 | - for (let i = 0; i < filteredHistory.length; i++) { | |
| 123 | - const historyItem = filteredHistory[i]; | |
| 124 | - | |
| 125 | - if (messageMode === "chat") { | |
| 126 | - const toolMessage: ToolResultChatMessage = | |
| 127 | - historyItem.message as ToolResultChatMessage; | |
| 128 | - if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { | |
| 129 | - // remove all tool calls from the history | |
| 130 | - continue; | |
| 131 | - } | |
| 132 | - } | |
| 133 | - | |
| 134 | - if (historyItem.message.role === "user") { | |
| 135 | - // Gather context items for user messages | |
| 136 | - let content = normalizeToMessageParts(historyItem.message); | |
| 137 | - | |
| 138 | - const ctxItems = historyItem.contextItems | |
| 139 | - .map((ctxItem) => { | |
| 140 | - return { | |
| 141 | - type: "text", | |
| 142 | - text: `${ctxItem.content}\n`, | |
| 143 | - } as TextMessagePart; | |
| 144 | - }) | |
| 145 | - .filter((part) => !!part.text.trim()); | |
| 146 | - | |
| 147 | - content = [...ctxItems, ...content]; | |
| 148 | - msgs.push({ | |
| 149 | - ...historyItem.message, | |
| 150 | - content, | |
| 151 | - }); | |
| 152 | - } else { | |
| 153 | - msgs.push(historyItem.message); | |
| 154 | - } | |
| 155 | - } | |
| 156 | - | |
| 157 | - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as | |
| 158 | - | UserChatMessage | |
| 159 | - | ToolResultChatMessage | |
| 160 | - | undefined; | |
| 161 | - | |
| 162 | - // Get context items for the last user message | |
| 163 | - const lastUserContextItems = getUserContextItems( | |
| 164 | - lastUserMsg, | |
| 165 | - filteredHistory, | |
| 166 | - ); | |
| 167 | - const systemMessage = getSystemMessageWithRules({ | |
| 168 | - baseSystemMessage: baseChatOrAgentSystemMessage, | |
| 169 | - rules, | |
| 170 | - userMessage: lastUserMsg, | |
| 171 | - contextItems: lastUserContextItems, | |
| 172 | - rulePolicies, | |
| 173 | - }); | |
| 174 | - | |
| 175 | - if (systemMessage.trim()) { | |
| 176 | - msgs.unshift({ | |
| 177 | - role: "system", | |
| 178 | - content: systemMessage, | |
| 179 | - }); | |
| 180 | - } | |
| 181 | - | |
| 182 | - // Remove the "id" from all of the messages | |
| 183 | - return msgs.map((msg) => { | |
| 184 | - const { id, ...rest } = msg as any; | |
| 185 | - return rest; | |
| 186 | - }); | |
| 187 | -} |
added core/llm/defaultSystemMessages.ts +68 −0
| @@ -0,0 +1,68 @@ | ||
| 1 | +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = | |
| 2 | + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; | |
| 3 | + | |
| 4 | +export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = | |
| 5 | + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; | |
| 6 | + | |
| 7 | +export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ | |
| 8 | + Always include the language and file name in the info string when you write code blocks. | |
| 9 | + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' | |
| 10 | +`; | |
| 11 | + | |
| 12 | +export const EDIT_CODE_INSTRUCTIONS = `\ | |
| 13 | + When addressing code modification requests, present a concise code snippet that | |
| 14 | + emphasizes only the necessary changes and uses abbreviated placeholders for | |
| 15 | + unmodified sections. For example: | |
| 16 | + | |
| 17 | + \`\`\`language /path/to/file | |
| 18 | + // ... existing code ... | |
| 19 | + | |
| 20 | + {{ modified code here }} | |
| 21 | + | |
| 22 | + // ... existing code ... | |
| 23 | + | |
| 24 | + {{ another modification }} | |
| 25 | + | |
| 26 | + // ... rest of code ... | |
| 27 | + \`\`\` | |
| 28 | + | |
| 29 | + In existing files, you should always restate the function or class that the snippet belongs to: | |
| 30 | + | |
| 31 | + \`\`\`language /path/to/file | |
| 32 | + // ... existing code ... | |
| 33 | + | |
| 34 | + function exampleFunction() { | |
| 35 | + // ... existing code ... | |
| 36 | + | |
| 37 | + {{ modified code here }} | |
| 38 | + | |
| 39 | + // ... rest of function ... | |
| 40 | + } | |
| 41 | + | |
| 42 | + // ... rest of code ... | |
| 43 | + \`\`\` | |
| 44 | + | |
| 45 | + Since users have access to their complete file, they prefer reading only the | |
| 46 | + relevant modifications. It's perfectly acceptable to omit unmodified portions | |
| 47 | + at the beginning, middle, or end of files using these "lazy" comments. Only | |
| 48 | + provide the complete file when explicitly requested. Include a concise explanation | |
| 49 | + of changes unless the user specifically asks for code only. | |
| 50 | +`; | |
| 51 | + | |
| 52 | +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ | |
| 53 | +<important_rules> | |
| 54 | + You are in chat mode. | |
| 55 | + | |
| 56 | + If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. | |
| 57 | + If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. | |
| 58 | + | |
| 59 | +${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 60 | +${EDIT_CODE_INSTRUCTIONS} | |
| 61 | +</important_rules>`; | |
| 62 | + | |
| 63 | +export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ | |
| 64 | +<important_rules> | |
| 65 | + You are in agent mode. | |
| 66 | + | |
| 67 | +${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 68 | +</important_rules>`; |
modified core/llm/llms/Bedrock.test.ts +248 −80
| @@ -1,12 +1,10 @@ | ||
| 1 | -import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; | |
| 2 | -import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; | |
| 3 | -import Bedrock from "./Bedrock.js"; | |
| 4 | 1 | import { |
| 5 | 2 | ChatMessage, |
| 6 | 3 | Chunk, |
| 7 | 4 | CompletionOptions, |
| 8 | 5 | UserChatMessage, |
| 9 | 6 | } from "../../index.js"; |
| 7 | +import Bedrock from "./Bedrock.js"; | |
| 10 | 8 | |
| 11 | 9 | // Mock AWS SDK |
| 12 | 10 | jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ |
| @@ -317,96 +315,266 @@ | ||
| 317 | 315 | }); |
| 318 | 316 | }); |
| 319 | 317 | |
| 320 | - it("should convert text messages correctly", () => { | |
| 321 | - const message: ChatMessage = { | |
| 322 | - role: "user", | |
| 323 | - content: "Hello", | |
| 324 | - } as UserChatMessage; | |
| 325 | - const converted = bedrock["_convertMessage"](message); | |
| 326 | - expect(converted).toEqual({ | |
| 327 | - role: "user", | |
| 328 | - content: [{ text: "Hello" }], | |
| 329 | - }); | |
| 318 | + it("should convert simple user and assistant messages correctly", () => { | |
| 319 | + const messages: ChatMessage[] = [ | |
| 320 | + { role: "user", content: "Hello" } as UserChatMessage, | |
| 321 | + { role: "assistant", content: "Hi there" }, | |
| 322 | + ]; | |
| 323 | + | |
| 324 | + const availableTools = new Set<string>(); | |
| 325 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 326 | + | |
| 327 | + expect(converted).toEqual([ | |
| 328 | + { role: "user", content: [{ text: "Hello" }] }, | |
| 329 | + { role: "assistant", content: [{ text: "Hi there" }] }, | |
| 330 | + ]); | |
| 330 | 331 | }); |
| 331 | 332 | |
| 332 | - it("should convert tool responses correctly", () => { | |
| 333 | - const message: ChatMessage = { | |
| 334 | - role: "tool", | |
| 335 | - content: "Tool result", | |
| 336 | - toolCallId: "tool-1", | |
| 337 | - }; | |
| 338 | - const converted = bedrock["_convertMessage"](message); | |
| 339 | - expect(converted).toEqual({ | |
| 340 | - role: "user", | |
| 341 | - content: [ | |
| 342 | - { | |
| 343 | - toolResult: { | |
| 344 | - toolUseId: "tool-1", | |
| 345 | - content: [{ text: "Tool result" }], | |
| 333 | + it("should handle tool responses correctly", () => { | |
| 334 | + const messages: ChatMessage[] = [ | |
| 335 | + { role: "user", content: "Use a tool" } as UserChatMessage, | |
| 336 | + { | |
| 337 | + role: "assistant", | |
| 338 | + content: "", | |
| 339 | + toolCalls: [ | |
| 340 | + { | |
| 341 | + id: "tool-1", | |
| 342 | + type: "function", | |
| 343 | + function: { | |
| 344 | + name: "test_tool", | |
| 345 | + arguments: '{"arg":"value"}', | |
| 346 | + }, | |
| 346 | 347 | }, |
| 347 | - }, | |
| 348 | - ], | |
| 349 | - }); | |
| 348 | + ], | |
| 349 | + }, | |
| 350 | + { | |
| 351 | + role: "tool", | |
| 352 | + content: "Tool result", | |
| 353 | + toolCallId: "tool-1", | |
| 354 | + }, | |
| 355 | + ]; | |
| 356 | + | |
| 357 | + const availableTools = new Set(["test_tool"]); | |
| 358 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 359 | + | |
| 360 | + expect(converted).toEqual([ | |
| 361 | + { role: "user", content: [{ text: "Use a tool" }] }, | |
| 362 | + { | |
| 363 | + role: "assistant", | |
| 364 | + content: [ | |
| 365 | + { | |
| 366 | + toolUse: { | |
| 367 | + toolUseId: "tool-1", | |
| 368 | + name: "test_tool", | |
| 369 | + input: { arg: "value" }, | |
| 370 | + }, | |
| 371 | + }, | |
| 372 | + ], | |
| 373 | + }, | |
| 374 | + { | |
| 375 | + role: "user", | |
| 376 | + content: [ | |
| 377 | + { | |
| 378 | + toolResult: { | |
| 379 | + toolUseId: "tool-1", | |
| 380 | + content: [{ text: "Tool result" }], | |
| 381 | + }, | |
| 382 | + }, | |
| 383 | + ], | |
| 384 | + }, | |
| 385 | + ]); | |
| 350 | 386 | }); |
| 351 | 387 | |
| 352 | - it("should convert tool calls correctly", () => { | |
| 353 | - const message: ChatMessage = { | |
| 354 | - role: "assistant", | |
| 355 | - content: "", | |
| 356 | - toolCalls: [ | |
| 357 | - { | |
| 358 | - id: "tool-1", | |
| 359 | - type: "function" as const, | |
| 360 | - function: { | |
| 361 | - name: "test_tool", | |
| 362 | - arguments: '{"arg":"value"}', | |
| 388 | + it("should handle tool calls with unavailable tools as text", () => { | |
| 389 | + const messages: ChatMessage[] = [ | |
| 390 | + { role: "user", content: "Use a tool" } as UserChatMessage, | |
| 391 | + { | |
| 392 | + role: "assistant", | |
| 393 | + content: "", | |
| 394 | + toolCalls: [ | |
| 395 | + { | |
| 396 | + id: "tool-1", | |
| 397 | + type: "function", | |
| 398 | + function: { | |
| 399 | + name: "unavailable_tool", | |
| 400 | + arguments: '{"arg":"value"}', | |
| 401 | + }, | |
| 363 | 402 | }, |
| 364 | - }, | |
| 365 | - ], | |
| 366 | - }; | |
| 367 | - const converted = bedrock["_convertMessage"](message); | |
| 368 | - expect(converted).toEqual({ | |
| 369 | - role: "assistant", | |
| 370 | - content: [ | |
| 371 | - { | |
| 372 | - toolUse: { | |
| 373 | - toolUseId: "tool-1", | |
| 374 | - name: "test_tool", | |
| 375 | - input: { arg: "value" }, | |
| 403 | + ], | |
| 404 | + }, | |
| 405 | + ]; | |
| 406 | + | |
| 407 | + // Empty set means no tools are available | |
| 408 | + const availableTools = new Set<string>(); | |
| 409 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 410 | + | |
| 411 | + expect(converted).toEqual([ | |
| 412 | + { role: "user", content: [{ text: "Use a tool" }] }, | |
| 413 | + { | |
| 414 | + role: "assistant", | |
| 415 | + content: [ | |
| 416 | + { | |
| 417 | + text: expect.stringContaining("Assistant tool call:"), | |
| 376 | 418 | }, |
| 377 | - }, | |
| 378 | - ], | |
| 379 | - }); | |
| 419 | + ], | |
| 420 | + }, | |
| 421 | + ]); | |
| 380 | 422 | }); |
| 381 | 423 | |
| 382 | - it("should handle multimodal content correctly", () => { | |
| 383 | - const message: ChatMessage = { | |
| 384 | - role: "user", | |
| 385 | - content: [ | |
| 386 | - { type: "text", text: "Look at this image:" }, | |
| 387 | - { | |
| 388 | - type: "imageUrl", | |
| 389 | - imageUrl: { | |
| 390 | - url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", | |
| 424 | + it("should handle thinking messages correctly", () => { | |
| 425 | + const messages: ChatMessage[] = [ | |
| 426 | + { role: "user", content: "Think about this" } as UserChatMessage, | |
| 427 | + { role: "thinking", content: "I am thinking about the solution" }, | |
| 428 | + { role: "assistant", content: "Here's my answer" }, | |
| 429 | + ]; | |
| 430 | + | |
| 431 | + const availableTools = new Set<string>(); | |
| 432 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 433 | + | |
| 434 | + expect(converted).toEqual([ | |
| 435 | + { role: "user", content: [{ text: "Think about this" }] }, | |
| 436 | + { | |
| 437 | + role: "assistant", | |
| 438 | + content: [ | |
| 439 | + { | |
| 440 | + reasoningContent: { | |
| 441 | + reasoningText: { | |
| 442 | + text: "I am thinking about the solution", | |
| 443 | + signature: undefined, | |
| 444 | + }, | |
| 445 | + }, | |
| 391 | 446 | }, |
| 392 | - }, | |
| 393 | - ], | |
| 394 | - } as UserChatMessage; | |
| 395 | - const converted = bedrock["_convertMessage"](message); | |
| 396 | - expect(converted).toEqual({ | |
| 397 | - role: "user", | |
| 398 | - content: [ | |
| 399 | - { text: "Look at this image:" }, | |
| 400 | - { | |
| 401 | - image: { | |
| 402 | - format: "jpeg", | |
| 403 | - source: { | |
| 404 | - bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), | |
| 447 | + { text: "Here's my answer" }, | |
| 448 | + ], | |
| 449 | + }, | |
| 450 | + ]); | |
| 451 | + }); | |
| 452 | + | |
| 453 | + it("should handle redacted thinking messages", () => { | |
| 454 | + const messages: ChatMessage[] = [ | |
| 455 | + { role: "user", content: "Think about this" } as UserChatMessage, | |
| 456 | + { | |
| 457 | + role: "thinking", | |
| 458 | + content: "", | |
| 459 | + redactedThinking: "redacted-content-bytes", | |
| 460 | + }, | |
| 461 | + { role: "assistant", content: "Here's my answer" }, | |
| 462 | + ]; | |
| 463 | + | |
| 464 | + const availableTools = new Set<string>(); | |
| 465 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 466 | + | |
| 467 | + expect(converted).toEqual([ | |
| 468 | + { role: "user", content: [{ text: "Think about this" }] }, | |
| 469 | + { | |
| 470 | + role: "assistant", | |
| 471 | + content: [ | |
| 472 | + { | |
| 473 | + reasoningContent: { | |
| 474 | + redactedContent: expect.any(Uint8Array), | |
| 405 | 475 | }, |
| 406 | 476 | }, |
| 407 | - }, | |
| 408 | - ], | |
| 477 | + { text: "Here's my answer" }, | |
| 478 | + ], | |
| 479 | + }, | |
| 480 | + ]); | |
| 481 | + | |
| 482 | + // Check that the Uint8Array contains the expected bytes | |
| 483 | + const redactedContent = | |
| 484 | + converted[1].content?.[0].reasoningContent?.redactedContent; | |
| 485 | + expect(redactedContent).toBeInstanceOf(Uint8Array); | |
| 486 | + expect(Buffer.from(redactedContent!).toString()).toBe( | |
| 487 | + "redacted-content-bytes", | |
| 488 | + ); | |
| 489 | + }); | |
| 490 | + | |
| 491 | + it("should convert multimodal content correctly", () => { | |
| 492 | + const messages: ChatMessage[] = [ | |
| 493 | + { | |
| 494 | + role: "user", | |
| 495 | + content: [ | |
| 496 | + { type: "text", text: "Look at this image:" }, | |
| 497 | + { | |
| 498 | + type: "imageUrl", | |
| 499 | + imageUrl: { | |
| 500 | + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", | |
| 501 | + }, | |
| 502 | + }, | |
| 503 | + ], | |
| 504 | + } as UserChatMessage, | |
| 505 | + ]; | |
| 506 | + | |
| 507 | + const availableTools = new Set<string>(); | |
| 508 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 509 | + | |
| 510 | + expect(converted).toEqual([ | |
| 511 | + { | |
| 512 | + role: "user", | |
| 513 | + content: [ | |
| 514 | + { text: "Look at this image:" }, | |
| 515 | + { | |
| 516 | + image: { | |
| 517 | + format: "jpeg", | |
| 518 | + source: { | |
| 519 | + bytes: expect.any(Uint8Array), | |
| 520 | + }, | |
| 521 | + }, | |
| 522 | + }, | |
| 523 | + ], | |
| 524 | + }, | |
| 525 | + ]); | |
| 526 | + | |
| 527 | + // Check that the image bytes were processed correctly | |
| 528 | + const imageBytes = converted[0].content?.[1].image?.source?.bytes; | |
| 529 | + expect(imageBytes).toBeInstanceOf(Uint8Array); | |
| 530 | + expect(Buffer.from(imageBytes!).toString("base64")).toBe( | |
| 531 | + "/9j/4AAQSkZJRg==", | |
| 532 | + ); | |
| 533 | + }); | |
| 534 | + | |
| 535 | + it("should add cache points for prompt caching when needed", () => { | |
| 536 | + // Create a test instance with caching behavior enabled | |
| 537 | + const bedrockWithCaching = new TestBedrock({ | |
| 538 | + apiKey: "test-key", | |
| 539 | + model: "anthropic.claude-3-sonnet-20240229-v1:0", | |
| 540 | + region: "us-east-1", | |
| 409 | 541 | }); |
| 542 | + | |
| 543 | + // Set caching behavior | |
| 544 | + bedrockWithCaching.cacheBehavior = { | |
| 545 | + cacheConversation: true, | |
| 546 | + cacheSystemMessage: true, | |
| 547 | + }; | |
| 548 | + | |
| 549 | + const messages: ChatMessage[] = [ | |
| 550 | + { role: "system", content: "You are a helpful assistant" }, | |
| 551 | + { role: "user", content: "First message" } as UserChatMessage, | |
| 552 | + { role: "assistant", content: "First response" }, | |
| 553 | + { role: "user", content: "Second message" } as UserChatMessage, | |
| 554 | + ]; | |
| 555 | + | |
| 556 | + const availableTools = new Set<string>(); | |
| 557 | + const converted = bedrockWithCaching["_convertMessages"]( | |
| 558 | + messages, | |
| 559 | + availableTools, | |
| 560 | + ); | |
| 561 | + | |
| 562 | + // The last two user messages should have cache points | |
| 563 | + // But we're not testing the system message here since it's handled separately | |
| 564 | + expect(converted.length).toBe(3); | |
| 565 | + expect(converted[0].role).toBe("user"); | |
| 566 | + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( | |
| 567 | + true, | |
| 568 | + ); | |
| 569 | + expect(converted[1].role).toBe("assistant"); | |
| 570 | + expect(converted[2].role).toBe("user"); | |
| 571 | + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( | |
| 572 | + true, | |
| 573 | + ); | |
| 574 | + | |
| 575 | + // Verify that text content includes a cache ID suffix | |
| 576 | + const userMessageText = converted[0].content?.[0].text; | |
| 577 | + expect(userMessageText).toMatch(/First message.+/); | |
| 410 | 578 | }); |
| 411 | 579 | }); |
| 412 | 580 | }); |
modified core/llm/llms/Bedrock.ts +236 −159
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | BedrockRuntimeClient, |
| 3 | 3 | ContentBlock, |
| 4 | + ConversationRole, | |
| 4 | 5 | ConverseStreamCommand, |
| 5 | 6 | ConverseStreamCommandOutput, |
| 7 | + ImageFormat, | |
| 6 | 8 | InvokeModelCommand, |
| 7 | 9 | Message, |
| 8 | 10 | ToolConfiguration, |
| @@ -14,6 +16,7 @@ | ||
| 14 | 16 | Chunk, |
| 15 | 17 | CompletionOptions, |
| 16 | 18 | LLMOptions, |
| 19 | + MessageContent, | |
| 17 | 20 | } from "../../index.js"; |
| 18 | 21 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 19 | 22 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| @@ -289,8 +292,8 @@ | ||
| 289 | 292 | const systemMessage = stripImages( |
| 290 | 293 | messages.find((m) => m.role === "system")?.content ?? "", |
| 291 | 294 | ); |
| 292 | - const convertedMessages = this._convertMessages(messages); | |
| 293 | 295 | |
| 296 | + // Prompt and system message caching settings | |
| 294 | 297 | const shouldCacheSystemMessage = |
| 295 | 298 | (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || |
| 296 | 299 | this.completionOptions.promptCaching; |
| @@ -298,9 +301,7 @@ | ||
| 298 | 301 | shouldCacheSystemMessage || |
| 299 | 302 | this.cacheBehavior?.cacheConversation || |
| 300 | 303 | this.completionOptions.promptCaching; |
| 301 | - const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 302 | 304 | |
| 303 | - // Add header for prompt caching | |
| 304 | 305 | if (enablePromptCaching) { |
| 305 | 306 | this.requestOptions.headers = { |
| 306 | 307 | ...this.requestOptions.headers, |
| @@ -308,30 +309,37 @@ | ||
| 308 | 309 | }; |
| 309 | 310 | } |
| 310 | 311 | |
| 312 | + // First get tools | |
| 311 | 313 | const supportsTools = |
| 312 | 314 | (this.capabilities?.tools || |
| 313 | 315 | PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? |
| 314 | 316 | false; |
| 315 | 317 | |
| 316 | - let toolConfig = | |
| 317 | - supportsTools && options.tools | |
| 318 | - ? ({ | |
| 319 | - tools: options.tools.map((tool) => ({ | |
| 320 | - toolSpec: { | |
| 321 | - name: tool.function.name, | |
| 322 | - description: tool.function.description, | |
| 323 | - inputSchema: { | |
| 324 | - json: tool.function.parameters, | |
| 325 | - }, | |
| 326 | - }, | |
| 327 | - })), | |
| 328 | - } as ToolConfiguration) | |
| 329 | - : undefined; | |
| 330 | - | |
| 331 | - if (toolConfig?.tools && shouldCacheToolsConfig) { | |
| 332 | - toolConfig.tools.push({ cachePoint: { type: "default" } }); | |
| 318 | + let toolConfig: undefined | ToolConfiguration = undefined; | |
| 319 | + const availableTools = new Set<string>(); | |
| 320 | + if (supportsTools && options.tools && options.tools.length > 0) { | |
| 321 | + toolConfig = { | |
| 322 | + tools: options.tools.map((tool) => ({ | |
| 323 | + toolSpec: { | |
| 324 | + name: tool.function.name, | |
| 325 | + description: tool.function.description, | |
| 326 | + inputSchema: { | |
| 327 | + json: tool.function.parameters, | |
| 328 | + }, | |
| 329 | + }, | |
| 330 | + })), | |
| 331 | + } as ToolConfiguration; | |
| 332 | + const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 333 | + if (shouldCacheToolsConfig) { | |
| 334 | + toolConfig.tools!.push({ cachePoint: { type: "default" } }); | |
| 335 | + } | |
| 336 | + options.tools.forEach((tool) => { | |
| 337 | + availableTools.add(tool.function.name); | |
| 338 | + }); | |
| 333 | 339 | } |
| 334 | 340 | |
| 341 | + const convertedMessages = this._convertMessages(messages, availableTools); | |
| 342 | + | |
| 335 | 343 | return { |
| 336 | 344 | modelId: options.model, |
| 337 | 345 | system: systemMessage |
| @@ -368,167 +376,236 @@ | ||
| 368 | 376 | }; |
| 369 | 377 | } |
| 370 | 378 | |
| 371 | - private _convertMessage( | |
| 372 | - message: ChatMessage, | |
| 373 | - addCaching: boolean = false, | |
| 374 | - ): Message | null { | |
| 375 | - // Handle system messages explicitly | |
| 376 | - if (message.role === "system") { | |
| 377 | - return null; | |
| 378 | - } | |
| 379 | + /* | |
| 380 | + Converts the messages to the format expected by the Bedrock API. | |
| 381 | + | |
| 382 | + */ | |
| 383 | + private _convertMessages( | |
| 384 | + messages: ChatMessage[], | |
| 385 | + availableTools: Set<string>, | |
| 386 | + ): Message[] { | |
| 387 | + let currentRole: "user" | "assistant" = "user"; | |
| 388 | + let currentBlocks: ContentBlock[] = []; | |
| 389 | + | |
| 390 | + const converted: Message[] = []; | |
| 391 | + const pushCurrentMessage = () => { | |
| 392 | + if (currentBlocks.length === 0 && converted.length > 1) { | |
| 393 | + throw new Error( | |
| 394 | + `Bedrock: no content in ${currentRole} message before conversational turn change`, | |
| 395 | + ); | |
| 396 | + } | |
| 397 | + if (currentBlocks.length > 0) { | |
| 398 | + converted.push({ | |
| 399 | + role: currentRole, | |
| 400 | + content: currentBlocks, | |
| 401 | + }); | |
| 402 | + } | |
| 403 | + currentBlocks = []; | |
| 404 | + }; | |
| 379 | 405 | |
| 380 | - const cachePoint = addCaching | |
| 381 | - ? { cachePoint: { type: "default" } } | |
| 382 | - : undefined; | |
| 383 | - | |
| 384 | - // Tool response handling | |
| 385 | - if (message.role === "tool") { | |
| 386 | - return { | |
| 387 | - role: "user", | |
| 388 | - content: [ | |
| 389 | - { | |
| 390 | - toolResult: { | |
| 391 | - toolUseId: message.toolCallId, | |
| 392 | - content: [ | |
| 393 | - { | |
| 394 | - text: message.content || "", | |
| 406 | + const nonSystemMessages = messages.filter((m) => m.role !== "system"); | |
| 407 | + const hasAddedToolCallIds = new Set<string>(); | |
| 408 | + | |
| 409 | + for (let idx = 0; idx < nonSystemMessages.length; idx++) { | |
| 410 | + const message = nonSystemMessages[idx]; | |
| 411 | + | |
| 412 | + if (message.role === "user" || message.role === "tool") { | |
| 413 | + // Detect conversational turn change | |
| 414 | + if (currentRole !== ConversationRole.USER) { | |
| 415 | + pushCurrentMessage(); | |
| 416 | + currentRole = ConversationRole.USER; | |
| 417 | + } | |
| 418 | + | |
| 419 | + // USER messages: | |
| 420 | + // Non-empty user message content is converted to "text" and "image" blocks | |
| 421 | + // If ANY user message part is cached, we add a single cache point block when we push the message | |
| 422 | + if (message.role === "user") { | |
| 423 | + const trimmedContent = | |
| 424 | + typeof message.content === "string" | |
| 425 | + ? message.content.trim() | |
| 426 | + : message.content; | |
| 427 | + if (trimmedContent) { | |
| 428 | + currentBlocks.push( | |
| 429 | + ...this._convertMessageContentToBlocks(trimmedContent), | |
| 430 | + ); | |
| 431 | + } | |
| 432 | + } | |
| 433 | + // TOOL messages: | |
| 434 | + // Tool messages are represented by "toolResult" blocks | |
| 435 | + // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig) | |
| 436 | + // If it doesn't, we convert it to a text block | |
| 437 | + else if (message.role === "tool") { | |
| 438 | + const trimmedContent = message.content.trim() || "No tool output"; | |
| 439 | + if (hasAddedToolCallIds.has(message.toolCallId)) { | |
| 440 | + currentBlocks.push({ | |
| 441 | + toolResult: { | |
| 442 | + toolUseId: message.toolCallId, | |
| 443 | + content: [ | |
| 444 | + { | |
| 445 | + text: trimmedContent, | |
| 446 | + }, | |
| 447 | + ], | |
| 448 | + }, | |
| 449 | + }); | |
| 450 | + } else { | |
| 451 | + currentBlocks.push({ | |
| 452 | + text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`, | |
| 453 | + }); | |
| 454 | + } | |
| 455 | + } | |
| 456 | + } else if (message.role === "assistant" || message.role === "thinking") { | |
| 457 | + // Detect conversational turn change | |
| 458 | + if (currentRole !== ConversationRole.ASSISTANT) { | |
| 459 | + pushCurrentMessage(); | |
| 460 | + currentRole = ConversationRole.ASSISTANT; | |
| 461 | + } | |
| 462 | + | |
| 463 | + // ASSISTANT messages: | |
| 464 | + // Non-empty assistant message content is converted to "text" and "image" blocks | |
| 465 | + if (message.role === "assistant") { | |
| 466 | + const trimmedContent = | |
| 467 | + typeof message.content === "string" | |
| 468 | + ? message.content.trim() | |
| 469 | + : message.content; | |
| 470 | + if (trimmedContent) { | |
| 471 | + currentBlocks.push( | |
| 472 | + ...this._convertMessageContentToBlocks(trimmedContent), | |
| 473 | + ); | |
| 474 | + } | |
| 475 | + // TOOL CALLS: | |
| 476 | + // Tool calls are represented by "toolUse" blocks | |
| 477 | + // Each tool call must have an id and a function name | |
| 478 | + // The function name must match one of the available tools | |
| 479 | + // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools) | |
| 480 | + if (message.toolCalls) { | |
| 481 | + for (const toolCall of message.toolCalls) { | |
| 482 | + if (toolCall.id && toolCall.function?.name) { | |
| 483 | + if (availableTools.has(toolCall.function.name)) { | |
| 484 | + currentBlocks.push({ | |
| 485 | + toolUse: { | |
| 486 | + toolUseId: toolCall.id, | |
| 487 | + name: toolCall.function.name, | |
| 488 | + input: safeParseToolCallArgs(toolCall), | |
| 489 | + }, | |
| 490 | + }); | |
| 491 | + hasAddedToolCallIds.add(toolCall.id); | |
| 492 | + } else { | |
| 493 | + const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; | |
| 494 | + currentBlocks.push({ | |
| 495 | + text: toolCallText, | |
| 496 | + }); | |
| 497 | + } | |
| 498 | + } else { | |
| 499 | + console.warn( | |
| 500 | + `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, | |
| 501 | + ); | |
| 502 | + continue; | |
| 503 | + } | |
| 504 | + } | |
| 505 | + } | |
| 506 | + } else if (message.role === "thinking") { | |
| 507 | + // THINKING: | |
| 508 | + // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content | |
| 509 | + if (message.redactedThinking) { | |
| 510 | + const block: ContentBlock.ReasoningContentMember = { | |
| 511 | + reasoningContent: { | |
| 512 | + redactedContent: new Uint8Array( | |
| 513 | + Buffer.from(message.redactedThinking), | |
| 514 | + ), | |
| 515 | + }, | |
| 516 | + }; | |
| 517 | + currentBlocks.push(block); | |
| 518 | + } else { | |
| 519 | + const block: ContentBlock.ReasoningContentMember = { | |
| 520 | + reasoningContent: { | |
| 521 | + reasoningText: { | |
| 522 | + text: (message.content as string) || "", | |
| 523 | + signature: message.signature, | |
| 395 | 524 | }, |
| 396 | - ], | |
| 397 | - }, | |
| 398 | - }, | |
| 399 | - ], | |
| 400 | - }; | |
| 525 | + }, | |
| 526 | + }; | |
| 527 | + currentBlocks.push(block); | |
| 528 | + } | |
| 529 | + } | |
| 530 | + } | |
| 401 | 531 | } |
| 402 | - | |
| 403 | - // Tool calls handling | |
| 404 | - if (message.role === "assistant" && message.toolCalls) { | |
| 405 | - return { | |
| 406 | - role: "assistant", | |
| 407 | - content: message.toolCalls.map((toolCall) => ({ | |
| 408 | - toolUse: { | |
| 409 | - toolUseId: toolCall.id, | |
| 410 | - name: toolCall.function?.name, | |
| 411 | - input: safeParseToolCallArgs(toolCall), | |
| 412 | - }, | |
| 413 | - })), | |
| 414 | - }; | |
| 532 | + if (currentBlocks.length > 0) { | |
| 533 | + pushCurrentMessage(); | |
| 415 | 534 | } |
| 416 | 535 | |
| 417 | - if (message.role === "thinking") { | |
| 418 | - if (message.redactedThinking) { | |
| 419 | - const content: ContentBlock.ReasoningContentMember = { | |
| 420 | - reasoningContent: { | |
| 421 | - redactedContent: new Uint8Array( | |
| 422 | - Buffer.from(message.redactedThinking), | |
| 423 | - ), | |
| 424 | - }, | |
| 425 | - }; | |
| 426 | - return { | |
| 427 | - role: "assistant", | |
| 428 | - content: [content], | |
| 429 | - }; | |
| 430 | - } else { | |
| 431 | - const content: ContentBlock.ReasoningContentMember = { | |
| 432 | - reasoningContent: { | |
| 433 | - reasoningText: { | |
| 434 | - text: (message.content as string) || "", | |
| 435 | - signature: message.signature, | |
| 436 | - }, | |
| 437 | - }, | |
| 438 | - }; | |
| 439 | - return { | |
| 440 | - role: "assistant", | |
| 441 | - content: [content], | |
| 442 | - }; | |
| 443 | - } | |
| 536 | + // If caching is enabled, we add cache_control parameter to the last two user messages | |
| 537 | + // The second-to-last because it retrieves potentially already cached contents, | |
| 538 | + // The last one because we want it cached for later retrieval. | |
| 539 | + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html | |
| 540 | + if (this.cacheBehavior?.cacheConversation) { | |
| 541 | + this._addCachingToLastTwoUserMessages(converted); | |
| 444 | 542 | } |
| 445 | 543 | |
| 446 | - // Standard text message | |
| 447 | - if (typeof message.content === "string") { | |
| 448 | - if (addCaching) { | |
| 449 | - message.content += getSecureID(); | |
| 544 | + return converted; | |
| 545 | + } | |
| 546 | + | |
| 547 | + private _addCachingToLastTwoUserMessages(converted: Message[]) { | |
| 548 | + let numCached = 0; | |
| 549 | + for (let i = converted.length - 1; i >= 0; i--) { | |
| 550 | + const message = converted[i]; | |
| 551 | + if (message.role === "user") { | |
| 552 | + message.content?.forEach((block) => { | |
| 553 | + if (block.text) { | |
| 554 | + block.text += getSecureID(); | |
| 555 | + } | |
| 556 | + }); | |
| 557 | + message.content?.push({ cachePoint: { type: "default" } }); | |
| 558 | + numCached++; | |
| 450 | 559 | } |
| 451 | - const content: any[] = [{ text: message.content }]; | |
| 452 | - if (addCaching) { | |
| 453 | - content.push({ cachePoint: { type: "default" } }); | |
| 560 | + if (numCached === 2) { | |
| 561 | + break; | |
| 454 | 562 | } |
| 455 | - return { | |
| 456 | - role: message.role, | |
| 457 | - content, | |
| 458 | - }; | |
| 459 | 563 | } |
| 564 | + } | |
| 460 | 565 | |
| 461 | - // Improved multimodal content handling | |
| 462 | - if (Array.isArray(message.content)) { | |
| 463 | - const content: any[] = []; | |
| 464 | - | |
| 465 | - // Process all parts first | |
| 466 | - message.content.forEach((part) => { | |
| 566 | + // Converts Continue message content (string/parts) to Bedrock ContentBlock format. | |
| 567 | + // Unsupported/problematic image formats are skipped with a warning. | |
| 568 | + private _convertMessageContentToBlocks( | |
| 569 | + content: MessageContent, | |
| 570 | + ): ContentBlock[] { | |
| 571 | + const blocks: ContentBlock[] = []; | |
| 572 | + if (typeof content === "string") { | |
| 573 | + blocks.push({ text: content }); | |
| 574 | + } else { | |
| 575 | + for (const part of content) { | |
| 467 | 576 | if (part.type === "text") { |
| 468 | - if (addCaching) { | |
| 469 | - part.text += getSecureID(); | |
| 470 | - } | |
| 471 | - content.push({ text: part.text }); | |
| 577 | + blocks.push({ text: part.text }); | |
| 472 | 578 | } else if (part.type === "imageUrl" && part.imageUrl) { |
| 473 | 579 | try { |
| 474 | 580 | const [mimeType, base64Data] = part.imageUrl.url.split(","); |
| 475 | 581 | const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; |
| 476 | - content.push({ | |
| 477 | - image: { | |
| 478 | - format, | |
| 479 | - source: { | |
| 480 | - bytes: Buffer.from(base64Data, "base64"), | |
| 582 | + if ( | |
| 583 | + format === ImageFormat.JPEG || | |
| 584 | + format === ImageFormat.PNG || | |
| 585 | + format === ImageFormat.WEBP || | |
| 586 | + format === ImageFormat.GIF | |
| 587 | + ) { | |
| 588 | + blocks.push({ | |
| 589 | + image: { | |
| 590 | + format, | |
| 591 | + source: { | |
| 592 | + bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), | |
| 593 | + }, | |
| 481 | 594 | }, |
| 482 | - }, | |
| 483 | - }); | |
| 595 | + }); | |
| 596 | + } else { | |
| 597 | + console.warn( | |
| 598 | + `Bedrock: skipping unsupported image part format: ${format}`, | |
| 599 | + part, | |
| 600 | + ); | |
| 601 | + } | |
| 484 | 602 | } catch (error) { |
| 485 | - console.warn(`Failed to process image: ${error}`); | |
| 603 | + console.warn("Bedrock: failed to process image part", error, part); | |
| 486 | 604 | } |
| 487 | 605 | } |
| 488 | - }); | |
| 489 | - | |
| 490 | - // Add cache point as a separate block at the end if needed | |
| 491 | - if (addCaching && content.length > 0) { | |
| 492 | - content.push({ cachePoint: { type: "default" } }); | |
| 493 | 606 | } |
| 494 | - | |
| 495 | - return { | |
| 496 | - role: message.role, | |
| 497 | - content, | |
| 498 | - } as Message; | |
| 499 | 607 | } |
| 500 | - return null; | |
| 501 | - } | |
| 502 | - | |
| 503 | - private _convertMessages(messages: ChatMessage[]): any[] { | |
| 504 | - const filteredmessages = messages.filter( | |
| 505 | - (m) => m.role !== "system" && !!m.content, | |
| 506 | - ); | |
| 507 | - const lastTwoUserMsgIndices = filteredmessages | |
| 508 | - .map((msg, index) => (msg.role === "user" ? index : -1)) | |
| 509 | - .filter((index) => index !== -1) | |
| 510 | - .slice(-2); | |
| 511 | - | |
| 512 | - const converted = filteredmessages | |
| 513 | - .map((message, filteredMsgIdx) => { | |
| 514 | - // Add cache_control parameter to the last two user messages | |
| 515 | - // The second-to-last because it retrieves potentially already cached contents, | |
| 516 | - // The last one because we want it cached for later retrieval. | |
| 517 | - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html | |
| 518 | - const addCaching = | |
| 519 | - this.cacheBehavior?.cacheConversation && | |
| 520 | - lastTwoUserMsgIndices.includes(filteredMsgIdx); | |
| 521 | - | |
| 522 | - try { | |
| 523 | - return this._convertMessage(message, addCaching); | |
| 524 | - } catch (error) { | |
| 525 | - console.error(`Failed to convert message: ${error}`); | |
| 526 | - return null; | |
| 527 | - } | |
| 528 | - }) | |
| 529 | - .filter(Boolean); | |
| 530 | - | |
| 531 | - return converted; | |
| 608 | + return blocks; | |
| 532 | 609 | } |
| 533 | 610 | |
| 534 | 611 | private async _getCredentials() { |
modified core/llm/llms/index.ts +1 −1
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | LLMOptions, |
| 9 | 9 | } from "../.."; |
| 10 | 10 | import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; |
| 11 | -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; | |
| 11 | +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; | |
| 12 | 12 | import { BaseLLM } from "../index"; |
| 13 | 13 | import Anthropic from "./Anthropic"; |
| 14 | 14 | import Asksage from "./Asksage"; |
modified core/llm/rules/getSystemMessageWithRules.ts +17 −8
| @@ -327,27 +327,36 @@ | ||
| 327 | 327 | export const getSystemMessageWithRules = ({ |
| 328 | 328 | baseSystemMessage, |
| 329 | 329 | userMessage, |
| 330 | - rules, | |
| 330 | + availableRules, | |
| 331 | 331 | contextItems, |
| 332 | 332 | rulePolicies = {}, |
| 333 | 333 | }: { |
| 334 | 334 | baseSystemMessage?: string; |
| 335 | 335 | userMessage: UserChatMessage | ToolResultChatMessage | undefined; |
| 336 | - rules: RuleWithSource[]; | |
| 336 | + availableRules: RuleWithSource[]; | |
| 337 | 337 | contextItems: ContextItemWithId[]; |
| 338 | 338 | rulePolicies?: RulePolicies; |
| 339 | -}) => { | |
| 340 | - const applicableRules = getApplicableRules( | |
| 339 | +}): { | |
| 340 | + systemMessage: string; | |
| 341 | + appliedRules: RuleWithSource[]; | |
| 342 | +} => { | |
| 343 | + const appliedRules = getApplicableRules( | |
| 341 | 344 | userMessage, |
| 342 | - rules, | |
| 345 | + availableRules, | |
| 343 | 346 | contextItems, |
| 344 | 347 | rulePolicies, |
| 345 | 348 | ); |
| 346 | 349 | let systemMessage = baseSystemMessage ?? ""; |
| 347 | 350 | |
| 348 | - for (const rule of applicableRules) { | |
| 349 | - systemMessage += `\n\n${rule.rule}`; | |
| 351 | + for (const rule of appliedRules) { | |
| 352 | + if (systemMessage) { | |
| 353 | + systemMessage += "\n\n"; | |
| 354 | + } | |
| 355 | + systemMessage += rule.rule; | |
| 350 | 356 | } |
| 351 | 357 | |
| 352 | - return systemMessage; | |
| 358 | + return { | |
| 359 | + systemMessage, | |
| 360 | + appliedRules, | |
| 361 | + }; | |
| 353 | 362 | }; |
modified core/llm/toolSupport.ts +3 −1
| @@ -179,7 +179,9 @@ | ||
| 179 | 179 | return false; |
| 180 | 180 | }, |
| 181 | 181 | deepseek: (model) => { |
| 182 | - if (model !== "deepseek-reasoner") { | |
| 182 | + // https://api-docs.deepseek.com/quick_start/pricing | |
| 183 | + // https://api-docs.deepseek.com/guides/function_calling | |
| 184 | + if (model === "deepseek-reasoner" || model === "deepseek-chat") { | |
| 183 | 185 | return true; |
| 184 | 186 | } |
| 185 | 187 |
modified core/tools/builtIn.ts +1 −0
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | CreateRuleBlock = "builtin_create_rule_block", |
| 14 | 14 | RequestRule = "builtin_request_rule", |
| 15 | 15 | FetchUrlContent = "builtin_fetch_url_content", |
| 16 | + CodebaseTool = "builtin_codebase", | |
| 16 | 17 | |
| 17 | 18 | // excluded from allTools for now |
| 18 | 19 | ViewRepoMap = "builtin_view_repo_map", |
modified core/tools/callTool.ts +26 −0
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; |
| 2 | 2 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 3 | +import { DataLogger } from "../data/log"; | |
| 3 | 4 | import { canParseUrl } from "../util/url"; |
| 4 | 5 | import { BuiltInToolNames } from "./builtIn"; |
| 5 | 6 | |
| 7 | +import { codebaseToolImpl } from "./implementations/codebaseTool"; | |
| 6 | 8 | import { createNewFileImpl } from "./implementations/createNewFile"; |
| 7 | 9 | import { createRuleBlockImpl } from "./implementations/createRuleBlock"; |
| 8 | 10 | import { fetchUrlContentImpl } from "./implementations/fetchUrlContent"; |
| @@ -164,11 +166,33 @@ | ||
| 164 | 166 | return await createRuleBlockImpl(args, extras); |
| 165 | 167 | case BuiltInToolNames.RequestRule: |
| 166 | 168 | return await requestRuleImpl(args, extras); |
| 169 | + case BuiltInToolNames.CodebaseTool: | |
| 170 | + return await codebaseToolImpl(args, extras); | |
| 167 | 171 | default: |
| 168 | 172 | throw new Error(`Tool "${functionName}" not found`); |
| 169 | 173 | } |
| 170 | 174 | } |
| 171 | 175 | |
| 176 | +function logToolUsage( | |
| 177 | + toolCall: ToolCall, | |
| 178 | + args: Record<string, any>, | |
| 179 | + contextItems: ContextItem[], | |
| 180 | + success: boolean, | |
| 181 | +) { | |
| 182 | + console.log(toolCall.function.arguments); | |
| 183 | + void DataLogger.getInstance().logDevData({ | |
| 184 | + name: "toolUsage", | |
| 185 | + data: { | |
| 186 | + toolCallId: toolCall.id, | |
| 187 | + functionName: toolCall.function.name, | |
| 188 | + functionArgs: toolCall.function.arguments, | |
| 189 | + toolCallArgs: args, | |
| 190 | + output: contextItems, | |
| 191 | + succeeded: success, | |
| 192 | + }, | |
| 193 | + }); | |
| 194 | +} | |
| 195 | + | |
| 172 | 196 | // Handles calls for core/non-client tools |
| 173 | 197 | // Returns an error context item if the tool call fails |
| 174 | 198 | // Note: Edit tool is handled on client |
| @@ -190,6 +214,7 @@ | ||
| 190 | 214 | item.icon = tool.faviconUrl; |
| 191 | 215 | }); |
| 192 | 216 | } |
| 217 | + logToolUsage(toolCall, args, contextItems, true); | |
| 193 | 218 | return { |
| 194 | 219 | contextItems, |
| 195 | 220 | errorMessage: undefined, |
| @@ -199,6 +224,7 @@ | ||
| 199 | 224 | if (e instanceof Error) { |
| 200 | 225 | errorMessage = e.message; |
| 201 | 226 | } |
| 227 | + logToolUsage(toolCall, {}, [], false); | |
| 202 | 228 | return { |
| 203 | 229 | contextItems: [], |
| 204 | 230 | 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 | +}; |
modified core/tools/definitions/editFile.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | -import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages"; | |
| 2 | +import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; | |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | 4 | |
| 5 | 5 | export interface EditToolArgs { |
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 @@ | ||
| 1 | 1 | import { ConfigDependentToolParams, IDE, Tool } from ".."; |
| 2 | +import { codebaseTool } from "./definitions/codebaseTool"; | |
| 2 | 3 | import { createNewFileTool } from "./definitions/createNewFile"; |
| 3 | 4 | import { createRuleBlock } from "./definitions/createRuleBlock"; |
| 4 | 5 | import { editFileTool } from "./definitions/editFile"; |
| @@ -37,7 +38,12 @@ | ||
| 37 | 38 | ): Tool[] => [ |
| 38 | 39 | requestRuleTool(params), |
| 39 | 40 | ...(params.enableExperimentalTools |
| 40 | - ? [searchAndReplaceInFileTool, viewRepoMapTool, viewSubdirectoryTool] | |
| 41 | + ? [ | |
| 42 | + searchAndReplaceInFileTool, | |
| 43 | + viewRepoMapTool, | |
| 44 | + viewSubdirectoryTool, | |
| 45 | + codebaseTool, | |
| 46 | + ] | |
| 41 | 47 | : [editFileTool]), |
| 42 | 48 | ]; |
| 43 | 49 |
modified core/util/findLast.ts +3 −3
| @@ -1,6 +1,6 @@ | ||
| 1 | -export function findLastIndex( | |
| 2 | - arr: any[], | |
| 3 | - criterion: (item: any) => boolean, | |
| 1 | +export function findLastIndex<T = any>( | |
| 2 | + arr: T[], | |
| 3 | + criterion: (item: T) => boolean, | |
| 4 | 4 | ): number { |
| 5 | 5 | let lastIndex = -1; |
| 6 | 6 |
modified extensions/intellij/build.gradle.kts +2 −5
| @@ -192,11 +192,8 @@ | ||
| 192 | 192 | } |
| 193 | 193 | |
| 194 | 194 | runIde { |
| 195 | - // Open the `manual-testing-sandbox` directory and the specific file on start | |
| 196 | - args = listOf( | |
| 197 | - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox", | |
| 198 | - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt" | |
| 199 | - ).map { file(it).absolutePath } | |
| 195 | + val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox" | |
| 196 | + args = listOf(dir, "$dir/test.kt") | |
| 200 | 197 | } |
| 201 | 198 | |
| 202 | 199 | test { |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +2 −2
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | import com.intellij.openapi.actionSystem.ActionPromoter |
| 6 | 6 | import com.intellij.openapi.actionSystem.AnAction |
| 7 | 7 | import com.intellij.openapi.actionSystem.DataContext |
| 8 | -import com.intellij.openapi.components.ServiceManager | |
| 8 | +import com.intellij.openapi.components.service | |
| 9 | 9 | import org.jetbrains.annotations.NotNull |
| 10 | 10 | |
| 11 | 11 | class ContinueActionPromote : ActionPromoter { |
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? { |
| 14 | 14 | // For autocomplete actions |
| 15 | 15 | if (actions.any { it is AcceptAutocompleteAction }) { |
| 16 | - val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) | |
| 16 | + val settings = service<ContinueExtensionSettings>() | |
| 17 | 17 | if (settings.continueState.showIDECompletionSideBySide) { |
| 18 | 18 | return actions.filterIsInstance<AcceptAutocompleteAction>() |
| 19 | 19 | } |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +3 −10
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.actions |
| 2 | 2 | |
| 3 | 3 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| 4 | -import com.intellij.openapi.components.ServiceManager | |
| 4 | +import com.intellij.openapi.components.service | |
| 5 | 5 | import com.intellij.openapi.project.Project |
| 6 | 6 | import com.intellij.openapi.wm.ToolWindowManager |
| 7 | 7 | |
| @@ -28,12 +28,5 @@ | ||
| 28 | 28 | continuePluginService.ideProtocolClient?.sendHighlightedCode() |
| 29 | 29 | } |
| 30 | 30 | |
| 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.activities |
| 2 | 2 | |
| 3 | 3 | import com.intellij.openapi.Disposable |
| 4 | -import com.intellij.openapi.application.ApplicationManager | |
| 5 | 4 | import com.intellij.openapi.components.Service |
| 6 | -import com.intellij.openapi.project.Project | |
| 7 | 5 | |
| 8 | 6 | /** |
| 9 | 7 | * The service is a parent disposable that represents the entire plugin lifecycle |
| @@ -18,15 +16,4 @@ | ||
| 18 | 16 | override fun dispose() { |
| 19 | 17 | } |
| 20 | 18 | |
| 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 | - } | |
| 32 | 19 | } |
| 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 @@ | ||
| 14 | 14 | import com.intellij.openapi.actionSystem.KeyboardShortcut |
| 15 | 15 | import com.intellij.openapi.application.ApplicationManager |
| 16 | 16 | import com.intellij.openapi.application.ApplicationNamesInfo |
| 17 | -import com.intellij.openapi.components.ServiceManager | |
| 18 | 17 | import com.intellij.openapi.editor.EditorFactory |
| 19 | 18 | import com.intellij.openapi.fileEditor.FileEditorManager |
| 20 | 19 | import com.intellij.openapi.keymap.KeymapManager |
| @@ -122,14 +121,10 @@ | ||
| 122 | 121 | |
| 123 | 122 | private fun initializePlugin(project: Project) { |
| 124 | 123 | val coroutineScope = CoroutineScope(Dispatchers.IO) |
| 125 | - val continuePluginService = ServiceManager.getService( | |
| 126 | - project, | |
| 127 | - ContinuePluginService::class.java | |
| 128 | - ) | |
| 124 | + val continuePluginService = project.service<ContinuePluginService>() | |
| 129 | 125 | |
| 130 | 126 | coroutineScope.launch { |
| 131 | - val settings = | |
| 132 | - ServiceManager.getService(ContinueExtensionSettings::class.java) | |
| 127 | + val settings = service<ContinueExtensionSettings>() | |
| 133 | 128 | if (!settings.continueState.shownWelcomeDialog) { |
| 134 | 129 | settings.continueState.shownWelcomeDialog = true |
| 135 | 130 | // Open tutorial file |
| @@ -270,7 +265,7 @@ | ||
| 270 | 265 | |
| 271 | 266 | EditorFactory.getInstance().eventMulticaster.addSelectionListener( |
| 272 | 267 | listener, |
| 273 | - ContinuePluginDisposable.getInstance(project) | |
| 268 | + project.service<ContinuePluginDisposable>() | |
| 274 | 269 | ) |
| 275 | 270 | |
| 276 | 271 | 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 @@ | ||
| 7 | 7 | import com.intellij.injected.editor.VirtualFileWindow |
| 8 | 8 | import com.intellij.openapi.application.* |
| 9 | 9 | import com.intellij.openapi.components.Service |
| 10 | -import com.intellij.openapi.components.ServiceManager | |
| 11 | 10 | import com.intellij.openapi.components.service |
| 12 | 11 | import com.intellij.openapi.editor.Editor |
| 13 | 12 | import com.intellij.openapi.editor.InlayProperties |
| @@ -64,8 +63,7 @@ | ||
| 64 | 63 | var lastChangeWasPartialAccept = false |
| 65 | 64 | |
| 66 | 65 | fun triggerCompletion(editor: Editor) { |
| 67 | - val settings = | |
| 68 | - ServiceManager.getService(ContinueExtensionSettings::class.java) | |
| 66 | + val settings = service<ContinueExtensionSettings>() | |
| 69 | 67 | if (!settings.continueState.enableTabAutocomplete) { |
| 70 | 68 | return |
| 71 | 69 | } |
| @@ -183,7 +181,7 @@ | ||
| 183 | 181 | } |
| 184 | 182 | if (isInjectedFile(editor)) return |
| 185 | 183 | // 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()) { | |
| 187 | 185 | return |
| 188 | 186 | } |
| 189 | 187 | |
| @@ -230,9 +228,10 @@ | ||
| 230 | 228 | } |
| 231 | 229 | } |
| 232 | 230 | |
| 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 | + } | |
| 236 | 235 | |
| 237 | 236 | private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> { |
| 238 | 237 | 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 @@ | ||
| 26 | 26 | private val animatedIcon = AnimatedIcon.Default() |
| 27 | 27 | |
| 28 | 28 | init { |
| 29 | - Disposer.register(ContinuePluginDisposable.getInstance(project), this) | |
| 29 | + Disposer.register(project.service<ContinuePluginDisposable>(), this) | |
| 30 | 30 | updateIcon() |
| 31 | 31 | } |
| 32 | 32 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +2 −1
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams |
| 11 | 11 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| 12 | 12 | import com.github.continuedev.continueintellijextension.utils.castNestedOrNull |
| 13 | +import com.intellij.openapi.components.service | |
| 13 | 14 | import com.intellij.openapi.editor.Editor |
| 14 | 15 | import com.intellij.openapi.project.Project |
| 15 | 16 | import kotlinx.coroutines.suspendCancellableCoroutine |
| @@ -201,7 +202,7 @@ | ||
| 201 | 202 | if (EditorUtils.editorFileExist(params.filepath)) EditorUtils.getOrOpenEditor(project, params.filepath) |
| 202 | 203 | else EditorUtils.getEditorByCreateFile(project, params.filepath) |
| 203 | 204 | |
| 204 | - val diffStreamService = project.getService(DiffStreamService::class.java) | |
| 205 | + val diffStreamService = project.service<DiffStreamService>() | |
| 205 | 206 | |
| 206 | 207 | val handler = ApplyToFileHandler( |
| 207 | 208 | 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 @@ | ||
| 9 | 9 | import com.intellij.diff.requests.SimpleDiffRequest |
| 10 | 10 | import com.intellij.openapi.application.ApplicationManager |
| 11 | 11 | import com.intellij.openapi.command.WriteCommandAction |
| 12 | -import com.intellij.openapi.components.ServiceManager | |
| 12 | +import com.intellij.openapi.components.service | |
| 13 | 13 | import com.intellij.openapi.fileEditor.FileDocumentManager |
| 14 | 14 | import com.intellij.openapi.project.DumbAware |
| 15 | 15 | import com.intellij.openapi.project.Project |
| @@ -18,7 +18,6 @@ | ||
| 18 | 18 | import com.intellij.openapi.vfs.LocalFileSystem |
| 19 | 19 | import java.awt.Toolkit |
| 20 | 20 | import java.io.File |
| 21 | -import java.net.URI | |
| 22 | 21 | import java.nio.file.Paths |
| 23 | 22 | import javax.swing.Action |
| 24 | 23 | import javax.swing.JComponent |
| @@ -89,11 +88,7 @@ | ||
| 89 | 88 | FileDocumentManager.getInstance().saveDocument(document) |
| 90 | 89 | |
| 91 | 90 | // 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) | |
| 97 | 92 | |
| 98 | 93 | // Clean up state |
| 99 | 94 | cleanUpFile(file) |
| @@ -102,10 +97,7 @@ | ||
| 102 | 97 | fun rejectDiff(file2: String?) { |
| 103 | 98 | val file = (file2 ?: lastFile2) ?: return |
| 104 | 99 | val diffInfo = diffInfoMap[file] ?: return |
| 105 | - val continuePluginService = ServiceManager.getService( | |
| 106 | - project, | |
| 107 | - ContinuePluginService::class.java | |
| 108 | - ) | |
| 100 | + val continuePluginService = project.service<ContinuePluginService>() | |
| 109 | 101 | continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex) |
| 110 | 102 | continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex) |
| 111 | 103 | 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 @@ | ||
| 6 | 6 | import com.github.continuedev.continueintellijextension.auth.ContinueAuthService |
| 7 | 7 | import com.github.continuedev.continueintellijextension.editor.DiffStreamService |
| 8 | 8 | import com.github.continuedev.continueintellijextension.editor.EditorUtils |
| 9 | +import com.github.continuedev.continueintellijextension.error.ContinueErrorService | |
| 9 | 10 | import com.github.continuedev.continueintellijextension.protocol.* |
| 10 | 11 | import com.github.continuedev.continueintellijextension.services.* |
| 11 | 12 | import com.github.continuedev.continueintellijextension.utils.* |
| @@ -46,7 +47,7 @@ | ||
| 46 | 47 | init { |
| 47 | 48 | // Setup config.json / config.ts save listeners |
| 48 | 49 | VirtualFileManager.getInstance().addAsyncFileListener( |
| 49 | - AsyncFileSaveListener(continuePluginService), ContinuePluginDisposable.getInstance(project) | |
| 50 | + AsyncFileSaveListener(continuePluginService), project.service<ContinuePluginDisposable>() | |
| 50 | 51 | ) |
| 51 | 52 | } |
| 52 | 53 | |
| @@ -67,8 +68,7 @@ | ||
| 67 | 68 | } |
| 68 | 69 | |
| 69 | 70 | "jetbrains/isOSREnabled" -> { |
| 70 | - val isOSREnabled = | |
| 71 | - ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR | |
| 71 | + val isOSREnabled = service<ContinueExtensionSettings>().continueState.enableOSR | |
| 72 | 72 | respond(isOSREnabled) |
| 73 | 73 | } |
| 74 | 74 | |
| @@ -463,8 +463,10 @@ | ||
| 463 | 463 | println("Unknown message type: $messageType") |
| 464 | 464 | } |
| 465 | 465 | } |
| 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) | |
| 468 | 470 | } |
| 469 | 471 | } |
| 470 | 472 | } |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +30 −31
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.`continue` |
| 2 | 2 | |
| 3 | 3 | import com.github.continuedev.continueintellijextension.* |
| 4 | -import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath | |
| 5 | 4 | 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 | |
| 7 | 7 | import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings |
| 8 | 8 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| 9 | 9 | import com.github.continuedev.continueintellijextension.utils.* |
| @@ -11,7 +11,6 @@ | ||
| 11 | 11 | import com.intellij.execution.configurations.GeneralCommandLine |
| 12 | 12 | import com.intellij.execution.util.ExecUtil |
| 13 | 13 | import com.intellij.ide.BrowserUtil |
| 14 | -import com.intellij.ide.plugins.PluginManager | |
| 15 | 14 | import com.intellij.ide.plugins.PluginManagerCore |
| 16 | 15 | import com.intellij.lang.annotation.HighlightSeverity |
| 17 | 16 | import com.intellij.notification.NotificationAction |
| @@ -19,6 +18,7 @@ | ||
| 19 | 18 | import com.intellij.notification.NotificationType |
| 20 | 19 | import com.intellij.openapi.application.ApplicationInfo |
| 21 | 20 | import com.intellij.openapi.application.ApplicationManager |
| 21 | +import com.intellij.openapi.application.EDT | |
| 22 | 22 | import com.intellij.openapi.components.service |
| 23 | 23 | import com.intellij.openapi.editor.impl.DocumentMarkupModel |
| 24 | 24 | import com.intellij.openapi.extensions.PluginId |
| @@ -38,9 +38,7 @@ | ||
| 38 | 38 | import java.io.File |
| 39 | 39 | import java.io.FileInputStream |
| 40 | 40 | import java.io.InputStreamReader |
| 41 | -import java.net.URI | |
| 42 | 41 | import java.nio.charset.Charset |
| 43 | -import java.nio.file.Paths | |
| 44 | 42 | |
| 45 | 43 | class IntelliJIDE( |
| 46 | 44 | private val project: Project, |
| @@ -297,23 +295,26 @@ | ||
| 297 | 295 | continuePluginService.diffManager?.showDiff(filepath, newContents, stepIndex) |
| 298 | 296 | } |
| 299 | 297 | |
| 300 | - override suspend fun getOpenFiles(): List<String> { | |
| 301 | - val fileEditorManager = FileEditorManager.getInstance(project) | |
| 302 | - return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList() | |
| 303 | - } | |
| 304 | - | |
| 305 | - override suspend fun getCurrentFile(): Map<String, Any>? { | |
| 306 | - val fileEditorManager = FileEditorManager.getInstance(project) | |
| 307 | - val editor = fileEditorManager.selectedTextEditor | |
| 308 | - val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } | |
| 309 | - return virtualFile?.toUriOrNull()?.let { | |
| 310 | - mapOf( | |
| 311 | - "path" to it, | |
| 312 | - "contents" to editor.document.text, | |
| 313 | - "isUntitled" to false | |
| 314 | - ) | |
| 298 | + override suspend fun getOpenFiles(): List<String> = | |
| 299 | + withContext(Dispatchers.EDT) { | |
| 300 | + FileEditorManager.getInstance(project).openFiles | |
| 301 | + .mapNotNull { it.toUriOrNull() } | |
| 302 | + .toList() | |
| 303 | + } | |
| 304 | + | |
| 305 | + override suspend fun getCurrentFile(): Map<String, Any>? = | |
| 306 | + withContext(Dispatchers.EDT) { | |
| 307 | + val fileEditorManager = FileEditorManager.getInstance(project) | |
| 308 | + val document = fileEditorManager.selectedTextEditor?.document | |
| 309 | + val virtualFile = document?.let { FileDocumentManager.getInstance().getFile(it) } | |
| 310 | + virtualFile?.toUriOrNull()?.let { | |
| 311 | + mapOf( | |
| 312 | + "path" to it, | |
| 313 | + "contents" to document.text, | |
| 314 | + "isUntitled" to false | |
| 315 | + ) | |
| 316 | + } | |
| 315 | 317 | } |
| 316 | - } | |
| 317 | 318 | |
| 318 | 319 | override suspend fun getPinnedFiles(): List<String> { |
| 319 | 320 | // Returning open files for now as per existing code |
| @@ -344,11 +345,10 @@ | ||
| 344 | 345 | command.setWorkDirectory(project.basePath) |
| 345 | 346 | val results = ExecUtil.execAndGetOutput(command).stdout |
| 346 | 347 | return results.split("\n") |
| 347 | - } catch (e: Exception) { | |
| 348 | - showToast( | |
| 349 | - ToastType.ERROR, | |
| 350 | - "Error executing ripgrep: ${e.message}" | |
| 351 | - ) | |
| 348 | + } catch (exception: Exception) { | |
| 349 | + val message = "Error executing ripgrep: ${exception.message}" | |
| 350 | + service<ContinueErrorService>().report(exception, message) | |
| 351 | + showToast(ToastType.ERROR, message) | |
| 352 | 352 | return emptyList() |
| 353 | 353 | } |
| 354 | 354 | } else { |
| @@ -386,11 +386,10 @@ | ||
| 386 | 386 | |
| 387 | 387 | command.setWorkDirectory(project.basePath) |
| 388 | 388 | return ExecUtil.execAndGetOutput(command).stdout |
| 389 | - } catch (e: Exception) { | |
| 390 | - showToast( | |
| 391 | - ToastType.ERROR, | |
| 392 | - "Error executing ripgrep: ${e.message}" | |
| 393 | - ) | |
| 389 | + } catch (exception: Exception) { | |
| 390 | + val message = "Error executing ripgrep: ${exception.message}" | |
| 391 | + service<ContinueErrorService>().report(exception, message) | |
| 392 | + showToast(ToastType.ERROR, message) | |
| 394 | 393 | return "Error: Unable to execute ripgrep command." |
| 395 | 394 | } |
| 396 | 395 | } else { |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +4 −5
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | import com.intellij.openapi.application.ApplicationManager |
| 8 | 8 | import com.intellij.openapi.command.WriteCommandAction |
| 9 | 9 | import com.intellij.openapi.command.undo.UndoManager |
| 10 | -import com.intellij.openapi.components.ServiceManager | |
| 10 | +import com.intellij.openapi.components.service | |
| 11 | 11 | import com.intellij.openapi.editor.Editor |
| 12 | 12 | import com.intellij.openapi.editor.markup.HighlighterLayer |
| 13 | 13 | import com.intellij.openapi.editor.markup.RangeHighlighter |
| @@ -42,7 +42,6 @@ | ||
| 42 | 42 | private var isRunning: Boolean = false |
| 43 | 43 | private var hasAcceptedOrRejectedBlock: Boolean = false |
| 44 | 44 | private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf() |
| 45 | - private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) | |
| 46 | 45 | private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) |
| 47 | 46 | |
| 48 | 47 | |
| @@ -62,10 +61,10 @@ | ||
| 62 | 61 | numDiffs = diffBlocks.size, |
| 63 | 62 | filepath = virtualFile?.url, |
| 64 | 63 | fileContent = "not implemented", |
| 65 | - toolCallId = toolCallId?.toString() | |
| 64 | + toolCallId = toolCallId | |
| 66 | 65 | ) |
| 67 | 66 | |
| 68 | - continuePluginService.sendToWebview("updateApplyState", payload) | |
| 67 | + project.service<ContinuePluginService>().sendToWebview("updateApplyState", payload) | |
| 69 | 68 | } |
| 70 | 69 | |
| 71 | 70 | fun acceptAll() { |
| @@ -102,7 +101,7 @@ | ||
| 102 | 101 | isRunning = true |
| 103 | 102 | sendUpdate(ApplyStateStatus.STREAMING) |
| 104 | 103 | |
| 105 | - continuePluginService.coreMessenger?.request( | |
| 104 | + project.service<ContinuePluginService>().coreMessenger?.request( | |
| 106 | 105 | "streamDiffLines", |
| 107 | 106 | StreamDiffLinesPayload( |
| 108 | 107 | 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.error |
| 2 | 2 | |
| 3 | 3 | import com.intellij.diagnostic.IdeaReportingEvent |
| 4 | -import com.intellij.openapi.application.ApplicationInfo | |
| 4 | +import com.intellij.openapi.components.service | |
| 5 | 5 | import com.intellij.openapi.diagnostic.ErrorReportSubmitter |
| 6 | 6 | import com.intellij.openapi.diagnostic.IdeaLoggingEvent |
| 7 | 7 | import com.intellij.openapi.diagnostic.SubmittedReportInfo |
| 8 | 8 | import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus |
| 9 | -import com.intellij.ui.jcef.JBCefApp | |
| 10 | 9 | import com.intellij.util.Consumer |
| 11 | -import io.sentry.Sentry | |
| 12 | -import io.sentry.SentryEvent | |
| 13 | -import io.sentry.protocol.Message | |
| 14 | 10 | import java.awt.Component |
| 15 | 11 | |
| 16 | 12 | class ContinueErrorSubmitter : ErrorReportSubmitter() { |
| 17 | 13 | |
| 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 | - | |
| 27 | 14 | override fun getReportActionText() = |
| 28 | 15 | "Report to Continue" |
| 29 | 16 | |
| @@ -34,12 +21,13 @@ | ||
| 34 | 21 | consumer: Consumer<in SubmittedReportInfo> |
| 35 | 22 | ): Boolean { |
| 36 | 23 | 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 | + ) | |
| 43 | 31 | } catch (_: Exception) { |
| 44 | 32 | consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED)) |
| 45 | 33 | return false |
| @@ -48,8 +36,4 @@ | ||
| 48 | 36 | return true |
| 49 | 37 | } |
| 50 | 38 | |
| 51 | - private companion object { | |
| 52 | - private const val SENTRY_DSN = "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" | |
| 53 | - } | |
| 54 | - | |
| 55 | 39 | } |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +1 −1
| @@ -111,7 +111,7 @@ | ||
| 111 | 111 | |
| 112 | 112 | companion object { |
| 113 | 113 | val instance: ContinueExtensionSettings |
| 114 | - get() = ServiceManager.getService(ContinueExtensionSettings::class.java) | |
| 114 | + get() = service<ContinueExtensionSettings>() | |
| 115 | 115 | } |
| 116 | 116 | |
| 117 | 117 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +14 −15
| @@ -9,30 +9,21 @@ | ||
| 9 | 9 | import com.google.gson.Gson |
| 10 | 10 | import com.google.gson.JsonObject |
| 11 | 11 | import com.google.gson.JsonParser |
| 12 | +import com.intellij.openapi.components.service | |
| 12 | 13 | import com.intellij.openapi.project.Project |
| 13 | 14 | import com.intellij.openapi.util.Disposer |
| 14 | 15 | import com.intellij.ui.jcef.* |
| 15 | 16 | import com.intellij.ui.jcef.JBCefClient.Properties |
| 16 | -import com.intellij.util.application | |
| 17 | 17 | import org.cef.CefApp |
| 18 | 18 | import org.cef.browser.CefBrowser |
| 19 | 19 | import org.cef.handler.CefLoadHandlerAdapter |
| 20 | 20 | |
| 21 | 21 | class ContinueBrowser(val project: Project, url: String) { |
| 22 | - private fun registerAppSchemeHandler() { | |
| 23 | - CefApp.getInstance().registerSchemeHandlerFactory( | |
| 24 | - "http", | |
| 25 | - "continue", | |
| 26 | - CustomSchemeHandlerFactory() | |
| 27 | - ) | |
| 28 | - } | |
| 29 | 22 | |
| 30 | 23 | val browser: JBCefBrowser |
| 31 | 24 | |
| 32 | - val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java) | |
| 33 | - | |
| 34 | 25 | init { |
| 35 | - val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR | |
| 26 | + val isOSREnabled = service<ContinueExtensionSettings>().continueState.enableOSR | |
| 36 | 27 | |
| 37 | 28 | this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { |
| 38 | 29 | // To avoid using System.setProperty to affect other plugins, |
| @@ -43,7 +34,7 @@ | ||
| 43 | 34 | } |
| 44 | 35 | |
| 45 | 36 | registerAppSchemeHandler() |
| 46 | - Disposer.register(ContinuePluginDisposable.getInstance(project), browser) | |
| 37 | + Disposer.register(project.service<ContinuePluginDisposable>(), browser) | |
| 47 | 38 | |
| 48 | 39 | // Listen for events sent from browser |
| 49 | 40 | val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!) |
| @@ -60,7 +51,7 @@ | ||
| 60 | 51 | } |
| 61 | 52 | |
| 62 | 53 | 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) | |
| 64 | 55 | return@addHandler null |
| 65 | 56 | } |
| 66 | 57 | |
| @@ -75,7 +66,7 @@ | ||
| 75 | 66 | } |
| 76 | 67 | |
| 77 | 68 | if (msg != null) { |
| 78 | - continuePluginService.ideProtocolClient?.handleMessage(msg, respondToWebview) | |
| 69 | + project.service<ContinuePluginService>().ideProtocolClient?.handleMessage(msg, respondToWebview) | |
| 79 | 70 | } |
| 80 | 71 | |
| 81 | 72 | null |
| @@ -99,7 +90,7 @@ | ||
| 99 | 90 | // Load the url only after the protocolClient is initialized, |
| 100 | 91 | // otherwise some messages will be lost, which are some configurations when the page is loaded. |
| 101 | 92 | // Moreover, we should add LoadHandler before loading the url. |
| 102 | - continuePluginService.onProtocolClientInitialized { | |
| 93 | + project.service<ContinuePluginService>().onProtocolClientInitialized { | |
| 103 | 94 | browser.loadURL(url) |
| 104 | 95 | } |
| 105 | 96 | |
| @@ -138,6 +129,14 @@ | ||
| 138 | 129 | } |
| 139 | 130 | } |
| 140 | 131 | |
| 132 | + private fun registerAppSchemeHandler() { | |
| 133 | + CefApp.getInstance().registerSchemeHandlerFactory( | |
| 134 | + "http", | |
| 135 | + "continue", | |
| 136 | + CustomSchemeHandlerFactory() | |
| 137 | + ) | |
| 138 | + } | |
| 139 | + | |
| 141 | 140 | private fun buildJavaScript(jsonData: String): String { |
| 142 | 141 | return """window.postMessage($jsonData, "*");""" |
| 143 | 142 | } |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +3 −5
| @@ -3,13 +3,13 @@ | ||
| 3 | 3 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| 4 | 4 | import com.intellij.openapi.actionSystem.ActionManager |
| 5 | 5 | import com.intellij.openapi.actionSystem.AnAction |
| 6 | -import com.intellij.openapi.components.ServiceManager | |
| 6 | +import com.intellij.openapi.components.service | |
| 7 | 7 | import com.intellij.openapi.project.DumbAware |
| 8 | 8 | import com.intellij.openapi.project.Project |
| 9 | 9 | import com.intellij.openapi.wm.ToolWindow |
| 10 | 10 | import com.intellij.openapi.wm.ToolWindowFactory |
| 11 | 11 | import com.intellij.ui.content.ContentFactory |
| 12 | -import javax.swing.* | |
| 12 | +import javax.swing.JComponent | |
| 13 | 13 | |
| 14 | 14 | const val JS_QUERY_POOL_SIZE = "200" |
| 15 | 15 | |
| @@ -52,9 +52,7 @@ | ||
| 52 | 52 | val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl |
| 53 | 53 | |
| 54 | 54 | 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 | |
| 58 | 56 | browser |
| 59 | 57 | } |
| 60 | 58 |
modified extensions/vscode/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/vscode/package.json +1 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.53", | |
| 5 | + "version": "1.1.54", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
modified gui/src/components/AcceptRejectDiffButtons.tsx +17 −1
| @@ -2,6 +2,9 @@ | ||
| 2 | 2 | import { ApplyState } from "core"; |
| 3 | 3 | import { useContext } from "react"; |
| 4 | 4 | import { IdeMessengerContext } from "../context/IdeMessenger"; |
| 5 | +import { useAppDispatch, useAppSelector } from "../redux/hooks"; | |
| 6 | +import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; | |
| 7 | +import { cancelToolCall } from "../redux/slices/sessionSlice"; | |
| 5 | 8 | import { getMetaKeyLabel } from "../util"; |
| 6 | 9 | import { ToolTip } from "./gui/Tooltip"; |
| 7 | 10 | |
| @@ -20,8 +23,21 @@ | ||
| 20 | 23 | (state) => state.status === "done", |
| 21 | 24 | ); |
| 22 | 25 | const ideMessenger = useContext(IdeMessengerContext); |
| 23 | - | |
| 26 | + const currentToolCallApplyState = useAppSelector( | |
| 27 | + selectCurrentToolCallApplyState, | |
| 28 | + ); | |
| 29 | + const dispatch = useAppDispatch(); | |
| 24 | 30 | async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { |
| 31 | + if ( | |
| 32 | + status === "rejectDiff" && | |
| 33 | + currentToolCallApplyState?.status === "done" | |
| 34 | + ) { | |
| 35 | + dispatch( | |
| 36 | + cancelToolCall({ | |
| 37 | + toolCallId: currentToolCallApplyState.toolCallId!, | |
| 38 | + }), | |
| 39 | + ); | |
| 40 | + } | |
| 25 | 41 | for (const { filepath = "", streamId } of pendingApplyStates) { |
| 26 | 42 | ideMessenger.post(status, { |
| 27 | 43 | filepath, |
modified gui/src/components/mainInput/InputToolbar.tsx +1 −13
| @@ -9,10 +9,6 @@ | ||
| 9 | 9 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 10 | 10 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| 11 | 11 | import { selectUseActiveFile } from "../../redux/selectors"; |
| 12 | -import { | |
| 13 | - selectCurrentToolCall, | |
| 14 | - selectCurrentToolCallApplyState, | |
| 15 | -} from "../../redux/selectors/selectCurrentToolCall"; | |
| 16 | 12 | import { selectSelectedChatModel } from "../../redux/slices/configSlice"; |
| 17 | 13 | import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice"; |
| 18 | 14 | import { exitEdit } from "../../redux/thunks/edit"; |
| @@ -53,20 +49,12 @@ | ||
| 53 | 49 | const useActiveFile = useAppSelector(selectUseActiveFile); |
| 54 | 50 | const isInEdit = useAppSelector((store) => store.session.isInEdit); |
| 55 | 51 | const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); |
| 56 | - const toolCallState = useAppSelector(selectCurrentToolCall); | |
| 57 | - const currentToolCallApplyState = useAppSelector( | |
| 58 | - selectCurrentToolCallApplyState, | |
| 59 | - ); | |
| 60 | 52 | const hasReasoningEnabled = useAppSelector( |
| 61 | 53 | (store) => store.session.hasReasoningEnabled, |
| 62 | 54 | ); |
| 63 | 55 | |
| 64 | 56 | const isEnterDisabled = |
| 65 | - props.disabled || | |
| 66 | - (isInEdit && codeToEdit.length === 0) || | |
| 67 | - toolCallState?.status === "generated" || | |
| 68 | - (currentToolCallApplyState && | |
| 69 | - currentToolCallApplyState.status !== "closed"); | |
| 57 | + props.disabled || (isInEdit && codeToEdit.length === 0); | |
| 70 | 58 | |
| 71 | 59 | const toolsSupported = defaultModel && modelSupportsTools(defaultModel); |
| 72 | 60 |
modified gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +6 −2
| @@ -2,8 +2,8 @@ | ||
| 2 | 2 | import { useSelector } from "react-redux"; |
| 3 | 3 | import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; |
| 4 | 4 | import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; |
| 5 | +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; | |
| 5 | 6 | import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; |
| 6 | -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; | |
| 7 | 7 | import { isJetBrains } from "../../../../util"; |
| 8 | 8 | import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; |
| 9 | 9 | import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; |
| @@ -50,7 +50,11 @@ | ||
| 50 | 50 | } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { |
| 51 | 51 | event.preventDefault(); |
| 52 | 52 | event.stopPropagation(); |
| 53 | - void dispatch(cancelCurrentToolCall()); | |
| 53 | + void dispatch( | |
| 54 | + cancelToolCall({ | |
| 55 | + toolCallId: toolCallState.toolCallId, | |
| 56 | + }), | |
| 57 | + ); | |
| 54 | 58 | } |
| 55 | 59 | }; |
| 56 | 60 |
modified gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +15 −3
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | import styled from "styled-components"; |
| 2 | -import { useAppDispatch } from "../../../../redux/hooks"; | |
| 2 | +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; | |
| 3 | +import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; | |
| 4 | +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; | |
| 3 | 5 | import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; |
| 4 | -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; | |
| 5 | 6 | import { |
| 6 | 7 | getAltKeyLabel, |
| 7 | 8 | getFontSize, |
| @@ -27,6 +28,7 @@ | ||
| 27 | 28 | export function PendingToolCallToolbar() { |
| 28 | 29 | const dispatch = useAppDispatch(); |
| 29 | 30 | const jetbrains = isJetBrains(); |
| 31 | + const currentToolCall = useAppSelector(selectCurrentToolCall); | |
| 30 | 32 | |
| 31 | 33 | return ( |
| 32 | 34 | <Container> |
| @@ -37,7 +39,17 @@ | ||
| 37 | 39 | <div className="flex gap-2 pb-0.5"> |
| 38 | 40 | <StopButton |
| 39 | 41 | className="text-description" |
| 40 | - onClick={() => dispatch(cancelCurrentToolCall())} | |
| 42 | + onClick={ | |
| 43 | + currentToolCall | |
| 44 | + ? () => { | |
| 45 | + dispatch( | |
| 46 | + cancelToolCall({ | |
| 47 | + toolCallId: currentToolCall.toolCallId, | |
| 48 | + }), | |
| 49 | + ); | |
| 50 | + } | |
| 51 | + : undefined | |
| 52 | + } | |
| 41 | 53 | data-testid="reject-tool-call-button" |
| 42 | 54 | > |
| 43 | 55 | {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} |
modified gui/src/components/mainInput/Lump/sections/RulesSection.tsx +1 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | DEFAULT_AGENT_SYSTEM_MESSAGE_URL, |
| 11 | 11 | DEFAULT_CHAT_SYSTEM_MESSAGE, |
| 12 | 12 | DEFAULT_CHAT_SYSTEM_MESSAGE_URL, |
| 13 | -} from "core/llm/constructMessages"; | |
| 13 | +} from "core/llm/defaultSystemMessages"; | |
| 14 | 14 | import { useContext, useMemo } from "react"; |
| 15 | 15 | import { useAuth } from "../../../../context/Auth"; |
| 16 | 16 | import { IdeMessengerContext } from "../../../../context/IdeMessenger"; |
modified gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +1 −0
| @@ -37,6 +37,7 @@ | ||
| 37 | 37 | contextRequests.push({ |
| 38 | 38 | provider: |
| 39 | 39 | attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!, |
| 40 | + query: attrs.query, | |
| 40 | 41 | }); |
| 41 | 42 | return child.attrs?.renderInlineAs ?? child.attrs?.label; |
| 42 | 43 |
modified gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +26 −31
| @@ -123,40 +123,35 @@ | ||
| 123 | 123 | return ( |
| 124 | 124 | <div |
| 125 | 125 | onClick={() => openContextItem(contextItem, ideMessenger)} |
| 126 | - className="group mr-2 flex cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10" | |
| 126 | + className="mr-2 flex cursor-pointer flex-row items-center gap-1.5 whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10" | |
| 127 | 127 | data-testid="context-items-peek-item" |
| 128 | 128 | > |
| 129 | - <div className="flex w-full items-center"> | |
| 130 | - {getContextItemIcon()} | |
| 131 | - <div className="flex min-w-0 flex-1 gap-2 text-xs"> | |
| 132 | - <div | |
| 133 | - className={`max-w-[50%] flex-shrink-0 truncate ${isUrl ? "hover:underline" : ""}`} | |
| 134 | - > | |
| 135 | - {contextItem.name} | |
| 136 | - </div> | |
| 137 | - <div | |
| 138 | - className={`min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`} | |
| 139 | - onClick={ | |
| 140 | - isUrl | |
| 141 | - ? (e) => { | |
| 142 | - if (contextItem.uri?.value) { | |
| 143 | - e.stopPropagation(); | |
| 144 | - ideMessenger.post("openUrl", contextItem.uri.value); | |
| 145 | - } else { | |
| 146 | - console.error("Couldn't open url", contextItem.uri); | |
| 147 | - } | |
| 148 | - } | |
| 149 | - : undefined | |
| 150 | - } | |
| 151 | - > | |
| 152 | - {contextItem.uri?.type === "file" | |
| 153 | - ? getUriPathBasename(contextItem.description) | |
| 154 | - : contextItem.description} | |
| 155 | - </div> | |
| 156 | - </div> | |
| 157 | - | |
| 129 | + {getContextItemIcon()} | |
| 130 | + <span className={`line-clamp-1 max-w-[130px] flex-shrink-0`}> | |
| 131 | + {contextItem.name} | |
| 132 | + </span> | |
| 133 | + <div | |
| 134 | + className={`group flex flex-row items-center gap-1.5 pr-1.5 text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`} | |
| 135 | + onClick={ | |
| 136 | + isUrl | |
| 137 | + ? (e) => { | |
| 138 | + if (contextItem.uri?.value) { | |
| 139 | + e.stopPropagation(); | |
| 140 | + ideMessenger.post("openUrl", contextItem.uri.value); | |
| 141 | + } else { | |
| 142 | + console.error("Couldn't open url", contextItem.uri); | |
| 143 | + } | |
| 144 | + } | |
| 145 | + : undefined | |
| 146 | + } | |
| 147 | + > | |
| 148 | + <span className={`line-clamp-1 flex-1 break-all`}> | |
| 149 | + {contextItem.uri?.type === "file" | |
| 150 | + ? getUriPathBasename(contextItem.description) | |
| 151 | + : contextItem.description} | |
| 152 | + </span> | |
| 158 | 153 | {isUrl && ( |
| 159 | - <ArrowTopRightOnSquareIcon className="mx-2 h-4 w-4 flex-shrink-0 text-gray-400 opacity-0 group-hover:opacity-100" /> | |
| 154 | + <ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" /> | |
| 160 | 155 | )} |
| 161 | 156 | </div> |
| 162 | 157 | </div> |
modified gui/src/hooks/ParallelListeners.tsx +5 −6
| @@ -268,7 +268,6 @@ | ||
| 268 | 268 | currentToolCallApplyState.streamId === state.streamId |
| 269 | 269 | ) { |
| 270 | 270 | if (state.status === "done" && autoAcceptEditToolDiffs) { |
| 271 | - console.log("AUTO ACCEPTED"); | |
| 272 | 271 | ideMessenger.post("acceptDiff", { |
| 273 | 272 | streamId: state.streamId, |
| 274 | 273 | filepath: state.filepath, |
| @@ -281,6 +280,11 @@ | ||
| 281 | 280 | toolCallId: currentToolCallApplyState.toolCallId!, |
| 282 | 281 | }), |
| 283 | 282 | ); |
| 283 | + void dispatch( | |
| 284 | + streamResponseAfterToolCall({ | |
| 285 | + toolCallId: currentToolCallApplyState.toolCallId!, | |
| 286 | + }), | |
| 287 | + ); | |
| 284 | 288 | } |
| 285 | 289 | // const output: ContextItem = { |
| 286 | 290 | // name: "Edit tool output", |
| @@ -288,11 +292,6 @@ | ||
| 288 | 292 | // description: "", |
| 289 | 293 | // }; |
| 290 | 294 | // dispatch(setToolCallOutput([])); |
| 291 | - void dispatch( | |
| 292 | - streamResponseAfterToolCall({ | |
| 293 | - toolCallId: currentToolCallApplyState.toolCallId!, | |
| 294 | - }), | |
| 295 | - ); | |
| 296 | 295 | } |
| 297 | 296 | } |
| 298 | 297 | } |
added gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +27 −0
| @@ -0,0 +1,27 @@ | ||
| 1 | +import { ContextItem, ContextItemWithId, ToolCallState } from "core"; | |
| 2 | + | |
| 3 | +export function toolCallStateToContextItems( | |
| 4 | + toolCallState: ToolCallState | undefined, | |
| 5 | +): ContextItemWithId[] { | |
| 6 | + if (!toolCallState) { | |
| 7 | + return []; | |
| 8 | + } | |
| 9 | + return ( | |
| 10 | + toolCallState.output?.map((ctxItem) => | |
| 11 | + toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId), | |
| 12 | + ) ?? [] | |
| 13 | + ); | |
| 14 | +} | |
| 15 | + | |
| 16 | +export function toolCallCtxItemToCtxItemWithId( | |
| 17 | + ctxItem: ContextItem, | |
| 18 | + toolCallId: string, | |
| 19 | +): ContextItemWithId { | |
| 20 | + return { | |
| 21 | + ...ctxItem, | |
| 22 | + id: { | |
| 23 | + providerTitle: "toolCall", | |
| 24 | + itemId: toolCallId, | |
| 25 | + }, | |
| 26 | + }; | |
| 27 | +} |
modified gui/src/redux/slices/sessionSlice.ts +49 −12
| @@ -20,13 +20,20 @@ | ||
| 20 | 20 | SessionMetadata, |
| 21 | 21 | } from "core"; |
| 22 | 22 | import { NEW_SESSION_TITLE } from "core/util/constants"; |
| 23 | -import { renderChatMessage } from "core/util/messageContent"; | |
| 23 | +import { | |
| 24 | + renderChatMessage, | |
| 25 | + renderContextItems, | |
| 26 | +} from "core/util/messageContent"; | |
| 24 | 27 | import { findUriInDirs, getUriPathBasename } from "core/util/uri"; |
| 28 | +import { findLastIndex } from "lodash"; | |
| 25 | 29 | import { v4 as uuidv4 } from "uuid"; |
| 30 | +import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; | |
| 26 | 31 | import { addToolCallDeltaToState } from "../../util/toolCallState"; |
| 27 | 32 | import { RootState } from "../store"; |
| 28 | 33 | import { streamResponseThunk } from "../thunks/streamResponse"; |
| 29 | -import { findCurrentToolCall, findToolCall } from "../util"; | |
| 34 | +import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; | |
| 35 | + | |
| 36 | +const getIdeMessenger = () => (window as any).ideMessenger; | |
| 30 | 37 | |
| 31 | 38 | // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. |
| 32 | 39 | // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. |
| @@ -105,19 +112,39 @@ | ||
| 105 | 112 | curMessage.isGatheringContext = payload; |
| 106 | 113 | } |
| 107 | 114 | }, |
| 108 | - clearLastEmptyResponse: (state) => { | |
| 115 | + clearDanglingMessages: (state) => { | |
| 116 | + // This is used during cancellation | |
| 117 | + // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing. | |
| 118 | + // The only thing allowed after the last assistant message that has either content or generated tool calls | |
| 119 | + // is a user or tool message | |
| 109 | 120 | if (state.history.length < 2) { |
| 110 | 121 | return; |
| 111 | 122 | } |
| 112 | - const lastMessage = state.history[state.history.length - 1]; | |
| 123 | + const lastUserOrToolIdx = findLastIndex( | |
| 124 | + state.history, | |
| 125 | + (item) => item.message.role === "tool" || item.message.role === "user", | |
| 126 | + ); | |
| 127 | + | |
| 128 | + let validAssistantMessageIdx = -1; | |
| 129 | + for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) { | |
| 130 | + const message = state.history[i]; | |
| 131 | + if ( | |
| 132 | + message.message.content || | |
| 133 | + message.toolCallState?.status !== "generating" | |
| 134 | + ) { | |
| 135 | + validAssistantMessageIdx = i; | |
| 136 | + // Cancel any tool calls that are dangling and generated | |
| 137 | + if (message.toolCallState?.status === "generated") { | |
| 138 | + message.toolCallState.status = "canceled"; | |
| 139 | + } | |
| 140 | + break; | |
| 141 | + } | |
| 142 | + } | |
| 113 | 143 | |
| 114 | - // Only clear in the case of an empty message | |
| 115 | - if (!lastMessage.message.content.length) { | |
| 116 | - state.mainEditorContentTrigger = | |
| 117 | - state.history[state.history.length - 2].editorState; | |
| 118 | - state.history = state.history.slice(0, -2); | |
| 119 | - // TODO is this logic correct for tool use conversations? | |
| 120 | - // Maybe slice at last index of "user" role message? | |
| 144 | + if (validAssistantMessageIdx === -1) { | |
| 145 | + state.history = state.history.slice(0, lastUserOrToolIdx + 1); | |
| 146 | + } else { | |
| 147 | + state.history = state.history.slice(0, validAssistantMessageIdx + 1); | |
| 121 | 148 | } |
| 122 | 149 | }, |
| 123 | 150 | // Trigger value picked up by editor with isMainInput to set its content |
| @@ -525,6 +552,7 @@ | ||
| 525 | 552 | contextItems: ContextItem[]; |
| 526 | 553 | }>, |
| 527 | 554 | ) => { |
| 555 | + // Update tool call state and corresponding tool output message | |
| 528 | 556 | const toolCallState = findToolCall( |
| 529 | 557 | state.history, |
| 530 | 558 | action.payload.toolCallId, |
| @@ -532,6 +560,15 @@ | ||
| 532 | 560 | if (toolCallState) { |
| 533 | 561 | toolCallState.output = action.payload.contextItems; |
| 534 | 562 | } |
| 563 | + const toolItem = findToolOutput(state.history, action.payload.toolCallId); | |
| 564 | + if (toolItem) { | |
| 565 | + toolItem.message.content = renderContextItems( | |
| 566 | + action.payload.contextItems, | |
| 567 | + ); | |
| 568 | + toolItem.contextItems = action.payload.contextItems.map((item) => | |
| 569 | + toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId), | |
| 570 | + ); | |
| 571 | + } | |
| 535 | 572 | }, |
| 536 | 573 | cancelToolCall: ( |
| 537 | 574 | state, |
| @@ -677,7 +714,7 @@ | ||
| 677 | 714 | setActive, |
| 678 | 715 | submitEditorAndInitAtIndex, |
| 679 | 716 | updateHistoryItemAtIndex, |
| 680 | - clearLastEmptyResponse, | |
| 717 | + clearDanglingMessages, | |
| 681 | 718 | setMainEditorContentTrigger, |
| 682 | 719 | deleteMessage, |
| 683 | 720 | setIsGatheringContext, |
modified gui/src/redux/thunks/callCurrentTool.ts +5 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | updateToolCallOutput, |
| 13 | 13 | } from "../slices/sessionSlice"; |
| 14 | 14 | import { ThunkApiType } from "../store"; |
| 15 | +import { logToolUsage } from "../util"; | |
| 15 | 16 | import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; |
| 16 | 17 | |
| 17 | 18 | export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>( |
| @@ -100,6 +101,8 @@ | ||
| 100 | 101 | ], |
| 101 | 102 | }), |
| 102 | 103 | ); |
| 104 | + | |
| 105 | + logToolUsage(toolCallState, false, extra.ideMessenger, output); | |
| 103 | 106 | } else if (output?.length) { |
| 104 | 107 | dispatch( |
| 105 | 108 | updateToolCallOutput({ |
| @@ -107,6 +110,8 @@ | ||
| 107 | 110 | contextItems: output, |
| 108 | 111 | }), |
| 109 | 112 | ); |
| 113 | + | |
| 114 | + logToolUsage(toolCallState, true, extra.ideMessenger, output); | |
| 110 | 115 | } |
| 111 | 116 | |
| 112 | 117 | // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` |
deleted gui/src/redux/thunks/cancelCurrentToolCall.ts +0 −50
| @@ -1,50 +0,0 @@ | ||
| 1 | -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; | |
| 2 | -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; | |
| 3 | -import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice"; | |
| 4 | -import { ThunkApiType } from "../store"; | |
| 5 | -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; | |
| 6 | - | |
| 7 | -export const cancelCurrentToolCall = createAsyncThunk< | |
| 8 | - void, | |
| 9 | - undefined, | |
| 10 | - ThunkApiType | |
| 11 | ->("chat/cancelTool", async (_, { dispatch, extra, getState }) => { | |
| 12 | - const state = getState(); | |
| 13 | - const toolCallState = selectCurrentToolCall(state); | |
| 14 | - | |
| 15 | - if (!toolCallState) { | |
| 16 | - return; | |
| 17 | - } | |
| 18 | - | |
| 19 | - if (toolCallState.status !== "generated") { | |
| 20 | - return; | |
| 21 | - } | |
| 22 | - | |
| 23 | - const { toolCallId } = toolCallState; | |
| 24 | - dispatch( | |
| 25 | - cancelToolCall({ | |
| 26 | - toolCallId, | |
| 27 | - }), | |
| 28 | - ); | |
| 29 | - | |
| 30 | - dispatch( | |
| 31 | - updateToolCallOutput({ | |
| 32 | - toolCallId, | |
| 33 | - contextItems: [ | |
| 34 | - { | |
| 35 | - name: "Tool Cancelled", | |
| 36 | - description: "Tool Cancelled", | |
| 37 | - content: | |
| 38 | - "The tool call was cancelled by the user. Please try something else or request further instructions.", | |
| 39 | - hidden: true, | |
| 40 | - }, | |
| 41 | - ], | |
| 42 | - }), | |
| 43 | - ); | |
| 44 | - const output = await dispatch( | |
| 45 | - streamResponseAfterToolCall({ | |
| 46 | - toolCallId, | |
| 47 | - }), | |
| 48 | - ); | |
| 49 | - unwrapResult(output); | |
| 50 | -}); |
modified gui/src/redux/thunks/cancelStream.ts +3 −5
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | 2 | import { |
| 3 | 3 | abortStream, |
| 4 | - clearLastEmptyResponse, | |
| 4 | + clearDanglingMessages, | |
| 5 | 5 | setInactive, |
| 6 | 6 | } from "../slices/sessionSlice"; |
| 7 | 7 | import { ThunkApiType } from "../store"; |
| @@ -12,9 +12,7 @@ | ||
| 12 | 12 | dispatch(setInactive()); |
| 13 | 13 | dispatch(abortStream()); |
| 14 | 14 | |
| 15 | - // In the case tool calls were being generated, | |
| 16 | - // Replace them with | |
| 17 | - // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box | |
| 18 | - dispatch(clearLastEmptyResponse()); | |
| 15 | + // Clear any dangling incomplete tool calls, thinking messages, etc. | |
| 16 | + dispatch(clearDanglingMessages()); | |
| 19 | 17 | }, |
| 20 | 18 | ); |
modified gui/src/redux/thunks/streamNormalInput.ts +41 −13
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | -import { ChatMessage, LLMFullCompletionOptions } from "core"; | |
| 2 | +import { LLMFullCompletionOptions } from "core"; | |
| 3 | 3 | import { modelSupportsTools } from "core/llm/autodetect"; |
| 4 | 4 | import { ToCoreProtocol } from "core/protocol"; |
| 5 | 5 | import { selectActiveTools } from "../selectors/selectActiveTools"; |
| @@ -9,38 +9,40 @@ | ||
| 9 | 9 | abortStream, |
| 10 | 10 | addPromptCompletionPair, |
| 11 | 11 | setActive, |
| 12 | + setAppliedRulesAtIndex, | |
| 12 | 13 | setInactive, |
| 13 | 14 | setToolGenerated, |
| 14 | 15 | streamUpdate, |
| 15 | 16 | } from "../slices/sessionSlice"; |
| 16 | 17 | import { ThunkApiType } from "../store"; |
| 18 | +import { | |
| 19 | + constructMessages, | |
| 20 | + getBaseSystemMessage, | |
| 21 | +} from "../util/constructMessages"; | |
| 17 | 22 | import { callCurrentTool } from "./callCurrentTool"; |
| 18 | 23 | |
| 19 | 24 | export const streamNormalInput = createAsyncThunk< |
| 20 | 25 | void, |
| 21 | 26 | { |
| 22 | - messages: ChatMessage[]; | |
| 23 | 27 | legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; |
| 24 | 28 | }, |
| 25 | 29 | ThunkApiType |
| 26 | 30 | >( |
| 27 | 31 | "chat/streamNormalInput", |
| 28 | - async ( | |
| 29 | - { messages, legacySlashCommandData }, | |
| 30 | - { dispatch, extra, getState }, | |
| 31 | - ) => { | |
| 32 | - // Gather state | |
| 32 | + async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { | |
| 33 | 33 | const state = getState(); |
| 34 | 34 | const selectedChatModel = selectSelectedChatModel(state); |
| 35 | 35 | |
| 36 | - const streamAborter = state.session.streamAborter; | |
| 37 | 36 | if (!selectedChatModel) { |
| 38 | - throw new Error("Default model not defined"); | |
| 37 | + throw new Error("No chat model selected"); | |
| 39 | 38 | } |
| 40 | 39 | |
| 41 | - let completionOptions: LLMFullCompletionOptions = {}; | |
| 40 | + // Get tools | |
| 42 | 41 | const activeTools = selectActiveTools(state); |
| 43 | 42 | const toolsSupported = modelSupportsTools(selectedChatModel); |
| 43 | + | |
| 44 | + // Construct completion options | |
| 45 | + let completionOptions: LLMFullCompletionOptions = {}; | |
| 44 | 46 | if (toolsSupported && activeTools.length > 0) { |
| 45 | 47 | completionOptions = { |
| 46 | 48 | tools: activeTools, |
| @@ -55,20 +57,46 @@ | ||
| 55 | 57 | }; |
| 56 | 58 | } |
| 57 | 59 | |
| 60 | + // Construct messages (excluding system message) | |
| 61 | + const baseSystemMessage = getBaseSystemMessage( | |
| 62 | + state.session.mode, | |
| 63 | + selectedChatModel, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + const withoutMessageIds = state.session.history.map((item) => { | |
| 67 | + const { id, ...messageWithoutId } = item.message; | |
| 68 | + return { ...item, message: messageWithoutId }; | |
| 69 | + }); | |
| 70 | + const { messages, appliedRules, appliedRuleIndex } = constructMessages( | |
| 71 | + withoutMessageIds, | |
| 72 | + baseSystemMessage, | |
| 73 | + state.config.config.rules, | |
| 74 | + state.ui.ruleSettings, | |
| 75 | + ); | |
| 76 | + | |
| 77 | + // TODO parallel tool calls will cause issues with this | |
| 78 | + // because there will be multiple tool messages, so which one should have applied rules? | |
| 79 | + dispatch( | |
| 80 | + setAppliedRulesAtIndex({ | |
| 81 | + index: appliedRuleIndex, | |
| 82 | + appliedRules: appliedRules, | |
| 83 | + }), | |
| 84 | + ); | |
| 85 | + | |
| 58 | 86 | dispatch(setActive()); |
| 59 | 87 | |
| 60 | - // Send request | |
| 88 | + // Send request and stream response | |
| 89 | + const streamAborter = state.session.streamAborter; | |
| 61 | 90 | const gen = extra.ideMessenger.llmStreamChat( |
| 62 | 91 | { |
| 63 | 92 | completionOptions, |
| 64 | 93 | title: selectedChatModel.title, |
| 65 | - messages, | |
| 94 | + messages: messages, | |
| 66 | 95 | legacySlashCommandData, |
| 67 | 96 | }, |
| 68 | 97 | streamAborter.signal, |
| 69 | 98 | ); |
| 70 | 99 | |
| 71 | - // Stream response | |
| 72 | 100 | let next = await gen.next(); |
| 73 | 101 | while (!next.done) { |
| 74 | 102 | if (!getState().session.isStreaming) { |
modified gui/src/redux/thunks/streamResponse.ts +2 −48
| @@ -1,15 +1,11 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | 2 | import { JSONContent } from "@tiptap/core"; |
| 3 | -import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; | |
| 4 | -import { constructMessages } from "core/llm/constructMessages"; | |
| 5 | -import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; | |
| 3 | +import { InputModifiers } from "core"; | |
| 6 | 4 | import posthog from "posthog-js"; |
| 7 | 5 | import { v4 as uuidv4 } from "uuid"; |
| 8 | 6 | import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; |
| 9 | -import { getBaseSystemMessage } from "../../util"; | |
| 10 | 7 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 11 | 8 | import { |
| 12 | - setAppliedRulesAtIndex, | |
| 13 | 9 | submitEditorAndInitAtIndex, |
| 14 | 10 | updateHistoryItemAtIndex, |
| 15 | 11 | } from "../slices/sessionSlice"; |
| @@ -77,7 +73,7 @@ | ||
| 77 | 73 | .map((item) => item.uri!.value), |
| 78 | 74 | ...selectedCode.map((rif) => rif.filepath), |
| 79 | 75 | ]; |
| 80 | - dispatch(updateFileSymbolsFromFiles(filesForSymbols)); | |
| 76 | + void dispatch(updateFileSymbolsFromFiles(filesForSymbols)); | |
| 81 | 77 | |
| 82 | 78 | dispatch( |
| 83 | 79 | updateHistoryItemAtIndex({ |
| @@ -93,47 +89,6 @@ | ||
| 93 | 89 | }), |
| 94 | 90 | ); |
| 95 | 91 | |
| 96 | - // Get updated history after the update | |
| 97 | - const updatedHistory = getState().session.history; | |
| 98 | - | |
| 99 | - // Determine which rules apply to this message | |
| 100 | - const userMsg = updatedHistory[inputIndex].message; | |
| 101 | - const rules = getState().config.config.rules; | |
| 102 | - const rulePolicies = getState().ui.ruleSettings; | |
| 103 | - | |
| 104 | - // Calculate applicable rules once | |
| 105 | - // We need to check the message type to match what getApplicableRules expects | |
| 106 | - const applicableRules = getApplicableRules( | |
| 107 | - userMsg.role === "user" || userMsg.role === "tool" | |
| 108 | - ? (userMsg as UserChatMessage | ToolResultChatMessage) | |
| 109 | - : undefined, | |
| 110 | - rules, | |
| 111 | - selectedContextItems, | |
| 112 | - rulePolicies, | |
| 113 | - ); | |
| 114 | - | |
| 115 | - // Store in history for UI display | |
| 116 | - dispatch( | |
| 117 | - setAppliedRulesAtIndex({ | |
| 118 | - index: inputIndex, | |
| 119 | - appliedRules: applicableRules, | |
| 120 | - }), | |
| 121 | - ); | |
| 122 | - | |
| 123 | - const messageMode = getState().session.mode; | |
| 124 | - const baseChatOrAgentSystemMessage = getBaseSystemMessage( | |
| 125 | - selectedChatModel, | |
| 126 | - messageMode, | |
| 127 | - ); | |
| 128 | - | |
| 129 | - const messages = constructMessages( | |
| 130 | - messageMode, | |
| 131 | - [...updatedHistory], | |
| 132 | - baseChatOrAgentSystemMessage, | |
| 133 | - applicableRules, | |
| 134 | - rulePolicies, | |
| 135 | - ); | |
| 136 | - | |
| 137 | 92 | posthog.capture("step run", { |
| 138 | 93 | step_name: "User Input", |
| 139 | 94 | params: {}, |
| @@ -150,7 +105,6 @@ | ||
| 150 | 105 | unwrapResult( |
| 151 | 106 | await dispatch( |
| 152 | 107 | streamNormalInput({ |
| 153 | - messages, | |
| 154 | 108 | legacySlashCommandData: legacyCommandWithInput |
| 155 | 109 | ? { |
| 156 | 110 | command: legacyCommandWithInput.command, |
modified gui/src/redux/thunks/streamResponseAfterToolCall.ts +3 −39
| @@ -1,10 +1,7 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | 2 | import { ChatMessage } from "core"; |
| 3 | -import { constructMessages } from "core/llm/constructMessages"; | |
| 4 | 3 | import { renderContextItems } from "core/util/messageContent"; |
| 5 | -import { getBaseSystemMessage } from "../../util"; | |
| 6 | -import { selectSelectedChatModel } from "../slices/configSlice"; | |
| 7 | -import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; | |
| 4 | +import { streamUpdate } from "../slices/sessionSlice"; | |
| 8 | 5 | import { ThunkApiType } from "../store"; |
| 9 | 6 | import { findToolCall } from "../util"; |
| 10 | 7 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| @@ -21,15 +18,8 @@ | ||
| 21 | 18 | await dispatch( |
| 22 | 19 | streamThunkWrapper(async () => { |
| 23 | 20 | const state = getState(); |
| 24 | - const initialHistory = state.session.history; | |
| 25 | - const selectedChatModel = selectSelectedChatModel(state); | |
| 26 | - | |
| 27 | - if (!selectedChatModel) { | |
| 28 | - throw new Error("No model selected"); | |
| 29 | - } | |
| 30 | 21 | |
| 31 | 22 | const toolCallState = findToolCall(state.session.history, toolCallId); |
| 32 | - | |
| 33 | 23 | if (!toolCallState) { |
| 34 | 24 | return; // in cases where edit tool is cancelled mid apply, this will be triggered |
| 35 | 25 | } |
| @@ -40,41 +30,15 @@ | ||
| 40 | 30 | |
| 41 | 31 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 42 | 32 | |
| 33 | + // TODO parallel tool calls - dispatch one tool message per tool call | |
| 43 | 34 | const newMessage: ChatMessage = { |
| 44 | 35 | role: "tool", |
| 45 | 36 | content: renderContextItems(toolOutput), |
| 46 | 37 | toolCallId, |
| 47 | 38 | }; |
| 48 | 39 | dispatch(streamUpdate([newMessage])); |
| 49 | - dispatch( | |
| 50 | - addContextItemsAtIndex({ | |
| 51 | - index: initialHistory.length, | |
| 52 | - contextItems: toolOutput.map((contextItem) => ({ | |
| 53 | - ...contextItem, | |
| 54 | - id: { | |
| 55 | - providerTitle: "toolCall", | |
| 56 | - itemId: toolCallId, | |
| 57 | - }, | |
| 58 | - })), | |
| 59 | - }), | |
| 60 | - ); | |
| 61 | - | |
| 62 | - const updatedHistory = getState().session.history; | |
| 63 | - const messageMode = getState().session.mode; | |
| 64 | - | |
| 65 | - const baseChatOrAgentSystemMessage = getBaseSystemMessage( | |
| 66 | - selectedChatModel, | |
| 67 | - messageMode, | |
| 68 | - ); | |
| 69 | - | |
| 70 | - const messages = constructMessages( | |
| 71 | - messageMode, | |
| 72 | - [...updatedHistory], | |
| 73 | - baseChatOrAgentSystemMessage, | |
| 74 | - state.config.config.rules, | |
| 75 | - ); | |
| 76 | 40 | |
| 77 | - unwrapResult(await dispatch(streamNormalInput({ messages }))); | |
| 41 | + unwrapResult(await dispatch(streamNormalInput({}))); | |
| 78 | 42 | }), |
| 79 | 43 | ); |
| 80 | 44 | }, |
modified gui/src/redux/thunks/streamThunkWrapper.tsx +1 −1
| @@ -22,7 +22,7 @@ | ||
| 22 | 22 | ); |
| 23 | 23 | } |
| 24 | 24 | } catch (e) { |
| 25 | - dispatch(cancelStream()); | |
| 25 | + await dispatch(cancelStream()); | |
| 26 | 26 | dispatch(setDialogMessage(<StreamErrorDialog error={e} />)); |
| 27 | 27 | dispatch(setShowDialog(true)); |
| 28 | 28 | } |
added gui/src/redux/util/constructMessages.test.ts +734 −0
| @@ -0,0 +1,734 @@ | ||
| 1 | +import { | |
| 2 | + AssistantChatMessage, | |
| 3 | + ChatHistoryItem, | |
| 4 | + ChatMessage, | |
| 5 | + ContextItemWithId, | |
| 6 | + ModelDescription, | |
| 7 | + RuleWithSource, | |
| 8 | + ThinkingChatMessage, | |
| 9 | + ToolResultChatMessage, | |
| 10 | + UserChatMessage, | |
| 11 | +} from "core"; | |
| 12 | +import { | |
| 13 | + DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 14 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 15 | +} from "core/llm/defaultSystemMessages"; | |
| 16 | +import { renderChatMessage } from "core/util/messageContent"; | |
| 17 | +import { beforeEach, describe, expect, test, vi } from "vitest"; | |
| 18 | +import { | |
| 19 | + CANCELLED_TOOL_CALL_MESSAGE, | |
| 20 | + constructMessages, | |
| 21 | + getBaseSystemMessage, | |
| 22 | + NO_TOOL_CALL_OUTPUT_MESSAGE, | |
| 23 | +} from "./constructMessages"; | |
| 24 | + | |
| 25 | +// For these tests we will mock the rules to simulate different scenarios | |
| 26 | +const CONTEXT_RULE: RuleWithSource = { | |
| 27 | + source: "rules-block", | |
| 28 | + rule: "CONTEXT_RULE", | |
| 29 | + description: "CONTEXT_TRIGGER", | |
| 30 | +}; | |
| 31 | +const LAST_MESSAGE_RULE: RuleWithSource = { | |
| 32 | + source: "rules-block", | |
| 33 | + rule: "LAST_MESSAGE_RULE", | |
| 34 | + description: "LAST_MESSAGE_TRIGGER", | |
| 35 | +}; | |
| 36 | +const NORMAL_RULE: RuleWithSource = { | |
| 37 | + source: "rules-block", | |
| 38 | + rule: "Always apply rule", | |
| 39 | +}; | |
| 40 | + | |
| 41 | +vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => { | |
| 42 | + const original = (await importOriginal()) as any; | |
| 43 | + return { | |
| 44 | + ...original, | |
| 45 | + getSystemMessageWithRules: ({ | |
| 46 | + baseSystemMessage, | |
| 47 | + availableRules, | |
| 48 | + userMessage, | |
| 49 | + contextItems, | |
| 50 | + rulePolicies, | |
| 51 | + }: { | |
| 52 | + baseSystemMessage: string; | |
| 53 | + availableRules: RuleWithSource[]; | |
| 54 | + userMessage?: UserChatMessage | ToolResultChatMessage; | |
| 55 | + contextItems: ContextItemWithId[]; | |
| 56 | + rulePolicies?: Record<string, any>; | |
| 57 | + }) => { | |
| 58 | + // Filter rules based on our mock logic | |
| 59 | + const appliedRules = availableRules.filter((rule) => { | |
| 60 | + if (rule.rule === LAST_MESSAGE_RULE.rule) { | |
| 61 | + if (userMessage) { | |
| 62 | + return renderChatMessage(userMessage).includes( | |
| 63 | + LAST_MESSAGE_RULE.description!, | |
| 64 | + ); | |
| 65 | + } else { | |
| 66 | + return false; | |
| 67 | + } | |
| 68 | + } | |
| 69 | + if (rule.rule === CONTEXT_RULE.rule) { | |
| 70 | + return contextItems.some((item) => | |
| 71 | + item.content.includes(CONTEXT_RULE.description!), | |
| 72 | + ); | |
| 73 | + } | |
| 74 | + return true; | |
| 75 | + }); | |
| 76 | + | |
| 77 | + // Build the system message with applied rules | |
| 78 | + let systemMessage = baseSystemMessage || ""; | |
| 79 | + if (appliedRules.length > 0) { | |
| 80 | + systemMessage += "\n\nRules to follow:\n"; | |
| 81 | + for (const rule of appliedRules) { | |
| 82 | + systemMessage += `- ${rule.rule}\n`; | |
| 83 | + } | |
| 84 | + } | |
| 85 | + | |
| 86 | + return { systemMessage, appliedRules }; | |
| 87 | + }, | |
| 88 | + }; | |
| 89 | +}); | |
| 90 | + | |
| 91 | +test("getBaseSystemMessage should return the correct system message based on mode", () => { | |
| 92 | + const mockModel = { | |
| 93 | + baseAgentSystemMessage: "Custom Agent System Message", | |
| 94 | + baseChatSystemMessage: "Custom Chat System Message", | |
| 95 | + } as ModelDescription; | |
| 96 | + | |
| 97 | + // Test agent mode with custom message | |
| 98 | + expect(getBaseSystemMessage("agent", mockModel)).toBe( | |
| 99 | + "Custom Agent System Message", | |
| 100 | + ); | |
| 101 | + | |
| 102 | + // Test chat mode with custom message | |
| 103 | + expect(getBaseSystemMessage("chat", mockModel)).toBe( | |
| 104 | + "Custom Chat System Message", | |
| 105 | + ); | |
| 106 | + | |
| 107 | + // Test agent mode with default message | |
| 108 | + expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe( | |
| 109 | + DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 110 | + ); | |
| 111 | + | |
| 112 | + // Test chat mode with default message | |
| 113 | + expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe( | |
| 114 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 115 | + ); | |
| 116 | +}); | |
| 117 | + | |
| 118 | +describe("constructMessages", () => { | |
| 119 | + // Setup mock data | |
| 120 | + let mockHistory: ChatHistoryItem[]; | |
| 121 | + const mockRules: RuleWithSource[] = [ | |
| 122 | + CONTEXT_RULE, | |
| 123 | + LAST_MESSAGE_RULE, | |
| 124 | + NORMAL_RULE, | |
| 125 | + ]; | |
| 126 | + | |
| 127 | + const createContextItem = ( | |
| 128 | + id: string, | |
| 129 | + content: string, | |
| 130 | + ): ContextItemWithId => ({ | |
| 131 | + id: { | |
| 132 | + providerTitle: "test-provider", | |
| 133 | + itemId: id, | |
| 134 | + }, | |
| 135 | + content, | |
| 136 | + name: `Context Item ${id}`, | |
| 137 | + description: `Description for ${id}`, | |
| 138 | + }); | |
| 139 | + | |
| 140 | + beforeEach(() => { | |
| 141 | + // Reset mock history before each test | |
| 142 | + mockHistory = []; | |
| 143 | + }); | |
| 144 | + | |
| 145 | + test("should ignore empty, tool, and system messages that go in", () => { | |
| 146 | + // Setup history with various message types including ones to be ignored | |
| 147 | + mockHistory = [ | |
| 148 | + { | |
| 149 | + message: { | |
| 150 | + role: "system", | |
| 151 | + content: "I should be ignored", | |
| 152 | + } as ChatMessage, | |
| 153 | + contextItems: [], | |
| 154 | + }, | |
| 155 | + { | |
| 156 | + message: { | |
| 157 | + role: "tool", | |
| 158 | + content: "I should be ignored", | |
| 159 | + toolCallId: "123", | |
| 160 | + } as ToolResultChatMessage, | |
| 161 | + contextItems: [], | |
| 162 | + }, | |
| 163 | + { | |
| 164 | + message: { role: "user", content: "" } as ChatMessage, // Empty message | |
| 165 | + contextItems: [], | |
| 166 | + }, | |
| 167 | + { | |
| 168 | + message: { role: "user", content: "Valid user message" } as ChatMessage, | |
| 169 | + contextItems: [], | |
| 170 | + }, | |
| 171 | + ]; | |
| 172 | + | |
| 173 | + const { messages } = constructMessages( | |
| 174 | + mockHistory, | |
| 175 | + "Base System Message", | |
| 176 | + mockRules, | |
| 177 | + {}, | |
| 178 | + ); | |
| 179 | + | |
| 180 | + // Should only contain a system message (added by the function) and the valid user message | |
| 181 | + expect(messages.length).toBe(2); | |
| 182 | + expect(messages[0].role).toBe("system"); | |
| 183 | + expect(messages[1].role).toBe("user"); | |
| 184 | + expect(messages[1].content).toEqual([ | |
| 185 | + { type: "text", text: "Valid user message" }, | |
| 186 | + ]); | |
| 187 | + expect(messages.some((msg) => msg.content === "I should be ignored")).toBe( | |
| 188 | + false, | |
| 189 | + ); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + test("should convert user messages to message parts arrays with context items", () => { | |
| 193 | + const contextItems = [ | |
| 194 | + createContextItem("1", "Context content 1"), | |
| 195 | + createContextItem("2", "Context content 2"), | |
| 196 | + ]; | |
| 197 | + | |
| 198 | + mockHistory = [ | |
| 199 | + { | |
| 200 | + message: { | |
| 201 | + role: "user", | |
| 202 | + content: "User message with context", | |
| 203 | + } as ChatMessage, | |
| 204 | + contextItems, | |
| 205 | + }, | |
| 206 | + ]; | |
| 207 | + | |
| 208 | + const { messages } = constructMessages( | |
| 209 | + mockHistory, | |
| 210 | + "Base System Message", | |
| 211 | + mockRules, | |
| 212 | + {}, | |
| 213 | + ); | |
| 214 | + | |
| 215 | + // Check that user message was converted to parts array with context items first | |
| 216 | + expect(messages.length).toBe(2); // System message + user message | |
| 217 | + expect(messages[1].role).toBe("user"); | |
| 218 | + | |
| 219 | + // Check content structure | |
| 220 | + const content = messages[1].content as any[]; | |
| 221 | + expect(content.length).toBe(3); // 2 context items + original message | |
| 222 | + expect(content[0].text).toContain("Context content 1"); | |
| 223 | + expect(content[1].text).toContain("Context content 2"); | |
| 224 | + expect(content[2].text).toBe("User message with context"); | |
| 225 | + }); | |
| 226 | + | |
| 227 | + test("should inject thinking messages with no changes", () => { | |
| 228 | + const thinkingMessage: ThinkingChatMessage = { | |
| 229 | + role: "thinking", | |
| 230 | + content: "Thinking process...", | |
| 231 | + }; | |
| 232 | + | |
| 233 | + mockHistory = [ | |
| 234 | + { | |
| 235 | + message: thinkingMessage, | |
| 236 | + contextItems: [], | |
| 237 | + }, | |
| 238 | + ]; | |
| 239 | + | |
| 240 | + const { messages } = constructMessages( | |
| 241 | + mockHistory, | |
| 242 | + "Base System Message", | |
| 243 | + mockRules, | |
| 244 | + {}, | |
| 245 | + ); | |
| 246 | + | |
| 247 | + // Should have system message + thinking message | |
| 248 | + expect(messages.length).toBe(2); | |
| 249 | + expect(messages[1].role).toBe("thinking"); | |
| 250 | + expect(messages[1].content).toBe("Thinking process..."); | |
| 251 | + }); | |
| 252 | + | |
| 253 | + test("should inject assistant messages with no changes", () => { | |
| 254 | + const assistantMessage: AssistantChatMessage = { | |
| 255 | + role: "assistant", | |
| 256 | + content: "Assistant response", | |
| 257 | + }; | |
| 258 | + | |
| 259 | + mockHistory = [ | |
| 260 | + { | |
| 261 | + message: assistantMessage, | |
| 262 | + contextItems: [], | |
| 263 | + }, | |
| 264 | + ]; | |
| 265 | + | |
| 266 | + const { messages } = constructMessages( | |
| 267 | + mockHistory, | |
| 268 | + "Base System Message", | |
| 269 | + mockRules, | |
| 270 | + {}, | |
| 271 | + ); | |
| 272 | + | |
| 273 | + // Should have system message + assistant message | |
| 274 | + expect(messages.length).toBe(2); | |
| 275 | + expect(messages[1].role).toBe("assistant"); | |
| 276 | + expect(messages[1].content).toBe("Assistant response"); | |
| 277 | + }); | |
| 278 | + | |
| 279 | + test("should follow assistant messages with tool calls by tool messages containing the tool output", () => { | |
| 280 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 281 | + role: "assistant", | |
| 282 | + content: "I will search for that", | |
| 283 | + toolCalls: [ | |
| 284 | + { | |
| 285 | + id: "tool-call-1", | |
| 286 | + type: "function", | |
| 287 | + function: { | |
| 288 | + name: "search", | |
| 289 | + arguments: '{"query": "test"}', | |
| 290 | + }, | |
| 291 | + }, | |
| 292 | + ], | |
| 293 | + }; | |
| 294 | + | |
| 295 | + // With tool output | |
| 296 | + mockHistory = [ | |
| 297 | + { | |
| 298 | + message: { | |
| 299 | + role: "user", | |
| 300 | + content: "Can you search for something?", | |
| 301 | + } as UserChatMessage, | |
| 302 | + contextItems: [], | |
| 303 | + }, | |
| 304 | + { | |
| 305 | + message: assistantWithToolCall, | |
| 306 | + contextItems: [], | |
| 307 | + toolCallState: { | |
| 308 | + toolCallId: "tool-call-1", | |
| 309 | + toolCall: { | |
| 310 | + id: "tool-call-1", | |
| 311 | + type: "function", | |
| 312 | + function: { | |
| 313 | + name: "search", | |
| 314 | + arguments: '{"query": "test"}', | |
| 315 | + }, | |
| 316 | + }, | |
| 317 | + status: "done", | |
| 318 | + parsedArgs: { query: "test" }, | |
| 319 | + output: [createContextItem("search-result", "Search result content")], | |
| 320 | + }, | |
| 321 | + }, | |
| 322 | + ]; | |
| 323 | + | |
| 324 | + const { messages } = constructMessages( | |
| 325 | + mockHistory, | |
| 326 | + "Base System Message", | |
| 327 | + mockRules, | |
| 328 | + {}, | |
| 329 | + ); | |
| 330 | + | |
| 331 | + // Should have: system + user + assistant + tool messages | |
| 332 | + expect(messages.length).toBe(4); | |
| 333 | + expect(messages[2].role).toBe("assistant"); | |
| 334 | + expect(messages[3].role).toBe("tool"); | |
| 335 | + const toolMessage = messages[3] as ToolResultChatMessage; | |
| 336 | + expect(toolMessage.toolCallId).toBe("tool-call-1"); | |
| 337 | + expect(toolMessage.content).toContain("Search result content"); | |
| 338 | + }); | |
| 339 | + | |
| 340 | + test("should show cancelled message for cancelled tool calls", () => { | |
| 341 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 342 | + role: "assistant", | |
| 343 | + content: "I will search for that", | |
| 344 | + toolCalls: [ | |
| 345 | + { | |
| 346 | + id: "tool-call-1", | |
| 347 | + type: "function", | |
| 348 | + function: { | |
| 349 | + name: "search", | |
| 350 | + arguments: '{"query": "test"}', | |
| 351 | + }, | |
| 352 | + }, | |
| 353 | + ], | |
| 354 | + }; | |
| 355 | + | |
| 356 | + // With cancelled tool call | |
| 357 | + mockHistory = [ | |
| 358 | + { | |
| 359 | + message: assistantWithToolCall, | |
| 360 | + contextItems: [], | |
| 361 | + toolCallState: { | |
| 362 | + toolCallId: "tool-call-1", | |
| 363 | + toolCall: { | |
| 364 | + id: "tool-call-1", | |
| 365 | + type: "function", | |
| 366 | + function: { | |
| 367 | + name: "search", | |
| 368 | + arguments: '{"query": "test"}', | |
| 369 | + }, | |
| 370 | + }, | |
| 371 | + status: "canceled", | |
| 372 | + parsedArgs: { query: "test" }, | |
| 373 | + }, | |
| 374 | + }, | |
| 375 | + ]; | |
| 376 | + | |
| 377 | + const { messages } = constructMessages( | |
| 378 | + mockHistory, | |
| 379 | + "Base System Message", | |
| 380 | + mockRules, | |
| 381 | + {}, | |
| 382 | + ); | |
| 383 | + | |
| 384 | + // Should have system + assistant + tool message with cancelled message | |
| 385 | + expect(messages.length).toBe(3); | |
| 386 | + expect(messages[2].role).toBe("tool"); | |
| 387 | + const toolMessage = messages[2] as ToolResultChatMessage; | |
| 388 | + expect(toolMessage.toolCallId).toBe("tool-call-1"); | |
| 389 | + expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE); | |
| 390 | + }); | |
| 391 | + | |
| 392 | + test('should show "No tool output" for tool calls without output', () => { | |
| 393 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 394 | + role: "assistant", | |
| 395 | + content: "I will search for that", | |
| 396 | + toolCalls: [ | |
| 397 | + { | |
| 398 | + id: "tool-call-1", | |
| 399 | + type: "function", | |
| 400 | + function: { | |
| 401 | + name: "search", | |
| 402 | + arguments: '{"query": "test"}', | |
| 403 | + }, | |
| 404 | + }, | |
| 405 | + ], | |
| 406 | + }; | |
| 407 | + | |
| 408 | + // With tool call but no output | |
| 409 | + mockHistory = [ | |
| 410 | + { | |
| 411 | + message: assistantWithToolCall, | |
| 412 | + contextItems: [], | |
| 413 | + toolCallState: { | |
| 414 | + toolCallId: "tool-call-1", | |
| 415 | + toolCall: { | |
| 416 | + id: "tool-call-1", | |
| 417 | + type: "function", | |
| 418 | + function: { | |
| 419 | + name: "search", | |
| 420 | + arguments: '{"query": "test"}', | |
| 421 | + }, | |
| 422 | + }, | |
| 423 | + status: "generating", // Not done yet | |
| 424 | + parsedArgs: { query: "test" }, | |
| 425 | + }, | |
| 426 | + }, | |
| 427 | + ]; | |
| 428 | + | |
| 429 | + const { messages } = constructMessages( | |
| 430 | + mockHistory, | |
| 431 | + "Base System Message", | |
| 432 | + mockRules, | |
| 433 | + {}, | |
| 434 | + ); | |
| 435 | + | |
| 436 | + // Should have system + assistant + tool message with "No tool output" | |
| 437 | + expect(messages.length).toBe(3); | |
| 438 | + expect(messages[2].role).toBe("tool"); | |
| 439 | + expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); | |
| 440 | + }); | |
| 441 | + | |
| 442 | + test("should start with system message using base message if provided", () => { | |
| 443 | + mockHistory = [ | |
| 444 | + { | |
| 445 | + message: { role: "user", content: "Hello" } as UserChatMessage, | |
| 446 | + contextItems: [], | |
| 447 | + }, | |
| 448 | + ]; | |
| 449 | + | |
| 450 | + const { messages } = constructMessages( | |
| 451 | + mockHistory, | |
| 452 | + "Custom Base System Message", | |
| 453 | + mockRules, | |
| 454 | + {}, | |
| 455 | + ); | |
| 456 | + | |
| 457 | + expect(messages[0].role).toBe("system"); | |
| 458 | + expect(messages[0].content).toContain("Custom Base System Message"); | |
| 459 | + }); | |
| 460 | + | |
| 461 | + test("should handle multiple tool calls in a single assistant message", () => { | |
| 462 | + const assistantWithMultipleToolCalls: AssistantChatMessage = { | |
| 463 | + role: "assistant", | |
| 464 | + content: "I will search and check the weather", | |
| 465 | + toolCalls: [ | |
| 466 | + { | |
| 467 | + id: "tool-call-1", | |
| 468 | + type: "function", | |
| 469 | + function: { | |
| 470 | + name: "search", | |
| 471 | + arguments: '{"query": "test"}', | |
| 472 | + }, | |
| 473 | + }, | |
| 474 | + { | |
| 475 | + id: "tool-call-2", | |
| 476 | + type: "function", | |
| 477 | + function: { | |
| 478 | + name: "weather", | |
| 479 | + arguments: '{"location": "New York"}', | |
| 480 | + }, | |
| 481 | + }, | |
| 482 | + ], | |
| 483 | + }; | |
| 484 | + | |
| 485 | + // Only the first tool call has output | |
| 486 | + mockHistory = [ | |
| 487 | + { | |
| 488 | + message: assistantWithMultipleToolCalls, | |
| 489 | + contextItems: [], | |
| 490 | + toolCallState: { | |
| 491 | + toolCallId: "tool-call-1", | |
| 492 | + toolCall: { | |
| 493 | + id: "tool-call-1", | |
| 494 | + type: "function", | |
| 495 | + function: { | |
| 496 | + name: "search", | |
| 497 | + arguments: '{"query": "test"}', | |
| 498 | + }, | |
| 499 | + }, | |
| 500 | + status: "done", | |
| 501 | + parsedArgs: { query: "test" }, | |
| 502 | + output: [createContextItem("search-result", "Search result content")], | |
| 503 | + }, | |
| 504 | + }, | |
| 505 | + ]; | |
| 506 | + | |
| 507 | + const { messages } = constructMessages( | |
| 508 | + mockHistory, | |
| 509 | + "Base System Message", | |
| 510 | + mockRules, | |
| 511 | + {}, | |
| 512 | + ); | |
| 513 | + | |
| 514 | + // Should have: system + assistant + 2 tool messages | |
| 515 | + expect(messages.length).toBe(4); | |
| 516 | + expect(messages[1].role).toBe("assistant"); | |
| 517 | + | |
| 518 | + // First tool message should have output | |
| 519 | + expect(messages[2].role).toBe("tool"); | |
| 520 | + expect(messages[3].role).toBe("tool"); | |
| 521 | + | |
| 522 | + const toolMessage1 = messages[2] as ToolResultChatMessage; | |
| 523 | + const toolMessage2 = messages[3] as ToolResultChatMessage; | |
| 524 | + expect(toolMessage1.toolCallId).toBe("tool-call-1"); | |
| 525 | + expect(toolMessage1.content).toContain("Search result content"); | |
| 526 | + | |
| 527 | + // Second tool message should have "No tool output" | |
| 528 | + expect(toolMessage2.toolCallId).toBe("tool-call-2"); | |
| 529 | + expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); | |
| 530 | + }); | |
| 531 | + | |
| 532 | + test("should handle messages with array content", () => { | |
| 533 | + // User message with array content (including an image) | |
| 534 | + const userMessageWithArray: UserChatMessage = { | |
| 535 | + role: "user", | |
| 536 | + content: [ | |
| 537 | + { type: "text", text: "Here is some text" }, | |
| 538 | + { | |
| 539 | + type: "imageUrl", | |
| 540 | + imageUrl: { url: "https://example.com/image.jpg" }, | |
| 541 | + }, | |
| 542 | + ], | |
| 543 | + }; | |
| 544 | + | |
| 545 | + mockHistory = [ | |
| 546 | + { | |
| 547 | + message: userMessageWithArray, | |
| 548 | + contextItems: [createContextItem("ctx", "Context text")], | |
| 549 | + }, | |
| 550 | + ]; | |
| 551 | + | |
| 552 | + const { messages, appliedRules } = constructMessages( | |
| 553 | + mockHistory, | |
| 554 | + "Base System Message", | |
| 555 | + mockRules, | |
| 556 | + {}, | |
| 557 | + ); | |
| 558 | + | |
| 559 | + // Check the user message content structure | |
| 560 | + expect(messages.length).toBe(2); | |
| 561 | + expect(messages[1].role).toBe("user"); | |
| 562 | + | |
| 563 | + const content = messages[1].content as any[]; | |
| 564 | + // Should have context item + original 2 parts | |
| 565 | + expect(content.length).toBe(3); | |
| 566 | + expect(content[0].type).toBe("text"); | |
| 567 | + expect(content[0].text).toContain("Context text"); | |
| 568 | + expect(content[1].type).toBe("text"); | |
| 569 | + expect(content[1].text).toBe("Here is some text"); | |
| 570 | + expect(content[2].type).toBe("imageUrl"); | |
| 571 | + expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg"); | |
| 572 | + | |
| 573 | + // This also verifies that rules are NOT applied if the triggers are not present | |
| 574 | + expect(appliedRules).toHaveLength(1); | |
| 575 | + expect(appliedRules).toContainEqual(NORMAL_RULE); | |
| 576 | + }); | |
| 577 | + | |
| 578 | + test("system message should include rules triggered by context items from the last user message forward", () => { | |
| 579 | + // Create context item that should trigger the CONTEXT_RULE | |
| 580 | + const triggeringContextItem = createContextItem( | |
| 581 | + "trigger", | |
| 582 | + `Some content with ${CONTEXT_RULE.description} in it`, | |
| 583 | + ); | |
| 584 | + | |
| 585 | + mockHistory = [ | |
| 586 | + // First user message with non-triggering context | |
| 587 | + { | |
| 588 | + message: { role: "user", content: "First message" } as UserChatMessage, | |
| 589 | + contextItems: [createContextItem("normal", "Normal context")], | |
| 590 | + }, | |
| 591 | + // Assistant response | |
| 592 | + { | |
| 593 | + message: { | |
| 594 | + role: "assistant", | |
| 595 | + content: "Assistant response", | |
| 596 | + } as AssistantChatMessage, | |
| 597 | + contextItems: [], | |
| 598 | + }, | |
| 599 | + // Last user message with triggering context | |
| 600 | + { | |
| 601 | + message: { role: "user", content: "Last message" } as UserChatMessage, | |
| 602 | + contextItems: [triggeringContextItem], | |
| 603 | + }, | |
| 604 | + ]; | |
| 605 | + | |
| 606 | + const { messages, appliedRules } = constructMessages( | |
| 607 | + mockHistory, | |
| 608 | + "Base System Message", | |
| 609 | + mockRules, | |
| 610 | + {}, | |
| 611 | + ); | |
| 612 | + | |
| 613 | + // Verify context rule was applied in the system message | |
| 614 | + expect(appliedRules).toHaveLength(2); | |
| 615 | + expect(appliedRules).toContainEqual(NORMAL_RULE); | |
| 616 | + expect(appliedRules).toContainEqual(CONTEXT_RULE); | |
| 617 | + expect(messages[0].role).toBe("system"); | |
| 618 | + expect(messages[0].content).toContain("Base System Message"); | |
| 619 | + expect(messages[0].content).toContain(CONTEXT_RULE.rule); | |
| 620 | + }); | |
| 621 | + | |
| 622 | + test("system message should include rules triggered by tool output after the last user message", () => { | |
| 623 | + // Create a history with a user message, assistant with tool call, and tool output containing triggering content | |
| 624 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 625 | + role: "assistant", | |
| 626 | + content: "I will search for that", | |
| 627 | + toolCalls: [ | |
| 628 | + { | |
| 629 | + id: "tool-call-1", | |
| 630 | + type: "function", | |
| 631 | + function: { | |
| 632 | + name: "search", | |
| 633 | + arguments: '{"query": "test"}', | |
| 634 | + }, | |
| 635 | + }, | |
| 636 | + ], | |
| 637 | + }; | |
| 638 | + | |
| 639 | + // Tool output containing the trigger for CONTEXT_RULE | |
| 640 | + const triggeringToolOutput = createContextItem( | |
| 641 | + "search-result", | |
| 642 | + `Search result with ${CONTEXT_RULE.description} trigger`, | |
| 643 | + ); | |
| 644 | + | |
| 645 | + mockHistory = [ | |
| 646 | + { | |
| 647 | + message: { | |
| 648 | + role: "user", | |
| 649 | + content: "Can you search for something?", | |
| 650 | + } as UserChatMessage, | |
| 651 | + contextItems: [], | |
| 652 | + }, | |
| 653 | + { | |
| 654 | + message: assistantWithToolCall, | |
| 655 | + contextItems: [], | |
| 656 | + toolCallState: { | |
| 657 | + toolCallId: "tool-call-1", | |
| 658 | + toolCall: { | |
| 659 | + id: "tool-call-1", | |
| 660 | + type: "function", | |
| 661 | + function: { | |
| 662 | + name: "search", | |
| 663 | + arguments: '{"query": "test"}', | |
| 664 | + }, | |
| 665 | + }, | |
| 666 | + status: "done", | |
| 667 | + parsedArgs: { query: "test" }, | |
| 668 | + output: [triggeringToolOutput], | |
| 669 | + }, | |
| 670 | + }, | |
| 671 | + ]; | |
| 672 | + | |
| 673 | + const { messages, appliedRules } = constructMessages( | |
| 674 | + mockHistory, | |
| 675 | + "Base System Message", | |
| 676 | + mockRules, | |
| 677 | + {}, | |
| 678 | + ); | |
| 679 | + | |
| 680 | + // Verify context rule was applied in the system message due to the tool output | |
| 681 | + expect(appliedRules).toHaveLength(2); | |
| 682 | + expect(appliedRules).toContainEqual(NORMAL_RULE); | |
| 683 | + expect(appliedRules).toContainEqual(CONTEXT_RULE); | |
| 684 | + expect(messages[0].role).toBe("system"); | |
| 685 | + expect(messages[0].content).toContain("Base System Message"); | |
| 686 | + expect(messages[0].content).toContain(CONTEXT_RULE.rule); | |
| 687 | + }); | |
| 688 | + | |
| 689 | + test("system message should only apply rules triggered by the last user message", () => { | |
| 690 | + // First user message with trigger for LAST_MESSAGE_RULE | |
| 691 | + const firstUserMessage = { | |
| 692 | + role: "user", | |
| 693 | + content: `This contains ${LAST_MESSAGE_RULE.description}`, | |
| 694 | + } as UserChatMessage; | |
| 695 | + | |
| 696 | + // Last user message without any triggers | |
| 697 | + const lastUserMessage = { | |
| 698 | + role: "user", | |
| 699 | + content: "This is a normal message", | |
| 700 | + } as UserChatMessage; | |
| 701 | + | |
| 702 | + mockHistory = [ | |
| 703 | + { | |
| 704 | + message: firstUserMessage, | |
| 705 | + contextItems: [], | |
| 706 | + }, | |
| 707 | + { | |
| 708 | + message: { | |
| 709 | + role: "assistant", | |
| 710 | + content: "First response", | |
| 711 | + } as AssistantChatMessage, | |
| 712 | + contextItems: [], | |
| 713 | + }, | |
| 714 | + { | |
| 715 | + message: lastUserMessage, | |
| 716 | + contextItems: [], | |
| 717 | + }, | |
| 718 | + ]; | |
| 719 | + | |
| 720 | + const { messages, appliedRules } = constructMessages( | |
| 721 | + mockHistory, | |
| 722 | + "Base System Message", | |
| 723 | + mockRules, | |
| 724 | + {}, | |
| 725 | + ); | |
| 726 | + | |
| 727 | + // LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message | |
| 728 | + expect(appliedRules).toHaveLength(1); | |
| 729 | + expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply | |
| 730 | + expect(messages[0].role).toBe("system"); | |
| 731 | + expect(messages[0].content).toContain("Base System Message"); | |
| 732 | + expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule); | |
| 733 | + }); | |
| 734 | +}); |
added gui/src/redux/util/constructMessages.ts +173 −0
| @@ -0,0 +1,173 @@ | ||
| 1 | +import { | |
| 2 | + ChatHistoryItem, | |
| 3 | + ChatMessage, | |
| 4 | + ContextItemWithId, | |
| 5 | + ModelDescription, | |
| 6 | + RuleWithSource, | |
| 7 | + TextMessagePart, | |
| 8 | + ToolResultChatMessage, | |
| 9 | + UserChatMessage, | |
| 10 | +} from "core"; | |
| 11 | +import { | |
| 12 | + DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 13 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 14 | +} from "core/llm/defaultSystemMessages"; | |
| 15 | +import { chatMessageIsEmpty } from "core/llm/messages"; | |
| 16 | +import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; | |
| 17 | +import { RulePolicies } from "core/llm/rules/types"; | |
| 18 | +import { findLast, findLastIndex } from "core/util/findLast"; | |
| 19 | +import { | |
| 20 | + normalizeToMessageParts, | |
| 21 | + renderContextItems, | |
| 22 | +} from "core/util/messageContent"; | |
| 23 | +import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; | |
| 24 | + | |
| 25 | +export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; | |
| 26 | +export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; | |
| 27 | + | |
| 28 | +interface MessageWithContextItems { | |
| 29 | + ctxItems: ContextItemWithId[]; | |
| 30 | + message: ChatMessage; | |
| 31 | +} | |
| 32 | +export function constructMessages( | |
| 33 | + history: ChatHistoryItem[], | |
| 34 | + baseSystemMessage: string | undefined, | |
| 35 | + availableRules: RuleWithSource[], | |
| 36 | + rulePolicies: RulePolicies, | |
| 37 | +): { | |
| 38 | + messages: ChatMessage[]; | |
| 39 | + appliedRules: RuleWithSource[]; | |
| 40 | + appliedRuleIndex: number; | |
| 41 | +} { | |
| 42 | + const historyCopy = [...history]; | |
| 43 | + | |
| 44 | + const msgs: MessageWithContextItems[] = []; | |
| 45 | + let appliedRuleIndex = -1; | |
| 46 | + let index = -1; | |
| 47 | + for (const item of historyCopy) { | |
| 48 | + index++; | |
| 49 | + if ( | |
| 50 | + item.message.role === "system" || | |
| 51 | + item.message.role === "tool" || | |
| 52 | + chatMessageIsEmpty(item.message) | |
| 53 | + ) { | |
| 54 | + // Tool messages will be re-inserted | |
| 55 | + continue; | |
| 56 | + } | |
| 57 | + | |
| 58 | + if (item.message.role === "user") { | |
| 59 | + appliedRuleIndex = index; | |
| 60 | + // Gather context items for user messages | |
| 61 | + let content = normalizeToMessageParts(item.message); | |
| 62 | + | |
| 63 | + const ctxItemParts = item.contextItems | |
| 64 | + .map((ctxItem) => { | |
| 65 | + return { | |
| 66 | + type: "text", | |
| 67 | + text: `${ctxItem.content}\n`, | |
| 68 | + } as TextMessagePart; | |
| 69 | + }) | |
| 70 | + .filter((part) => !!part.text.trim()); | |
| 71 | + | |
| 72 | + content = [...ctxItemParts, ...content]; | |
| 73 | + msgs.push({ | |
| 74 | + ctxItems: item.contextItems, | |
| 75 | + message: { | |
| 76 | + ...item.message, | |
| 77 | + content, | |
| 78 | + }, | |
| 79 | + }); | |
| 80 | + } else if (item.message.role === "thinking") { | |
| 81 | + msgs.push({ | |
| 82 | + ctxItems: item.contextItems, | |
| 83 | + message: item.message, | |
| 84 | + }); | |
| 85 | + } else if (item.message.role === "assistant") { | |
| 86 | + msgs.push({ | |
| 87 | + ctxItems: item.contextItems, | |
| 88 | + message: item.message, | |
| 89 | + }); | |
| 90 | + | |
| 91 | + // Add a tool message for each tool call | |
| 92 | + if (item.message.toolCalls?.length) { | |
| 93 | + // If the assistant message has tool calls, we need to insert tool messages | |
| 94 | + for (const toolCall of item.message.toolCalls) { | |
| 95 | + let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE; | |
| 96 | + // TODO parallel tool calls: toolCallState only supports one tool call per message for now | |
| 97 | + if (item.toolCallState?.status === "canceled") { | |
| 98 | + content = CANCELLED_TOOL_CALL_MESSAGE; | |
| 99 | + } else if ( | |
| 100 | + item.toolCallState?.toolCallId === toolCall.id && | |
| 101 | + item.toolCallState?.output | |
| 102 | + ) { | |
| 103 | + content = renderContextItems(item.toolCallState.output); | |
| 104 | + } | |
| 105 | + msgs.push({ | |
| 106 | + ctxItems: toolCallStateToContextItems(item.toolCallState), | |
| 107 | + message: { | |
| 108 | + role: "tool", | |
| 109 | + content, | |
| 110 | + toolCallId: toolCall.id!, | |
| 111 | + }, | |
| 112 | + }); | |
| 113 | + } | |
| 114 | + } | |
| 115 | + } | |
| 116 | + } | |
| 117 | + | |
| 118 | + // Some rules only apply to the last user or tool message | |
| 119 | + const lastUserOrToolMsg = findLast( | |
| 120 | + msgs, | |
| 121 | + (item) => item.message.role === "user" || item.message.role === "tool", | |
| 122 | + )?.message as UserChatMessage | ToolResultChatMessage; | |
| 123 | + | |
| 124 | + // Some rules apply to all context items since the last user message, inclusiv | |
| 125 | + const lastUserMsgIndex = findLastIndex( | |
| 126 | + msgs, | |
| 127 | + (item) => item.message.role === "user", | |
| 128 | + ); | |
| 129 | + const itemsBackToLastUserMessage = msgs | |
| 130 | + .slice(lastUserMsgIndex, msgs.length) | |
| 131 | + .filter( | |
| 132 | + (item) => item.message.role === "tool" || item.message.role === "user", | |
| 133 | + ); | |
| 134 | + const rulesContextItems = itemsBackToLastUserMessage | |
| 135 | + .map((item) => item.ctxItems) | |
| 136 | + .flat(); | |
| 137 | + | |
| 138 | + const { systemMessage, appliedRules } = getSystemMessageWithRules({ | |
| 139 | + baseSystemMessage, | |
| 140 | + availableRules, | |
| 141 | + userMessage: lastUserOrToolMsg, | |
| 142 | + contextItems: rulesContextItems, | |
| 143 | + rulePolicies, | |
| 144 | + }); | |
| 145 | + | |
| 146 | + if (systemMessage.trim()) { | |
| 147 | + msgs.unshift({ | |
| 148 | + ctxItems: [], | |
| 149 | + message: { | |
| 150 | + role: "system", | |
| 151 | + content: systemMessage, | |
| 152 | + }, | |
| 153 | + }); | |
| 154 | + } | |
| 155 | + | |
| 156 | + const messages = msgs.map((m) => m.message); | |
| 157 | + return { | |
| 158 | + messages, | |
| 159 | + appliedRules, | |
| 160 | + appliedRuleIndex, | |
| 161 | + }; | |
| 162 | +} | |
| 163 | + | |
| 164 | +export function getBaseSystemMessage( | |
| 165 | + messageMode: string, | |
| 166 | + model: ModelDescription, | |
| 167 | +): string { | |
| 168 | + if (messageMode === "agent") { | |
| 169 | + return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; | |
| 170 | + } else { | |
| 171 | + return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; | |
| 172 | + } | |
| 173 | +} |
modified gui/src/redux/util/index.ts +34 −1
| @@ -1,4 +1,7 @@ | ||
| 1 | -import { ToolCallState } from "core"; | |
| 1 | +import { ContextItem, ToolCallState } from "core"; | |
| 2 | +import { safeParseToolCallArgs } from "core/tools/parseArgs"; | |
| 3 | +import { IIdeMessenger } from "../../context/IdeMessenger"; | |
| 4 | +import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice"; | |
| 2 | 5 | import { RootState } from "../store"; |
| 3 | 6 | |
| 4 | 7 | export function findCurrentToolCall( |
| @@ -7,6 +10,7 @@ | ||
| 7 | 10 | return chatHistory[chatHistory.length - 1]?.toolCallState; |
| 8 | 11 | } |
| 9 | 12 | |
| 13 | +// TODO parallel tool calls - find tool call must search within arrays | |
| 10 | 14 | export function findToolCall( |
| 11 | 15 | chatHistory: RootState["session"]["history"], |
| 12 | 16 | toolCallId: string, |
| @@ -15,3 +19,32 @@ | ||
| 15 | 19 | (item) => item.toolCallState?.toolCallId === toolCallId, |
| 16 | 20 | )?.toolCallState; |
| 17 | 21 | } |
| 22 | + | |
| 23 | +export function findToolOutput( | |
| 24 | + chatHistory: RootState["session"]["history"], | |
| 25 | + toolCallId: string, | |
| 26 | +): ChatHistoryItemWithMessageId | undefined { | |
| 27 | + return chatHistory.find( | |
| 28 | + (item) => | |
| 29 | + item.message.role === "tool" && item.message.toolCallId === toolCallId, | |
| 30 | + ); | |
| 31 | +} | |
| 32 | + | |
| 33 | +export function logToolUsage( | |
| 34 | + toolCallState: ToolCallState, | |
| 35 | + success: boolean, | |
| 36 | + messenger: IIdeMessenger, | |
| 37 | + finalOutput?: ContextItem[], | |
| 38 | +) { | |
| 39 | + messenger.post("devdata/log", { | |
| 40 | + name: "toolUsage", | |
| 41 | + data: { | |
| 42 | + toolCallId: toolCallState.toolCallId, | |
| 43 | + functionName: toolCallState.toolCall?.function?.name, | |
| 44 | + functionArgs: toolCallState.toolCall?.function?.arguments, | |
| 45 | + toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), | |
| 46 | + output: finalOutput || toolCallState.output || [], | |
| 47 | + succeeded: success, | |
| 48 | + }, | |
| 49 | + }); | |
| 50 | +} |
modified gui/src/util/index.ts +0 −52
| @@ -1,10 +1,4 @@ | ||
| 1 | -import { MessageModes, ModelDescription } from "core"; | |
| 2 | 1 | import { ProfileDescription } from "core/config/ProfileLifecycleManager"; |
| 3 | -import { | |
| 4 | - DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 5 | - DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 6 | -} from "core/llm/constructMessages"; | |
| 7 | -import _ from "lodash"; | |
| 8 | 2 | import { KeyboardEvent as ReactKeyboardEvent } from "react"; |
| 9 | 3 | import { getLocalStorage } from "./localStorage"; |
| 10 | 4 | |
| @@ -88,52 +82,6 @@ | ||
| 88 | 82 | return false; |
| 89 | 83 | } |
| 90 | 84 | |
| 91 | -/** | |
| 92 | - * Updates the values of an object's properties based on the specified paths. | |
| 93 | - * | |
| 94 | - * This function creates a deep clone of the provided object and updates its properties | |
| 95 | - * based on the given path-to-value mappings. If a value in the mapping is a function, | |
| 96 | - * it will be used to determine the new value for the property. Otherwise, the value itself | |
| 97 | - * will be set for the property. | |
| 98 | - * | |
| 99 | - * @param {Object} old - The original object to be cloned and updated. | |
| 100 | - * @param {Object} pathToValue - An object where the keys represent the paths to the properties | |
| 101 | - * to be updated and the values represent the new values or functions | |
| 102 | - * to determine the new values. | |
| 103 | - * @returns {Object} A new object with the updated values. | |
| 104 | - */ | |
| 105 | -export function updatedObj(old: any, pathToValue: { [key: string]: any }) { | |
| 106 | - const newObject = _.cloneDeep(old); | |
| 107 | - | |
| 108 | - for (const key in pathToValue) { | |
| 109 | - if (typeof pathToValue[key] === "function") { | |
| 110 | - _.updateWith(newObject, key, pathToValue[key]); | |
| 111 | - } else { | |
| 112 | - _.updateWith(newObject, key, (__) => pathToValue[key]); | |
| 113 | - } | |
| 114 | - } | |
| 115 | - | |
| 116 | - return newObject; | |
| 117 | -} | |
| 118 | - | |
| 119 | 85 | export function isLocalProfile(profile: ProfileDescription): boolean { |
| 120 | 86 | return profile.profileType === "local"; |
| 121 | 87 | } |
| 122 | - | |
| 123 | -/** | |
| 124 | - * Get the base system message for the agent or chat mode from the model description. | |
| 125 | - */ | |
| 126 | -export function getBaseSystemMessage( | |
| 127 | - modelDetails: ModelDescription | null, | |
| 128 | - mode: MessageModes, | |
| 129 | -) { | |
| 130 | - let baseChatOrAgentSystemMessage: string | undefined; | |
| 131 | - if (mode === "agent") { | |
| 132 | - baseChatOrAgentSystemMessage = | |
| 133 | - modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; | |
| 134 | - } else { | |
| 135 | - baseChatOrAgentSystemMessage = | |
| 136 | - modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; | |
| 137 | - } | |
| 138 | - return baseChatOrAgentSystemMessage; | |
| 139 | -} |
modified packages/config-yaml/src/schemas/data/index.ts +10 −0
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | editInteractionEventSchema_0_2_0, |
| 29 | 29 | editInteractionEventSchema_0_2_0_noCode, |
| 30 | 30 | } from "./editInteraction/v0.2.0.js"; |
| 31 | +import { editOutcomeEventAllSchema } from "./editOutcome/index.js"; | |
| 31 | 32 | import { |
| 32 | 33 | editOutcomeEventSchema_0_2_0, |
| 33 | 34 | editOutcomeEventSchema_0_2_0_noCode, |
| @@ -51,6 +52,11 @@ | ||
| 51 | 52 | tokensGeneratedEventSchema_0_2_0, |
| 52 | 53 | tokensGeneratedEventSchema_0_2_0_noCode, |
| 53 | 54 | } 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"; | |
| 54 | 60 | |
| 55 | 61 | const semverRegex = |
| 56 | 62 | /^(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-]+)*))?$/; |
| @@ -81,7 +87,9 @@ | ||
| 81 | 87 | tokensGenerated: tokensGeneratedEventAllSchema, |
| 82 | 88 | chatInteraction: chatInteractionEventAllSchema, |
| 83 | 89 | editInteraction: editInteractionEventAllSchema, |
| 90 | + editOutcome: editOutcomeEventAllSchema, | |
| 84 | 91 | nextEdit: nextEditEventAllSchema, |
| 92 | + toolUsage: toolUsageEventAllSchema, | |
| 85 | 93 | }); |
| 86 | 94 | |
| 87 | 95 | // Version and level specific schemas are organized here |
| @@ -109,6 +117,7 @@ | ||
| 109 | 117 | editInteraction: editInteractionEventSchema_0_2_0, |
| 110 | 118 | editOutcome: editOutcomeEventSchema_0_2_0, |
| 111 | 119 | nextEdit: nextEditEventSchema_0_2_0, |
| 120 | + toolUsage: toolUsageEventSchema_0_2_0, | |
| 112 | 121 | }, |
| 113 | 122 | noCode: { |
| 114 | 123 | autocomplete: autocompleteEventSchema_0_2_0_noCode, |
| @@ -118,6 +127,7 @@ | ||
| 118 | 127 | editInteraction: editInteractionEventSchema_0_2_0_noCode, |
| 119 | 128 | editOutcome: editOutcomeEventSchema_0_2_0_noCode, |
| 120 | 129 | nextEdit: nextEditEventSchema_0_2_0_noCode, |
| 130 | + toolUsage: toolUsageEventSchema_0_2_0_noCode, | |
| 121 | 131 | }, |
| 122 | 132 | }, |
| 123 | 133 | }; |
added packages/config-yaml/src/schemas/data/toolUsage/index.ts +11 −0
| @@ -0,0 +1,11 @@ | ||
| 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 | + succeeded: z.boolean(), | |
| 10 | + output: z.array(z.any()).optional(), | |
| 11 | +}); |
added packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts +26 −0
| @@ -0,0 +1,26 @@ | ||
| 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 | + succeeded: true, | |
| 18 | + output: true, | |
| 19 | +}); | |
| 20 | + | |
| 21 | +export const toolUsageEventSchema_0_2_0_noCode = | |
| 22 | + toolUsageEventSchema_0_2_0.omit({ | |
| 23 | + functionArgs: true, | |
| 24 | + toolCallArgs: true, | |
| 25 | + output: true, | |
| 26 | + }); |