diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.vitest.ts similarity index 89% rename from core/config/ConfigHandler.test.ts rename to core/config/ConfigHandler.vitest.ts index 4b4be0762..5af9d6bb8 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.vitest.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import path from "node:path"; +import { describe, expect, test } from "vitest"; import { testConfigHandler } from "../test/fixtures"; import { TEST_DIR } from "../test/testDir"; import { getConfigTsPath } from "../util/paths"; @@ -24,7 +25,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { ); }); - test.skip("should add a system message from config.ts", async () => { + test("should add a system message from config.ts", async () => { const configTs = `export function modifyConfig(config: Config): Config { config.systemMessage = "SYSTEM"; return config; @@ -39,7 +40,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { expect(config.systemMessage).toBe("SYSTEM"); }); - test.skip("should acknowledge override from .continuerc.json", async () => { + test("should acknowledge override from .continuerc.json", async () => { fs.writeFileSync( path.join(TEST_DIR, ".continuerc.json"), JSON.stringify({ systemMessage: "SYSTEM2" }), diff --git a/core/config/loadLocalAssistants.test.ts b/core/config/loadLocalAssistants.vitest.ts similarity index 99% rename from core/config/loadLocalAssistants.test.ts rename to core/config/loadLocalAssistants.vitest.ts index 2865a5b34..a366316d4 100644 --- a/core/config/loadLocalAssistants.test.ts +++ b/core/config/loadLocalAssistants.vitest.ts @@ -1,3 +1,4 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { walkDirCache } from "../indexing/walkDir"; import { testIde } from "../test/fixtures"; import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir"; diff --git a/core/config/usesFreeTrialApiKey.test.ts b/core/config/usesFreeTrialApiKey.test.ts deleted file mode 100644 index 8e8727084..000000000 --- a/core/config/usesFreeTrialApiKey.test.ts +++ /dev/null @@ -1,344 +0,0 @@ -import { jest } from "@jest/globals"; -import { BrowserSerializedContinueConfig } from ".."; - -// Create the mock before importing anything else -const mockDecodeSecretLocation = jest.fn(); - -// Mock the module -jest.unstable_mockModule("@continuedev/config-yaml", () => ({ - SecretType: { - User: "user", - Organization: "organization", - FreeTrial: "free_trial", - }, - decodeSecretLocation: mockDecodeSecretLocation, -})); - -// Import after mocking -const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey"); -const { SecretType } = await import("@continuedev/config-yaml"); - -beforeEach(() => { - mockDecodeSecretLocation.mockReset(); -}); - -test("usesFreeTrialApiKey should return false when config is null", () => { - const result = usesFreeTrialApiKey(null); - expect(result).toBe(false); -}); - -test("usesFreeTrialApiKey should return false when config is undefined", () => { - const result = usesFreeTrialApiKey(undefined as any); - expect(result).toBe(false); -}); - -test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - underlyingProviderName: "test", - }, - { - title: "Model 2", - provider: "test", - model: "test-model-2", - underlyingProviderName: "test", - }, - ], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); -}); - -test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "user:testuser/api-key", - underlyingProviderName: "test", - }, - ], - edit: [ - { - title: "Model 2", - provider: "test", - model: "test-model-2", - apiKeyLocation: "organization:testorg/api-key", - underlyingProviderName: "test", - }, - ], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation - .mockReturnValueOnce({ - secretType: SecretType.User, - userSlug: "testuser", - secretName: "api-key", - }) - .mockReturnValueOnce({ - secretType: SecretType.Organization, - orgSlug: "testorg", - secretName: "api-key", - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); -}); - -test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "user:testuser/api-key", - underlyingProviderName: "test", - }, - { - title: "Free Trial Model", - provider: "test", - model: "free-trial-model", - apiKeyLocation: "free_trial:owner/package/api-key", - underlyingProviderName: "test", - }, - ], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation - .mockReturnValueOnce({ - secretType: SecretType.User, - userSlug: "testuser", - secretName: "api-key", - }) - .mockReturnValueOnce({ - secretType: SecretType.FreeTrial, - blockSlug: { ownerSlug: "owner", packageSlug: "package" }, - secretName: "api-key", - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(true); - expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); -}); - -test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "user:testuser/api-key", - underlyingProviderName: "test", - }, - ], - edit: [ - { - title: "Free Trial Edit Model", - provider: "test", - model: "free-trial-edit-model", - apiKeyLocation: "free_trial:owner/package/api-key", - underlyingProviderName: "test", - }, - ], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation - .mockReturnValueOnce({ - secretType: SecretType.User, - userSlug: "testuser", - secretName: "api-key", - }) - .mockReturnValueOnce({ - secretType: SecretType.FreeTrial, - blockSlug: { ownerSlug: "owner", packageSlug: "package" }, - secretName: "api-key", - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(true); -}); - -test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => { - const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {}); - - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "invalid-secret-location", - underlyingProviderName: "test", - }, - ], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation.mockImplementation(() => { - throw new Error("Invalid secret location format"); - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(consoleSpy).toHaveBeenCalledWith( - "Error checking for free trial API key:", - expect.any(Error), - ); - - consoleSpy.mockRestore(); -}); - -test("usesFreeTrialApiKey should handle empty modelsByRole object", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(mockDecodeSecretLocation).not.toHaveBeenCalled(); -}); diff --git a/core/config/usesFreeTrialApiKey.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts new file mode 100644 index 000000000..b92dd90a2 --- /dev/null +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -0,0 +1,348 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { BrowserSerializedContinueConfig } from ".."; + +// Create the mock before importing anything else +const mockDecodeSecretLocation = vi.fn(); + +// Mock the module +vi.mock("@continuedev/config-yaml", () => ({ + SecretType: { + User: "user", + Organization: "organization", + FreeTrial: "free_trial", + }, + decodeSecretLocation: mockDecodeSecretLocation, +})); + +describe("usesFreeTrialApiKey", () => { + let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey; + let SecretType: typeof import("@continuedev/config-yaml").SecretType; + + beforeEach(async () => { + mockDecodeSecretLocation.mockReset(); + usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey")) + .usesFreeTrialApiKey; + SecretType = (await import("@continuedev/config-yaml")).SecretType; + }); + + test("usesFreeTrialApiKey should return false when config is null", () => { + const result = usesFreeTrialApiKey(null); + expect(result).toBe(false); + }); + + test("usesFreeTrialApiKey should return false when config is undefined", () => { + const result = usesFreeTrialApiKey(undefined as any); + expect(result).toBe(false); + }); + + test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + underlyingProviderName: "test", + }, + { + title: "Model 2", + provider: "test", + model: "test-model-2", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + }); + + test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + ], + edit: [ + { + title: "Model 2", + provider: "test", + model: "test-model-2", + apiKeyLocation: "organization:testorg/api-key", + underlyingProviderName: "test", + }, + ], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.Organization, + orgSlug: "testorg", + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); + }); + + test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + { + title: "Free Trial Model", + provider: "test", + model: "free-trial-model", + apiKeyLocation: "free_trial:owner/package/api-key", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.FreeTrial, + blockSlug: { ownerSlug: "owner", packageSlug: "package" }, + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(true); + expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); + }); + + test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + ], + edit: [ + { + title: "Free Trial Edit Model", + provider: "test", + model: "free-trial-edit-model", + apiKeyLocation: "free_trial:owner/package/api-key", + underlyingProviderName: "test", + }, + ], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.FreeTrial, + blockSlug: { ownerSlug: "owner", packageSlug: "package" }, + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(true); + }); + + test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => { + const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "invalid-secret-location", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation.mockImplementation(() => { + throw new Error("Invalid secret location format"); + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(consoleSpy).toHaveBeenCalledWith( + "Error checking for free trial API key:", + expect.any(Error), + ); + + consoleSpy.mockRestore(); + }); + + test("usesFreeTrialApiKey should handle empty modelsByRole object", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(mockDecodeSecretLocation).not.toHaveBeenCalled(); + }); +}); diff --git a/core/config/util.ts b/core/config/util.ts index 9128fc0b5..a53027a76 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -10,7 +10,7 @@ import { JSONModelDescription, PromptTemplate, } from "../"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; diff --git a/core/config/util.test.ts b/core/config/util.vitest.ts similarity index 96% rename from core/config/util.test.ts rename to core/config/util.vitest.ts index e7de79e1b..5ea63c879 100644 --- a/core/config/util.test.ts +++ b/core/config/util.vitest.ts @@ -1,3 +1,4 @@ +import { describe, expect, it } from "vitest"; import { PromptTemplate } from ".."; import { serializePromptTemplates } from "./util"; diff --git a/core/config/workspace/workspaceBlocks.test.ts b/core/config/workspace/workspaceBlocks.vitest.ts similarity index 98% rename from core/config/workspace/workspaceBlocks.test.ts rename to core/config/workspace/workspaceBlocks.vitest.ts index 532444196..281a4d785 100644 --- a/core/config/workspace/workspaceBlocks.test.ts +++ b/core/config/workspace/workspaceBlocks.vitest.ts @@ -1,5 +1,5 @@ import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml"; -import { describe, expect, test } from "@jest/globals"; +import { describe, expect, test } from "vitest"; import { findAvailableFilename, getFileContent } from "./workspaceBlocks"; describe("getFileContent", () => { diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.vitest.ts similarity index 94% rename from core/context/mcp/MCPConnection.test.ts rename to core/context/mcp/MCPConnection.vitest.ts index f8f146f07..7736ebec9 100644 --- a/core/context/mcp/MCPConnection.test.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -1,10 +1,10 @@ -import { jest } from "@jest/globals"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import MCPConnection from "./MCPConnection"; describe("MCPConnection", () => { beforeEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe("constructor", () => { @@ -131,10 +131,10 @@ describe("MCPConnection", () => { it("should connect successfully", async () => { const conn = new MCPConnection(options); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockResolvedValue(undefined); - const mockGetServerCapabilities = jest + const mockGetServerCapabilities = vi .spyOn(Client.prototype, "getServerCapabilities") .mockReturnValue({ resources: {}, @@ -142,12 +142,12 @@ describe("MCPConnection", () => { prompts: {}, }); - const mockListResources = jest + const mockListResources = vi .spyOn(Client.prototype, "listResources") .mockResolvedValue({ resources: [{ name: "test-resource", uri: "test-uri" }], }); - const mockListTools = jest + const mockListTools = vi .spyOn(Client.prototype, "listTools") .mockResolvedValue({ tools: [ @@ -159,7 +159,7 @@ describe("MCPConnection", () => { }, ], }); - const mockListPrompts = jest + const mockListPrompts = vi .spyOn(Client.prototype, "listPrompts") .mockResolvedValue({ prompts: [{ name: "test-prompt" }] }); @@ -175,7 +175,7 @@ describe("MCPConnection", () => { it("should handle custom connection timeout", async () => { const conn = new MCPConnection({ ...options, timeout: 1500 }); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockImplementation( () => new Promise((resolve) => setTimeout(resolve, 1000)), @@ -190,7 +190,7 @@ describe("MCPConnection", () => { it("should handle connection timeout", async () => { const conn = new MCPConnection({ ...options, timeout: 1 }); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockImplementation( () => new Promise((resolve) => setTimeout(resolve, 100)), @@ -208,7 +208,7 @@ describe("MCPConnection", () => { const conn = new MCPConnection(options); conn.status = "connected"; - const mockConnect = jest.spyOn(Client.prototype, "connect"); + const mockConnect = vi.spyOn(Client.prototype, "connect"); const abortController = new AbortController(); await conn.connectClient(false, abortController.signal); @@ -219,7 +219,7 @@ describe("MCPConnection", () => { it("should handle transport errors", async () => { const conn = new MCPConnection(options); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockRejectedValue(new Error("spawn test-cmd ENOENT")); @@ -233,7 +233,7 @@ describe("MCPConnection", () => { it.skip("should include stderr output in error message when stdio command fails", async () => { // Clear any existing mocks to ensure we get real behavior - jest.restoreAllMocks(); + vi.restoreAllMocks(); // Use a command that will definitely fail and produce stderr output const failingOptions = { diff --git a/core/context/mcp/MCPManagerSingleton.test.ts b/core/context/mcp/MCPManagerSingleton.vitest.ts similarity index 91% rename from core/context/mcp/MCPManagerSingleton.test.ts rename to core/context/mcp/MCPManagerSingleton.vitest.ts index 49e2389d6..f361c13a1 100644 --- a/core/context/mcp/MCPManagerSingleton.test.ts +++ b/core/context/mcp/MCPManagerSingleton.vitest.ts @@ -1,3 +1,4 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; import { MCPOptions } from "../.."; import MCPConnection from "./MCPConnection"; import { MCPManagerSingleton } from "./MCPManagerSingleton"; @@ -18,8 +19,8 @@ class TestMCPConnection extends MCPConnection { } as any; this.abortController = new AbortController(); - this.connectClient = jest.fn().mockResolvedValue(undefined); - this.getStatus = jest + this.connectClient = vi.fn().mockResolvedValue(undefined); + this.getStatus = vi .fn() .mockReturnValue({ status: "connected", errors: [] }); } @@ -54,13 +55,12 @@ describe("MCPManagerSingleton", () => { id: string, options: MCPOptions, ): MCPConnection { - if (!this.connections.has(id)) { - const connection = new TestMCPConnection(options); - this.connections.set(id, connection); - return connection; - } else { + if (this.connections.has(id)) { return this.connections.get(id)!; } + const connection = new TestMCPConnection(options); + this.connections.set(id, connection); + return connection; }; }); @@ -103,7 +103,7 @@ describe("MCPManagerSingleton", () => { "test-id", testOptions, ) as TestMCPConnection; - const closeSpy = jest.spyOn(connection.client, "close"); + const closeSpy = vi.spyOn(connection.client, "close"); await manager.removeConnection("test-id"); @@ -133,8 +133,8 @@ describe("MCPManagerSingleton", () => { "test-id", testOptions, ) as TestMCPConnection; - const abortSpy = jest.spyOn(connection.abortController, "abort"); - const closeSpy = jest.spyOn(connection.client, "close"); + const abortSpy = vi.spyOn(connection.abortController, "abort"); + const closeSpy = vi.spyOn(connection.client, "close"); // Remove it by setting empty server list manager.setConnections([], false); @@ -192,7 +192,7 @@ describe("MCPManagerSingleton", () => { }); it("should call onConnectionsRefreshed if defined", async () => { - const mockCallback = jest.fn(); + const mockCallback = vi.fn(); manager.onConnectionsRefreshed = mockCallback; manager.createConnection("test-id", testOptions); @@ -209,7 +209,7 @@ describe("MCPManagerSingleton", () => { testOptions, ) as TestMCPConnection; const mockStatus = { status: "connected", errors: [] }; - connection.getStatus = jest.fn().mockReturnValue(mockStatus); + connection.getStatus = vi.fn().mockReturnValue(mockStatus); const statuses = manager.getStatuses(); expect(statuses).toHaveLength(1); diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.vitest.ts similarity index 90% rename from core/context/providers/_context-providers.test.ts rename to core/context/providers/_context-providers.vitest.ts index 468aac6ec..7ae55d32e 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.vitest.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; +import { afterAll, describe, expect, test } from "vitest"; import { contextProviderClassFromName } from "."; import { ContextProviderExtras, @@ -8,7 +9,7 @@ import { } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { LLMLogger } from "../../llm/logger"; -import { TEST_DIR } from "../../test/testDir"; +import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir"; import FileSystemIde from "../../util/filesystem"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ @@ -25,6 +26,7 @@ const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ async function getContextProviderExtras( fullInput: string, ): Promise { + setUpTestDir(); const ide = new FileSystemIde(TEST_DIR); const ideSettingsPromise = ide.getIdeSettings(); const llmLogger = new LLMLogger(); @@ -52,6 +54,10 @@ async function getContextProviderExtras( } describe.skip("Should successfully run all context providers", () => { + afterAll(() => { + tearDownTestDir(); + }); + const extrasPromise = getContextProviderExtras("Test"); CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => { diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index bbae656c2..910b16c14 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,5 +1,6 @@ import { BaseContextProvider } from "../"; import { ContextProviderName } from "../../"; +import { Telemetry } from "../../util/posthog"; import ClipboardContextProvider from "./ClipboardContextProvider"; import CodebaseContextProvider from "./CodebaseContextProvider"; @@ -75,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [ export function contextProviderClassFromName( name: ContextProviderName, ): typeof BaseContextProvider | undefined { - return Providers.find((cls) => cls.description.title === name); + const provider = Providers.find((cls) => cls.description.title === name); + + void Telemetry.capture("context_provider_load", { + providerName: name, + found: !!provider, // also capture those which user expected to be present + }); + + return provider; } diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 28de3d096..6829e7d75 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -107,7 +107,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); results.sort( - (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], + (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!], ); results = results.slice(-this.options.nFinal); return results; diff --git a/core/context/retrieval/utils.test.ts b/core/context/retrieval/utils.vitest.ts similarity index 98% rename from core/context/retrieval/utils.test.ts rename to core/context/retrieval/utils.vitest.ts index 4b8d9d3fe..133e30c8e 100644 --- a/core/context/retrieval/utils.test.ts +++ b/core/context/retrieval/utils.vitest.ts @@ -1,6 +1,6 @@ // Generated by Continue +import { describe, expect, it } from "vitest"; import { Chunk } from "../../index"; - import { deduplicateChunks } from "./util"; describe("deduplicateChunks", () => { diff --git a/core/core.ts b/core/core.ts index 9896411ee..613bd0807 100644 --- a/core/core.ts +++ b/core/core.ts @@ -872,7 +872,7 @@ export class Core { this.messenger.send("toolCallPartialOutput", params); }; - return await callTool(tool, toolCall, { + const result = await callTool(tool, toolCall, { config, ide: this.ide, llm: config.selectedModelByRole.chat, @@ -883,6 +883,8 @@ export class Core { onPartialOutput, codeBaseIndexer: this.codeBaseIndexer, }); + + return result; } private async isItemTooBig(item: ContextItemWithId) { @@ -1105,6 +1107,10 @@ export class Core { itemId: uuidv4(), }; + void Telemetry.capture("context_provider_get_context_items", { + name: provider.description.title, + }); + const items = await provider.getContextItems(query, { config, llm, diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index f64448f36..daa1b6c35 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -112,7 +112,7 @@ export async function* streamDiffLines({ // If any rules are present this will result in using chat instead of legacy completion const systemMessage = rulesToInclude ? getSystemMessageWithRules({ - rules: rulesToInclude, + availableRules: rulesToInclude, userMessage: typeof prompt === "string" ? ({ @@ -125,7 +125,7 @@ export async function* streamDiffLines({ ) as UserChatMessage | ToolResultChatMessage | undefined), baseSystemMessage: undefined, contextItems: [], - }) + }).systemMessage : undefined; if (systemMessage) { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts deleted file mode 100644 index dc9dbc8bf..000000000 --- a/core/llm/constructMessages.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { - ChatHistoryItem, - ChatMessage, - ContextItemWithId, - RuleWithSource, - TextMessagePart, - ToolResultChatMessage, - UserChatMessage, -} from "../"; -import { findLast } from "../util/findLast"; -import { normalizeToMessageParts } from "../util/messageContent"; -import { isUserOrToolMsg } from "./messages"; -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -import { RulePolicies } from "./rules/types"; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; - -export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ - Always include the language and file name in the info string when you write code blocks. - If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' -`; - -export const EDIT_CODE_INSTRUCTIONS = `\ - When addressing code modification requests, present a concise code snippet that - emphasizes only the necessary changes and uses abbreviated placeholders for - unmodified sections. For example: - - \`\`\`language /path/to/file - // ... existing code ... - - {{ modified code here }} - - // ... existing code ... - - {{ another modification }} - - // ... rest of code ... - \`\`\` - - In existing files, you should always restate the function or class that the snippet belongs to: - - \`\`\`language /path/to/file - // ... existing code ... - - function exampleFunction() { - // ... existing code ... - - {{ modified code here }} - - // ... rest of function ... - } - - // ... rest of code ... - \`\`\` - - Since users have access to their complete file, they prefer reading only the - relevant modifications. It's perfectly acceptable to omit unmodified portions - at the beginning, middle, or end of files using these "lazy" comments. Only - provide the complete file when explicitly requested. Include a concise explanation - of changes unless the user specifically asks for code only. -`; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ - - You are in chat mode. - - 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. - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. - -${CODEBLOCK_FORMATTING_INSTRUCTIONS} -${EDIT_CODE_INSTRUCTIONS} -`; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ - - You are in agent mode. - -${CODEBLOCK_FORMATTING_INSTRUCTIONS} -`; - -/** - * Helper function to get the context items for a user message - */ -function getUserContextItems( - userMsg: UserChatMessage | ToolResultChatMessage | undefined, - history: ChatHistoryItem[], -): ContextItemWithId[] { - if (!userMsg) return []; - - // Find the history item that contains the userMsg - const historyItem = history.find((item) => { - // Check if the message ID matches - if ("id" in userMsg && "id" in item.message) { - return (item.message as any).id === (userMsg as any).id; - } - // Fallback to content comparison - return ( - item.message.content === userMsg.content && - item.message.role === userMsg.role - ); - }); - - return historyItem?.contextItems || []; -} - -export function constructMessages( - messageMode: string, - history: ChatHistoryItem[], - baseChatOrAgentSystemMessage: string | undefined, - rules: RuleWithSource[], - rulePolicies?: RulePolicies, -): ChatMessage[] { - const filteredHistory = history.filter( - (item) => item.message.role !== "system", - ); - const msgs: ChatMessage[] = []; - - for (let i = 0; i < filteredHistory.length; i++) { - const historyItem = filteredHistory[i]; - - if (messageMode === "chat") { - const toolMessage: ToolResultChatMessage = - historyItem.message as ToolResultChatMessage; - if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { - // remove all tool calls from the history - continue; - } - } - - if (historyItem.message.role === "user") { - // Gather context items for user messages - let content = normalizeToMessageParts(historyItem.message); - - const ctxItems = historyItem.contextItems - .map((ctxItem) => { - return { - type: "text", - text: `${ctxItem.content}\n`, - } as TextMessagePart; - }) - .filter((part) => !!part.text.trim()); - - content = [...ctxItems, ...content]; - msgs.push({ - ...historyItem.message, - content, - }); - } else { - msgs.push(historyItem.message); - } - } - - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as - | UserChatMessage - | ToolResultChatMessage - | undefined; - - // Get context items for the last user message - const lastUserContextItems = getUserContextItems( - lastUserMsg, - filteredHistory, - ); - const systemMessage = getSystemMessageWithRules({ - baseSystemMessage: baseChatOrAgentSystemMessage, - rules, - userMessage: lastUserMsg, - contextItems: lastUserContextItems, - rulePolicies, - }); - - if (systemMessage.trim()) { - msgs.unshift({ - role: "system", - content: systemMessage, - }); - } - - // Remove the "id" from all of the messages - return msgs.map((msg) => { - const { id, ...rest } = msg as any; - return rest; - }); -} diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts new file mode 100644 index 000000000..c2f82bac4 --- /dev/null +++ b/core/llm/defaultSystemMessages.ts @@ -0,0 +1,68 @@ +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; + +export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ + Always include the language and file name in the info string when you write code blocks. + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' +`; + +export const EDIT_CODE_INSTRUCTIONS = `\ + When addressing code modification requests, present a concise code snippet that + emphasizes only the necessary changes and uses abbreviated placeholders for + unmodified sections. For example: + + \`\`\`language /path/to/file + // ... existing code ... + + {{ modified code here }} + + // ... existing code ... + + {{ another modification }} + + // ... rest of code ... + \`\`\` + + In existing files, you should always restate the function or class that the snippet belongs to: + + \`\`\`language /path/to/file + // ... existing code ... + + function exampleFunction() { + // ... existing code ... + + {{ modified code here }} + + // ... rest of function ... + } + + // ... rest of code ... + \`\`\` + + Since users have access to their complete file, they prefer reading only the + relevant modifications. It's perfectly acceptable to omit unmodified portions + at the beginning, middle, or end of files using these "lazy" comments. Only + provide the complete file when explicitly requested. Include a concise explanation + of changes unless the user specifically asks for code only. +`; + +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ + + You are in chat mode. + + 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. + If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. + +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +${EDIT_CODE_INSTRUCTIONS} +`; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ + + You are in agent mode. + +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +`; diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index a3088f409..69b4ab7a8 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -1,12 +1,10 @@ -import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; -import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; -import Bedrock from "./Bedrock.js"; import { ChatMessage, Chunk, CompletionOptions, UserChatMessage, } from "../../index.js"; +import Bedrock from "./Bedrock.js"; // Mock AWS SDK jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ @@ -317,96 +315,266 @@ describe("Bedrock", () => { }); }); - it("should convert text messages correctly", () => { - const message: ChatMessage = { - role: "user", - content: "Hello", - } as UserChatMessage; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [{ text: "Hello" }], - }); + it("should convert simple user and assistant messages correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" } as UserChatMessage, + { role: "assistant", content: "Hi there" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Hello" }] }, + { role: "assistant", content: [{ text: "Hi there" }] }, + ]); }); - it("should convert tool responses correctly", () => { - const message: ChatMessage = { - role: "tool", - content: "Tool result", - toolCallId: "tool-1", - }; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [ - { - toolResult: { - toolUseId: "tool-1", - content: [{ text: "Tool result" }], - }, - }, - ], - }); - }); - - it("should convert tool calls correctly", () => { - const message: ChatMessage = { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-1", - type: "function" as const, - function: { - name: "test_tool", - arguments: '{"arg":"value"}', - }, - }, - ], - }; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "assistant", - content: [ - { - toolUse: { - toolUseId: "tool-1", - name: "test_tool", - input: { arg: "value" }, - }, - }, - ], - }); - }); - - it("should handle multimodal content correctly", () => { - const message: ChatMessage = { - role: "user", - content: [ - { type: "text", text: "Look at this image:" }, - { - type: "imageUrl", - imageUrl: { - url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", - }, - }, - ], - } as UserChatMessage; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [ - { text: "Look at this image:" }, - { - image: { - format: "jpeg", - source: { - bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), + it("should handle tool responses correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Use a tool" } as UserChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg":"value"}', }, }, - }, - ], + ], + }, + { + role: "tool", + content: "Tool result", + toolCallId: "tool-1", + }, + ]; + + const availableTools = new Set(["test_tool"]); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Use a tool" }] }, + { + role: "assistant", + content: [ + { + toolUse: { + toolUseId: "tool-1", + name: "test_tool", + input: { arg: "value" }, + }, + }, + ], + }, + { + role: "user", + content: [ + { + toolResult: { + toolUseId: "tool-1", + content: [{ text: "Tool result" }], + }, + }, + ], + }, + ]); + }); + + it("should handle tool calls with unavailable tools as text", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Use a tool" } as UserChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-1", + type: "function", + function: { + name: "unavailable_tool", + arguments: '{"arg":"value"}', + }, + }, + ], + }, + ]; + + // Empty set means no tools are available + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Use a tool" }] }, + { + role: "assistant", + content: [ + { + text: expect.stringContaining("Assistant tool call:"), + }, + ], + }, + ]); + }); + + it("should handle thinking messages correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Think about this" } as UserChatMessage, + { role: "thinking", content: "I am thinking about the solution" }, + { role: "assistant", content: "Here's my answer" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Think about this" }] }, + { + role: "assistant", + content: [ + { + reasoningContent: { + reasoningText: { + text: "I am thinking about the solution", + signature: undefined, + }, + }, + }, + { text: "Here's my answer" }, + ], + }, + ]); + }); + + it("should handle redacted thinking messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Think about this" } as UserChatMessage, + { + role: "thinking", + content: "", + redactedThinking: "redacted-content-bytes", + }, + { role: "assistant", content: "Here's my answer" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Think about this" }] }, + { + role: "assistant", + content: [ + { + reasoningContent: { + redactedContent: expect.any(Uint8Array), + }, + }, + { text: "Here's my answer" }, + ], + }, + ]); + + // Check that the Uint8Array contains the expected bytes + const redactedContent = + converted[1].content?.[0].reasoningContent?.redactedContent; + expect(redactedContent).toBeInstanceOf(Uint8Array); + expect(Buffer.from(redactedContent!).toString()).toBe( + "redacted-content-bytes", + ); + }); + + it("should convert multimodal content correctly", () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: [ + { type: "text", text: "Look at this image:" }, + { + type: "imageUrl", + imageUrl: { + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", + }, + }, + ], + } as UserChatMessage, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { + role: "user", + content: [ + { text: "Look at this image:" }, + { + image: { + format: "jpeg", + source: { + bytes: expect.any(Uint8Array), + }, + }, + }, + ], + }, + ]); + + // Check that the image bytes were processed correctly + const imageBytes = converted[0].content?.[1].image?.source?.bytes; + expect(imageBytes).toBeInstanceOf(Uint8Array); + expect(Buffer.from(imageBytes!).toString("base64")).toBe( + "/9j/4AAQSkZJRg==", + ); + }); + + it("should add cache points for prompt caching when needed", () => { + // Create a test instance with caching behavior enabled + const bedrockWithCaching = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", }); + + // Set caching behavior + bedrockWithCaching.cacheBehavior = { + cacheConversation: true, + cacheSystemMessage: true, + }; + + const messages: ChatMessage[] = [ + { role: "system", content: "You are a helpful assistant" }, + { role: "user", content: "First message" } as UserChatMessage, + { role: "assistant", content: "First response" }, + { role: "user", content: "Second message" } as UserChatMessage, + ]; + + const availableTools = new Set(); + const converted = bedrockWithCaching["_convertMessages"]( + messages, + availableTools, + ); + + // The last two user messages should have cache points + // But we're not testing the system message here since it's handled separately + expect(converted.length).toBe(3); + expect(converted[0].role).toBe("user"); + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( + true, + ); + expect(converted[1].role).toBe("assistant"); + expect(converted[2].role).toBe("user"); + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( + true, + ); + + // Verify that text content includes a cache ID suffix + const userMessageText = converted[0].content?.[0].text; + expect(userMessageText).toMatch(/First message.+/); }); }); }); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 371713905..1c1c61ed3 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,8 +1,10 @@ import { BedrockRuntimeClient, ContentBlock, + ConversationRole, ConverseStreamCommand, ConverseStreamCommandOutput, + ImageFormat, InvokeModelCommand, Message, ToolConfiguration, @@ -14,6 +16,7 @@ import { Chunk, CompletionOptions, LLMOptions, + MessageContent, } from "../../index.js"; import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; @@ -289,8 +292,8 @@ class Bedrock extends BaseLLM { const systemMessage = stripImages( messages.find((m) => m.role === "system")?.content ?? "", ); - const convertedMessages = this._convertMessages(messages); + // Prompt and system message caching settings const shouldCacheSystemMessage = (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || this.completionOptions.promptCaching; @@ -298,9 +301,7 @@ class Bedrock extends BaseLLM { shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching; - const shouldCacheToolsConfig = this.completionOptions.promptCaching; - // Add header for prompt caching if (enablePromptCaching) { this.requestOptions.headers = { ...this.requestOptions.headers, @@ -308,30 +309,37 @@ class Bedrock extends BaseLLM { }; } + // First get tools const supportsTools = (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false; - let toolConfig = - supportsTools && options.tools - ? ({ - tools: options.tools.map((tool) => ({ - toolSpec: { - name: tool.function.name, - description: tool.function.description, - inputSchema: { - json: tool.function.parameters, - }, - }, - })), - } as ToolConfiguration) - : undefined; - - if (toolConfig?.tools && shouldCacheToolsConfig) { - toolConfig.tools.push({ cachePoint: { type: "default" } }); + let toolConfig: undefined | ToolConfiguration = undefined; + const availableTools = new Set(); + if (supportsTools && options.tools && options.tools.length > 0) { + toolConfig = { + tools: options.tools.map((tool) => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters, + }, + }, + })), + } as ToolConfiguration; + const shouldCacheToolsConfig = this.completionOptions.promptCaching; + if (shouldCacheToolsConfig) { + toolConfig.tools!.push({ cachePoint: { type: "default" } }); + } + options.tools.forEach((tool) => { + availableTools.add(tool.function.name); + }); } + const convertedMessages = this._convertMessages(messages, availableTools); + return { modelId: options.model, system: systemMessage @@ -368,167 +376,236 @@ class Bedrock extends BaseLLM { }; } - private _convertMessage( - message: ChatMessage, - addCaching: boolean = false, - ): Message | null { - // Handle system messages explicitly - if (message.role === "system") { - return null; - } + /* + Converts the messages to the format expected by the Bedrock API. + + */ + private _convertMessages( + messages: ChatMessage[], + availableTools: Set, + ): Message[] { + let currentRole: "user" | "assistant" = "user"; + let currentBlocks: ContentBlock[] = []; - const cachePoint = addCaching - ? { cachePoint: { type: "default" } } - : undefined; - - // Tool response handling - if (message.role === "tool") { - return { - role: "user", - content: [ - { - toolResult: { - toolUseId: message.toolCallId, - content: [ - { - text: message.content || "", - }, - ], - }, - }, - ], - }; - } - - // Tool calls handling - if (message.role === "assistant" && message.toolCalls) { - return { - role: "assistant", - content: message.toolCalls.map((toolCall) => ({ - toolUse: { - toolUseId: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - }, - })), - }; - } - - if (message.role === "thinking") { - if (message.redactedThinking) { - const content: ContentBlock.ReasoningContentMember = { - reasoningContent: { - redactedContent: new Uint8Array( - Buffer.from(message.redactedThinking), - ), - }, - }; - return { - role: "assistant", - content: [content], - }; - } else { - const content: ContentBlock.ReasoningContentMember = { - reasoningContent: { - reasoningText: { - text: (message.content as string) || "", - signature: message.signature, - }, - }, - }; - return { - role: "assistant", - content: [content], - }; + const converted: Message[] = []; + const pushCurrentMessage = () => { + if (currentBlocks.length === 0 && converted.length > 1) { + throw new Error( + `Bedrock: no content in ${currentRole} message before conversational turn change`, + ); } - } - - // Standard text message - if (typeof message.content === "string") { - if (addCaching) { - message.content += getSecureID(); + if (currentBlocks.length > 0) { + converted.push({ + role: currentRole, + content: currentBlocks, + }); } - const content: any[] = [{ text: message.content }]; - if (addCaching) { - content.push({ cachePoint: { type: "default" } }); - } - return { - role: message.role, - content, - }; - } + currentBlocks = []; + }; - // Improved multimodal content handling - if (Array.isArray(message.content)) { - const content: any[] = []; + const nonSystemMessages = messages.filter((m) => m.role !== "system"); + const hasAddedToolCallIds = new Set(); - // Process all parts first - message.content.forEach((part) => { - if (part.type === "text") { - if (addCaching) { - part.text += getSecureID(); + for (let idx = 0; idx < nonSystemMessages.length; idx++) { + const message = nonSystemMessages[idx]; + + if (message.role === "user" || message.role === "tool") { + // Detect conversational turn change + if (currentRole !== ConversationRole.USER) { + pushCurrentMessage(); + currentRole = ConversationRole.USER; + } + + // USER messages: + // Non-empty user message content is converted to "text" and "image" blocks + // If ANY user message part is cached, we add a single cache point block when we push the message + if (message.role === "user") { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { + currentBlocks.push( + ...this._convertMessageContentToBlocks(trimmedContent), + ); } - content.push({ text: part.text }); + } + // TOOL messages: + // Tool messages are represented by "toolResult" blocks + // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig) + // If it doesn't, we convert it to a text block + else if (message.role === "tool") { + const trimmedContent = message.content.trim() || "No tool output"; + if (hasAddedToolCallIds.has(message.toolCallId)) { + currentBlocks.push({ + toolResult: { + toolUseId: message.toolCallId, + content: [ + { + text: trimmedContent, + }, + ], + }, + }); + } else { + currentBlocks.push({ + text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`, + }); + } + } + } else if (message.role === "assistant" || message.role === "thinking") { + // Detect conversational turn change + if (currentRole !== ConversationRole.ASSISTANT) { + pushCurrentMessage(); + currentRole = ConversationRole.ASSISTANT; + } + + // ASSISTANT messages: + // Non-empty assistant message content is converted to "text" and "image" blocks + if (message.role === "assistant") { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { + currentBlocks.push( + ...this._convertMessageContentToBlocks(trimmedContent), + ); + } + // TOOL CALLS: + // Tool calls are represented by "toolUse" blocks + // Each tool call must have an id and a function name + // The function name must match one of the available tools + // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools) + if (message.toolCalls) { + for (const toolCall of message.toolCalls) { + if (toolCall.id && toolCall.function?.name) { + if (availableTools.has(toolCall.function.name)) { + currentBlocks.push({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function.name, + input: safeParseToolCallArgs(toolCall), + }, + }); + hasAddedToolCallIds.add(toolCall.id); + } else { + const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; + currentBlocks.push({ + text: toolCallText, + }); + } + } else { + console.warn( + `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, + ); + continue; + } + } + } + } else if (message.role === "thinking") { + // THINKING: + // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content + if (message.redactedThinking) { + const block: ContentBlock.ReasoningContentMember = { + reasoningContent: { + redactedContent: new Uint8Array( + Buffer.from(message.redactedThinking), + ), + }, + }; + currentBlocks.push(block); + } else { + const block: ContentBlock.ReasoningContentMember = { + reasoningContent: { + reasoningText: { + text: (message.content as string) || "", + signature: message.signature, + }, + }, + }; + currentBlocks.push(block); + } + } + } + } + if (currentBlocks.length > 0) { + pushCurrentMessage(); + } + + // If caching is enabled, we add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + if (this.cacheBehavior?.cacheConversation) { + this._addCachingToLastTwoUserMessages(converted); + } + + return converted; + } + + private _addCachingToLastTwoUserMessages(converted: Message[]) { + let numCached = 0; + for (let i = converted.length - 1; i >= 0; i--) { + const message = converted[i]; + if (message.role === "user") { + message.content?.forEach((block) => { + if (block.text) { + block.text += getSecureID(); + } + }); + message.content?.push({ cachePoint: { type: "default" } }); + numCached++; + } + if (numCached === 2) { + break; + } + } + } + + // Converts Continue message content (string/parts) to Bedrock ContentBlock format. + // Unsupported/problematic image formats are skipped with a warning. + private _convertMessageContentToBlocks( + content: MessageContent, + ): ContentBlock[] { + const blocks: ContentBlock[] = []; + if (typeof content === "string") { + blocks.push({ text: content }); + } else { + for (const part of content) { + if (part.type === "text") { + blocks.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { try { const [mimeType, base64Data] = part.imageUrl.url.split(","); const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; - content.push({ - image: { - format, - source: { - bytes: Buffer.from(base64Data, "base64"), + if ( + format === ImageFormat.JPEG || + format === ImageFormat.PNG || + format === ImageFormat.WEBP || + format === ImageFormat.GIF + ) { + blocks.push({ + image: { + format, + source: { + bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), + }, }, - }, - }); + }); + } else { + console.warn( + `Bedrock: skipping unsupported image part format: ${format}`, + part, + ); + } } catch (error) { - console.warn(`Failed to process image: ${error}`); + console.warn("Bedrock: failed to process image part", error, part); } } - }); - - // Add cache point as a separate block at the end if needed - if (addCaching && content.length > 0) { - content.push({ cachePoint: { type: "default" } }); } - - return { - role: message.role, - content, - } as Message; } - return null; - } - - private _convertMessages(messages: ChatMessage[]): any[] { - const filteredmessages = messages.filter( - (m) => m.role !== "system" && !!m.content, - ); - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1) - .slice(-2); - - const converted = filteredmessages - .map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); - - try { - return this._convertMessage(message, addCaching); - } catch (error) { - console.error(`Failed to convert message: ${error}`); - return null; - } - }) - .filter(Boolean); - - return converted; + return blocks; } private async _getCredentials() { diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 81495c269..e45828c40 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -8,7 +8,7 @@ import { LLMOptions, } from "../.."; import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index c005a5f92..f017f24fd 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -327,27 +327,36 @@ export const getApplicableRules = ( export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, - rules, + availableRules, contextItems, rulePolicies = {}, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; - rules: RuleWithSource[]; + availableRules: RuleWithSource[]; contextItems: ContextItemWithId[]; rulePolicies?: RulePolicies; -}) => { - const applicableRules = getApplicableRules( +}): { + systemMessage: string; + appliedRules: RuleWithSource[]; +} => { + const appliedRules = getApplicableRules( userMessage, - rules, + availableRules, contextItems, rulePolicies, ); let systemMessage = baseSystemMessage ?? ""; - for (const rule of applicableRules) { - systemMessage += `\n\n${rule.rule}`; + for (const rule of appliedRules) { + if (systemMessage) { + systemMessage += "\n\n"; + } + systemMessage += rule.rule; } - return systemMessage; + return { + systemMessage, + appliedRules, + }; }; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 5f6ffbce8..c74b6c564 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -179,7 +179,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, deepseek: (model) => { - if (model !== "deepseek-reasoner") { + // https://api-docs.deepseek.com/quick_start/pricing + // https://api-docs.deepseek.com/guides/function_calling + if (model === "deepseek-reasoner" || model === "deepseek-chat") { return true; } diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 00878dfeb..a7b2ecd61 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -13,6 +13,7 @@ export enum BuiltInToolNames { CreateRuleBlock = "builtin_create_rule_block", RequestRule = "builtin_request_rule", FetchUrlContent = "builtin_fetch_url_content", + CodebaseTool = "builtin_codebase", // excluded from allTools for now ViewRepoMap = "builtin_view_repo_map", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 40dd7abe2..0b81cbae5 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,8 +1,10 @@ import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; +import { DataLogger } from "../data/log"; import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; +import { codebaseToolImpl } from "./implementations/codebaseTool"; import { createNewFileImpl } from "./implementations/createNewFile"; import { createRuleBlockImpl } from "./implementations/createRuleBlock"; import { fetchUrlContentImpl } from "./implementations/fetchUrlContent"; @@ -164,11 +166,33 @@ async function callBuiltInTool( return await createRuleBlockImpl(args, extras); case BuiltInToolNames.RequestRule: return await requestRuleImpl(args, extras); + case BuiltInToolNames.CodebaseTool: + return await codebaseToolImpl(args, extras); default: throw new Error(`Tool "${functionName}" not found`); } } +function logToolUsage( + toolCall: ToolCall, + args: Record, + contextItems: ContextItem[], + success: boolean, +) { + console.log(toolCall.function.arguments); + void DataLogger.getInstance().logDevData({ + name: "toolUsage", + data: { + toolCallId: toolCall.id, + functionName: toolCall.function.name, + functionArgs: toolCall.function.arguments, + toolCallArgs: args, + output: contextItems, + succeeded: success, + }, + }); +} + // Handles calls for core/non-client tools // Returns an error context item if the tool call fails // Note: Edit tool is handled on client @@ -190,6 +214,7 @@ export async function callTool( item.icon = tool.faviconUrl; }); } + logToolUsage(toolCall, args, contextItems, true); return { contextItems, errorMessage: undefined, @@ -199,6 +224,7 @@ export async function callTool( if (e instanceof Error) { errorMessage = e.message; } + logToolUsage(toolCall, {}, [], false); return { contextItems: [], errorMessage, diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts new file mode 100644 index 000000000..fffe51e02 --- /dev/null +++ b/core/tools/definitions/codebaseTool.ts @@ -0,0 +1,29 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const codebaseTool: Tool = { + type: "function", + displayTitle: "Codebase Search", + wouldLikeTo: "search the codebase for: {{{ query }}}", + isCurrently: "searching the codebase for: {{{ query }}}", + hasAlready: "searched the codebase for: {{{ query }}}", + readonly: true, + isInstant: false, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.CodebaseTool, + description: + "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.", + parameters: { + type: "object", + required: ["query"], + properties: { + query: { + type: "string", + description: + "Natural language description of what you're looking for in the codebase (e.g., 'authentication logic', 'database connection setup', 'error handling')", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 53e18cd43..235833d1f 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,5 +1,5 @@ import { Tool } from "../.."; -import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages"; +import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export interface EditToolArgs { diff --git a/core/tools/implementations/codebaseTool.ts b/core/tools/implementations/codebaseTool.ts new file mode 100644 index 000000000..46b06a8c6 --- /dev/null +++ b/core/tools/implementations/codebaseTool.ts @@ -0,0 +1,61 @@ +import { ToolImpl } from "."; +import { RangeInFile } from "../.."; +import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval"; + +export const codebaseToolImpl: ToolImpl = async (args, extras) => { + if (!args.query || args.query.trim() === "") { + return [ + { + name: "Error", + description: "Codebase search error", + content: "Query parameter is required and cannot be empty.", + }, + ]; + } + + try { + const contextExtras = { + config: extras.config, + fullInput: args.query, + embeddingsProvider: extras.config.selectedModelByRole.embed, + reranker: extras.config.selectedModelByRole.rerank, + llm: extras.llm, + ide: extras.ide, + selectedCode: [] as RangeInFile[], + fetch: extras.fetch, + }; + + // Use the existing retrieval function to get context items + const results = await retrieveContextItemsFromEmbeddings( + contextExtras, + undefined, + undefined, + ); + + // If no results found, return helpful message + if (results.length === 0) { + return [ + { + name: "No Results", + description: "Codebase search", + content: `No relevant code found for query: "${args.query}". This could mean: +- The codebase hasn't been indexed yet +- No code matches the search criteria +- Embeddings provider is not configured + +Try re-indexing the codebase or using a more specific query.`, + }, + ]; + } + + return results; + } catch (error) { + return [ + { + name: "Error", + description: "Codebase search error", + content: `Failed to search codebase: ${error instanceof Error ? error.message : String(error)}`, + }, + ]; + } +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index 2d4f2cb36..54987607b 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { ConfigDependentToolParams, IDE, Tool } from ".."; +import { codebaseTool } from "./definitions/codebaseTool"; import { createNewFileTool } from "./definitions/createNewFile"; import { createRuleBlock } from "./definitions/createRuleBlock"; import { editFileTool } from "./definitions/editFile"; @@ -37,7 +38,12 @@ export const getConfigDependentToolDefinitions = ( ): Tool[] => [ requestRuleTool(params), ...(params.enableExperimentalTools - ? [searchAndReplaceInFileTool, viewRepoMapTool, viewSubdirectoryTool] + ? [ + searchAndReplaceInFileTool, + viewRepoMapTool, + viewSubdirectoryTool, + codebaseTool, + ] : [editFileTool]), ]; diff --git a/core/util/findLast.ts b/core/util/findLast.ts index 9e99fd473..256d6e09d 100644 --- a/core/util/findLast.ts +++ b/core/util/findLast.ts @@ -1,6 +1,6 @@ -export function findLastIndex( - arr: any[], - criterion: (item: any) => boolean, +export function findLastIndex( + arr: T[], + criterion: (item: T) => boolean, ): number { let lastIndex = -1; diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index d1e6a000d..07c1279df 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -192,11 +192,8 @@ tasks { } runIde { - // Open the `manual-testing-sandbox` directory and the specific file on start - args = listOf( - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox", - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt" - ).map { file(it).absolutePath } + val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox" + args = listOf(dir, "$dir/test.kt") } test { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt index 8c046c342..43ae74881 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -5,7 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinueExtensi import com.intellij.openapi.actionSystem.ActionPromoter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import org.jetbrains.annotations.NotNull class ContinueActionPromote : ActionPromoter { @@ -13,7 +13,7 @@ class ContinueActionPromote : ActionPromoter { override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? { // For autocomplete actions if (actions.any { it is AcceptAutocompleteAction }) { - val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) + val settings = service() if (settings.continueState.showIDECompletionSideBySide) { return actions.filterIsInstance() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt index 1bd31c463..654b96483 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt @@ -1,7 +1,7 @@ package com.github.continuedev.continueintellijextension.actions import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowManager @@ -28,12 +28,5 @@ fun focusContinueInput(project: Project?) { continuePluginService.ideProtocolClient?.sendHighlightedCode() } -fun getPluginService(project: Project?): ContinuePluginService? { - if (project == null) { - return null - } - return ServiceManager.getService( - project, - ContinuePluginService::class.java - ) -} \ No newline at end of file +fun getPluginService(project: Project?): ContinuePluginService? = + project?.service() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt index e8d3d0788..7fee29ee3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt @@ -1,9 +1,7 @@ package com.github.continuedev.continueintellijextension.activities import com.intellij.openapi.Disposable -import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service -import com.intellij.openapi.project.Project /** * The service is a parent disposable that represents the entire plugin lifecycle @@ -18,15 +16,4 @@ class ContinuePluginDisposable : Disposable { override fun dispose() { } - companion object { - - fun getInstance(): ContinuePluginDisposable { - return ApplicationManager.getApplication().getService(ContinuePluginDisposable::class.java) - } - - fun getInstance(project: Project): ContinuePluginDisposable { - return project.getService(ContinuePluginDisposable::class.java) - } - - } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index d4a9d2201..3aaeef5ed 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -14,7 +14,6 @@ import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.keymap.KeymapManager @@ -122,14 +121,10 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { private fun initializePlugin(project: Project) { val coroutineScope = CoroutineScope(Dispatchers.IO) - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) + val continuePluginService = project.service() coroutineScope.launch { - val settings = - ServiceManager.getService(ContinueExtensionSettings::class.java) + val settings = service() if (!settings.continueState.shownWelcomeDialog) { settings.continueState.shownWelcomeDialog = true // Open tutorial file @@ -270,7 +265,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { EditorFactory.getInstance().eventMulticaster.addSelectionListener( listener, - ContinuePluginDisposable.getInstance(project) + project.service() ) val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 17397f1c8..f4c3fd67f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -7,7 +7,6 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.application.* import com.intellij.openapi.components.Service -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.InlayProperties @@ -64,8 +63,7 @@ class AutocompleteService(private val project: Project) { var lastChangeWasPartialAccept = false fun triggerCompletion(editor: Editor) { - val settings = - ServiceManager.getService(ContinueExtensionSettings::class.java) + val settings = service() if (!settings.continueState.enableTabAutocomplete) { return } @@ -183,7 +181,7 @@ class AutocompleteService(private val project: Project) { } if (isInjectedFile(editor)) return // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled - if (shouldSkipRender(ServiceManager.getService(ContinueExtensionSettings::class.java))) { + if (shouldSkipRender()) { return } @@ -230,9 +228,10 @@ class AutocompleteService(private val project: Project) { } } - private fun shouldSkipRender(settings: ContinueExtensionSettings) = - !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() - + private fun shouldSkipRender(): Boolean { + val settings = service() + return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() + } private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt index 9eba3ce5d..3997f220c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt @@ -26,7 +26,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), private val animatedIcon = AnimatedIcon.Default() init { - Disposer.register(ContinuePluginDisposable.getInstance(project), this) + Disposer.register(project.service(), this) updateIcon() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index 5084b4201..28b648d4a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -10,6 +10,7 @@ import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import kotlinx.coroutines.suspendCancellableCoroutine @@ -201,7 +202,7 @@ class ApplyToFileHandler( if (EditorUtils.editorFileExist(params.filepath)) EditorUtils.getOrOpenEditor(project, params.filepath) else EditorUtils.getEditorByCreateFile(project, params.filepath) - val diffStreamService = project.getService(DiffStreamService::class.java) + val diffStreamService = project.service() val handler = ApplyToFileHandler( project, continuePluginService, ide, params, editorUtils, diffStreamService diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt index 417fbb8d4..c0eeec508 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt @@ -9,7 +9,7 @@ import com.intellij.diff.contents.DiffContent import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project @@ -18,7 +18,6 @@ import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import java.awt.Toolkit import java.io.File -import java.net.URI import java.nio.file.Paths import javax.swing.Action import javax.swing.JComponent @@ -89,11 +88,7 @@ class DiffManager(private val project: Project) : DumbAware { FileDocumentManager.getInstance().saveDocument(document) // Notify server of acceptance - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) - continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex) + project.service().ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex) // Clean up state cleanUpFile(file) @@ -102,10 +97,7 @@ class DiffManager(private val project: Project) : DumbAware { fun rejectDiff(file2: String?) { val file = (file2 ?: lastFile2) ?: return val diffInfo = diffInfoMap[file] ?: return - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) + val continuePluginService = project.service() continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex) continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex) continuePluginService.coreMessenger?.request("cancelApply", null, null) {} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index ddbb5f738..c79b6c9f0 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.activities.showTutorial import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.protocol.* import com.github.continuedev.continueintellijextension.services.* import com.github.continuedev.continueintellijextension.utils.* @@ -46,7 +47,7 @@ class IdeProtocolClient( init { // Setup config.json / config.ts save listeners VirtualFileManager.getInstance().addAsyncFileListener( - AsyncFileSaveListener(continuePluginService), ContinuePluginDisposable.getInstance(project) + AsyncFileSaveListener(continuePluginService), project.service() ) } @@ -67,8 +68,7 @@ class IdeProtocolClient( } "jetbrains/isOSREnabled" -> { - val isOSREnabled = - ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = service().continueState.enableOSR respond(isOSREnabled) } @@ -463,8 +463,10 @@ class IdeProtocolClient( println("Unknown message type: $messageType") } } - } catch (error: Exception) { - ide.showToast(ToastType.ERROR, " Error handling message of type $messageType: $error") + } catch (exception: Exception) { + val exceptionMessage = "Error handling message of type $messageType: $exception" + service().report(exception, exceptionMessage) + ide.showToast(ToastType.ERROR, exceptionMessage) } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 9ceca69f3..4feec68da 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -1,9 +1,9 @@ package com.github.continuedev.continueintellijextension.`continue` import com.github.continuedev.continueintellijextension.* -import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath import com.github.continuedev.continueintellijextension.constants.ContinueConstants -import com.github.continuedev.continueintellijextension.`continue`.GitService +import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.* @@ -11,7 +11,6 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.ide.BrowserUtil -import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity import com.intellij.notification.NotificationAction @@ -19,6 +18,7 @@ import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.extensions.PluginId @@ -38,9 +38,7 @@ import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.InputStreamReader -import java.net.URI import java.nio.charset.Charset -import java.nio.file.Paths class IntelliJIDE( private val project: Project, @@ -297,23 +295,26 @@ class IntelliJIDE( continuePluginService.diffManager?.showDiff(filepath, newContents, stepIndex) } - override suspend fun getOpenFiles(): List { - val fileEditorManager = FileEditorManager.getInstance(project) - return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList() - } - - override suspend fun getCurrentFile(): Map? { - val fileEditorManager = FileEditorManager.getInstance(project) - val editor = fileEditorManager.selectedTextEditor - val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } - return virtualFile?.toUriOrNull()?.let { - mapOf( - "path" to it, - "contents" to editor.document.text, - "isUntitled" to false - ) + override suspend fun getOpenFiles(): List = + withContext(Dispatchers.EDT) { + FileEditorManager.getInstance(project).openFiles + .mapNotNull { it.toUriOrNull() } + .toList() + } + + override suspend fun getCurrentFile(): Map? = + withContext(Dispatchers.EDT) { + val fileEditorManager = FileEditorManager.getInstance(project) + val document = fileEditorManager.selectedTextEditor?.document + val virtualFile = document?.let { FileDocumentManager.getInstance().getFile(it) } + virtualFile?.toUriOrNull()?.let { + mapOf( + "path" to it, + "contents" to document.text, + "isUntitled" to false + ) + } } - } override suspend fun getPinnedFiles(): List { // Returning open files for now as per existing code @@ -344,11 +345,10 @@ class IntelliJIDE( command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout return results.split("\n") - } catch (e: Exception) { - showToast( - ToastType.ERROR, - "Error executing ripgrep: ${e.message}" - ) + } catch (exception: Exception) { + val message = "Error executing ripgrep: ${exception.message}" + service().report(exception, message) + showToast(ToastType.ERROR, message) return emptyList() } } else { @@ -386,11 +386,10 @@ class IntelliJIDE( command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout - } catch (e: Exception) { - showToast( - ToastType.ERROR, - "Error executing ripgrep: ${e.message}" - ) + } catch (exception: Exception) { + val message = "Error executing ripgrep: ${exception.message}" + service().report(exception, message) + showToast(ToastType.ERROR, message) return "Error: Unable to execute ripgrep command." } } else { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index d764e58ef..52abfe00c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -7,7 +7,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.undo.UndoManager -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.RangeHighlighter @@ -42,7 +42,6 @@ class DiffStreamHandler( private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false private val unfinishedHighlighters: MutableList = mutableListOf() - private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) @@ -62,10 +61,10 @@ class DiffStreamHandler( numDiffs = diffBlocks.size, filepath = virtualFile?.url, fileContent = "not implemented", - toolCallId = toolCallId?.toString() + toolCallId = toolCallId ) - continuePluginService.sendToWebview("updateApplyState", payload) + project.service().sendToWebview("updateApplyState", payload) } fun acceptAll() { @@ -102,7 +101,7 @@ class DiffStreamHandler( isRunning = true sendUpdate(ApplyStateStatus.STREAMING) - continuePluginService.coreMessenger?.request( + project.service().coreMessenger?.request( "streamDiffLines", StreamDiffLinesPayload( input = input, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt new file mode 100644 index 000000000..b1fdae571 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt @@ -0,0 +1,50 @@ +package com.github.continuedev.continueintellijextension.error + +import com.intellij.ide.plugins.PluginManagerCore +import com.intellij.openapi.application.ApplicationInfo +import com.intellij.openapi.components.Service +import com.intellij.openapi.diagnostic.Attachment +import com.intellij.openapi.diagnostic.Logger +import com.intellij.openapi.extensions.PluginId +import com.intellij.ui.jcef.JBCefApp +import io.sentry.Hint +import io.sentry.Sentry +import io.sentry.SentryEvent +import io.sentry.protocol.Message + +private typealias SentryAttachment = io.sentry.Attachment + +@Service +class ContinueErrorService { + private val log = Logger.getInstance(ContinueErrorService::class.java) + + init { + Sentry.init { config -> + config.dsn = SENTRY_DSN + config.isSendDefaultPii = false + config.setTag("ide_version", ApplicationInfo.getInstance().build.asString()) + config.setTag("jcef_supported", JBCefApp.isSupported().toString()) + config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version) + } + } + + fun report( + throwable: Throwable, + message: String? = null, + attachments: List? = null + ) { + val sentryEvent = SentryEvent() + sentryEvent.throwable = throwable + sentryEvent.message = Message().apply { this.message = message } + val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) }) + Sentry.captureEvent(sentryEvent, hint) + log.warn("Problem sent to Sentry: $message", throwable) + } + + private companion object { + private const val PLUGIN_ID = "com.github.continuedev.continueintellijextension" + private const val SENTRY_DSN = + "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt index 26a2960e1..3f30c17a8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt @@ -1,29 +1,16 @@ package com.github.continuedev.continueintellijextension.error import com.intellij.diagnostic.IdeaReportingEvent -import com.intellij.openapi.application.ApplicationInfo +import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.ErrorReportSubmitter import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.SubmittedReportInfo import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus -import com.intellij.ui.jcef.JBCefApp import com.intellij.util.Consumer -import io.sentry.Sentry -import io.sentry.SentryEvent -import io.sentry.protocol.Message import java.awt.Component class ContinueErrorSubmitter : ErrorReportSubmitter() { - init { - Sentry.init { config -> - config.dsn = SENTRY_DSN - config.isSendDefaultPii = false - config.setTag("ide_version", ApplicationInfo.getInstance().build.asString()) - config.setTag("jcef_supported", JBCefApp.isSupported().toString()) - } - } - override fun getReportActionText() = "Report to Continue" @@ -34,12 +21,13 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { consumer: Consumer ): Boolean { try { - val event = events.filterIsInstance().firstOrNull() ?: return false - val sentryEvent = SentryEvent() - sentryEvent.throwable = event.data.throwable - sentryEvent.message = Message().apply { message = additionalInfo } - sentryEvent.setTag("plugin_version", event.plugin?.version) - Sentry.captureEvent(sentryEvent) + val event = events.filterIsInstance() + .firstOrNull() ?: return false + service().report( + throwable = event.data.throwable, + message = additionalInfo ?: event.data.message, + attachments = event.data.allAttachments + ) } catch (_: Exception) { consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED)) return false @@ -48,8 +36,4 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { return true } - private companion object { - private const val SENTRY_DSN = "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" - } - } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 908bf3f8d..4e4117985 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -111,7 +111,7 @@ open class ContinueExtensionSettings : PersistentStateComponent() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 43a468cf7..7fd13e177 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -9,30 +9,21 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser +import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* import com.intellij.ui.jcef.JBCefClient.Properties -import com.intellij.util.application import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter class ContinueBrowser(val project: Project, url: String) { - private fun registerAppSchemeHandler() { - CefApp.getInstance().registerSchemeHandlerFactory( - "http", - "continue", - CustomSchemeHandlerFactory() - ) - } val browser: JBCefBrowser - val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java) - init { - val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = service().continueState.enableOSR this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { // To avoid using System.setProperty to affect other plugins, @@ -43,7 +34,7 @@ class ContinueBrowser(val project: Project, url: String) { } registerAppSchemeHandler() - Disposer.register(ContinuePluginDisposable.getInstance(project), browser) + Disposer.register(project.service(), browser) // Listen for events sent from browser val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!) @@ -60,7 +51,7 @@ class ContinueBrowser(val project: Project, url: String) { } if (PASS_THROUGH_TO_CORE.contains(messageType)) { - continuePluginService.coreMessenger?.request(messageType, data, messageId, respond) + project.service().coreMessenger?.request(messageType, data, messageId, respond) return@addHandler null } @@ -75,7 +66,7 @@ class ContinueBrowser(val project: Project, url: String) { } if (msg != null) { - continuePluginService.ideProtocolClient?.handleMessage(msg, respondToWebview) + project.service().ideProtocolClient?.handleMessage(msg, respondToWebview) } null @@ -99,7 +90,7 @@ class ContinueBrowser(val project: Project, url: String) { // Load the url only after the protocolClient is initialized, // otherwise some messages will be lost, which are some configurations when the page is loaded. // Moreover, we should add LoadHandler before loading the url. - continuePluginService.onProtocolClientInitialized { + project.service().onProtocolClientInitialized { browser.loadURL(url) } @@ -138,6 +129,14 @@ class ContinueBrowser(val project: Project, url: String) { } } + private fun registerAppSchemeHandler() { + CefApp.getInstance().registerSchemeHandlerFactory( + "http", + "continue", + CustomSchemeHandlerFactory() + ) + } + private fun buildJavaScript(jsonData: String): String { return """window.postMessage($jsonData, "*");""" } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index d0d44655c..492356ed3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -3,13 +3,13 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory -import javax.swing.* +import javax.swing.JComponent const val JS_QUERY_POOL_SIZE = "200" @@ -52,9 +52,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl val browser = ContinueBrowser(project, url) - val continuePluginService = - ServiceManager.getService(project, ContinuePluginService::class.java) - continuePluginService.continuePluginWindow = this + project.service().continuePluginWindow = this browser } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index a0f195f07..be6120fc1 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.52", + "version": "1.1.54", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.52", + "version": "1.1.54", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index ba7a88c27..cf8b8f679 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.53", + "version": "1.1.54", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index a19b56068..252d19332 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -2,6 +2,9 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../redux/slices/sessionSlice"; import { getMetaKeyLabel } from "../util"; import { ToolTip } from "./gui/Tooltip"; @@ -20,8 +23,21 @@ export default function AcceptRejectAllButtons({ (state) => state.status === "done", ); const ideMessenger = useContext(IdeMessengerContext); - + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, + ); + const dispatch = useAppDispatch(); async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { + if ( + status === "rejectDiff" && + currentToolCallApplyState?.status === "done" + ) { + dispatch( + cancelToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); + } for (const { filepath = "", streamId } of pendingApplyStates) { ideMessenger.post(status, { filepath, diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 0dfbcd493..88d5a5c65 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -9,10 +9,6 @@ import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; -import { - selectCurrentToolCall, - selectCurrentToolCallApplyState, -} from "../../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice"; import { exitEdit } from "../../redux/thunks/edit"; @@ -53,20 +49,12 @@ function InputToolbar(props: InputToolbarProps) { const useActiveFile = useAppSelector(selectUseActiveFile); const isInEdit = useAppSelector((store) => store.session.isInEdit); const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); - const toolCallState = useAppSelector(selectCurrentToolCall); - const currentToolCallApplyState = useAppSelector( - selectCurrentToolCallApplyState, - ); const hasReasoningEnabled = useAppSelector( (store) => store.session.hasReasoningEnabled, ); const isEnterDisabled = - props.disabled || - (isInEdit && codeToEdit.length === 0) || - toolCallState?.status === "generated" || - (currentToolCallApplyState && - currentToolCallApplyState.status !== "closed"); + props.disabled || (isInEdit && codeToEdit.length === 0); const toolsSupported = defaultModel && modelSupportsTools(defaultModel); diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 02027865e..510366448 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -2,8 +2,8 @@ import { useEffect } from "react"; import { useSelector } from "react-redux"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; import { isJetBrains } from "../../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; @@ -50,7 +50,11 @@ export function LumpToolbar() { } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { event.preventDefault(); event.stopPropagation(); - void dispatch(cancelCurrentToolCall()); + void dispatch( + cancelToolCall({ + toolCallId: toolCallState.toolCallId, + }), + ); } }; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx index 365898dce..3cb6acc2d 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx @@ -1,7 +1,8 @@ import styled from "styled-components"; -import { useAppDispatch } from "../../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; import { getAltKeyLabel, getFontSize, @@ -27,6 +28,7 @@ const StopButton = styled.div` export function PendingToolCallToolbar() { const dispatch = useAppDispatch(); const jetbrains = isJetBrains(); + const currentToolCall = useAppSelector(selectCurrentToolCall); return ( @@ -37,7 +39,17 @@ export function PendingToolCallToolbar() {
dispatch(cancelCurrentToolCall())} + onClick={ + currentToolCall + ? () => { + dispatch( + cancelToolCall({ + toolCallId: currentToolCall.toolCallId, + }), + ); + } + : undefined + } data-testid="reject-tool-call-button" > {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 1097805d2..761973428 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -10,7 +10,7 @@ import { DEFAULT_AGENT_SYSTEM_MESSAGE_URL, DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, -} from "core/llm/constructMessages"; +} from "core/llm/defaultSystemMessages"; import { useContext, useMemo } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts index 15ac8e856..0f6f0c0e4 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts @@ -37,6 +37,7 @@ function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] { contextRequests.push({ provider: attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!, + query: attrs.query, }); return child.attrs?.renderInlineAs ?? child.attrs?.label; diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 73317d20e..4b344ecea 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -123,40 +123,35 @@ export function ContextItemsPeekItem({ return (
openContextItem(contextItem, ideMessenger)} - 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" + 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" data-testid="context-items-peek-item" > -
- {getContextItemIcon()} -
-
- {contextItem.name} -
-
{ - if (contextItem.uri?.value) { - e.stopPropagation(); - ideMessenger.post("openUrl", contextItem.uri.value); - } else { - console.error("Couldn't open url", contextItem.uri); - } - } - : undefined - } - > - {contextItem.uri?.type === "file" - ? getUriPathBasename(contextItem.description) - : contextItem.description} -
-
- + {getContextItemIcon()} + + {contextItem.name} + +
{ + if (contextItem.uri?.value) { + e.stopPropagation(); + ideMessenger.post("openUrl", contextItem.uri.value); + } else { + console.error("Couldn't open url", contextItem.uri); + } + } + : undefined + } + > + + {contextItem.uri?.type === "file" + ? getUriPathBasename(contextItem.description) + : contextItem.description} + {isUrl && ( - + )}
diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 693359a97..246e92ce6 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -268,7 +268,6 @@ function ParallelListeners() { currentToolCallApplyState.streamId === state.streamId ) { if (state.status === "done" && autoAcceptEditToolDiffs) { - console.log("AUTO ACCEPTED"); ideMessenger.post("acceptDiff", { streamId: state.streamId, filepath: state.filepath, @@ -281,6 +280,11 @@ function ParallelListeners() { toolCallId: currentToolCallApplyState.toolCallId!, }), ); + void dispatch( + streamResponseAfterToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); } // const output: ContextItem = { // name: "Edit tool output", @@ -288,11 +292,6 @@ function ParallelListeners() { // description: "", // }; // dispatch(setToolCallOutput([])); - void dispatch( - streamResponseAfterToolCall({ - toolCallId: currentToolCallApplyState.toolCallId!, - }), - ); } } } diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts new file mode 100644 index 000000000..b3e132cad --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -0,0 +1,27 @@ +import { ContextItem, ContextItemWithId, ToolCallState } from "core"; + +export function toolCallStateToContextItems( + toolCallState: ToolCallState | undefined, +): ContextItemWithId[] { + if (!toolCallState) { + return []; + } + return ( + toolCallState.output?.map((ctxItem) => + toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId), + ) ?? [] + ); +} + +export function toolCallCtxItemToCtxItemWithId( + ctxItem: ContextItem, + toolCallId: string, +): ContextItemWithId { + return { + ...ctxItem, + id: { + providerTitle: "toolCall", + itemId: toolCallId, + }, + }; +} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 9c91cce73..7c2fd4a82 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -20,13 +20,20 @@ import { SessionMetadata, } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; -import { renderChatMessage } from "core/util/messageContent"; +import { + renderChatMessage, + renderContextItems, +} from "core/util/messageContent"; import { findUriInDirs, getUriPathBasename } from "core/util/uri"; +import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; +import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; -import { findCurrentToolCall, findToolCall } from "../util"; +import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; + +const getIdeMessenger = () => (window as any).ideMessenger; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -105,19 +112,39 @@ export const sessionSlice = createSlice({ curMessage.isGatheringContext = payload; } }, - clearLastEmptyResponse: (state) => { + clearDanglingMessages: (state) => { + // This is used during cancellation + // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing. + // The only thing allowed after the last assistant message that has either content or generated tool calls + // is a user or tool message if (state.history.length < 2) { return; } - const lastMessage = state.history[state.history.length - 1]; + const lastUserOrToolIdx = findLastIndex( + state.history, + (item) => item.message.role === "tool" || item.message.role === "user", + ); - // Only clear in the case of an empty message - if (!lastMessage.message.content.length) { - state.mainEditorContentTrigger = - state.history[state.history.length - 2].editorState; - state.history = state.history.slice(0, -2); - // TODO is this logic correct for tool use conversations? - // Maybe slice at last index of "user" role message? + let validAssistantMessageIdx = -1; + for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) { + const message = state.history[i]; + if ( + message.message.content || + message.toolCallState?.status !== "generating" + ) { + validAssistantMessageIdx = i; + // Cancel any tool calls that are dangling and generated + if (message.toolCallState?.status === "generated") { + message.toolCallState.status = "canceled"; + } + break; + } + } + + if (validAssistantMessageIdx === -1) { + state.history = state.history.slice(0, lastUserOrToolIdx + 1); + } else { + state.history = state.history.slice(0, validAssistantMessageIdx + 1); } }, // Trigger value picked up by editor with isMainInput to set its content @@ -525,6 +552,7 @@ export const sessionSlice = createSlice({ contextItems: ContextItem[]; }>, ) => { + // Update tool call state and corresponding tool output message const toolCallState = findToolCall( state.history, action.payload.toolCallId, @@ -532,6 +560,15 @@ export const sessionSlice = createSlice({ if (toolCallState) { toolCallState.output = action.payload.contextItems; } + const toolItem = findToolOutput(state.history, action.payload.toolCallId); + if (toolItem) { + toolItem.message.content = renderContextItems( + action.payload.contextItems, + ); + toolItem.contextItems = action.payload.contextItems.map((item) => + toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId), + ); + } }, cancelToolCall: ( state, @@ -677,7 +714,7 @@ export const { setActive, submitEditorAndInitAtIndex, updateHistoryItemAtIndex, - clearLastEmptyResponse, + clearDanglingMessages, setMainEditorContentTrigger, deleteMessage, setIsGatheringContext, diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index 6395a6e32..7c03226ee 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -12,6 +12,7 @@ import { updateToolCallOutput, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { logToolUsage } from "../util"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; export const callCurrentTool = createAsyncThunk( @@ -100,6 +101,8 @@ export const callCurrentTool = createAsyncThunk( ], }), ); + + logToolUsage(toolCallState, false, extra.ideMessenger, output); } else if (output?.length) { dispatch( updateToolCallOutput({ @@ -107,6 +110,8 @@ export const callCurrentTool = createAsyncThunk( contextItems: output, }), ); + + logToolUsage(toolCallState, true, extra.ideMessenger, output); } // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` diff --git a/gui/src/redux/thunks/cancelCurrentToolCall.ts b/gui/src/redux/thunks/cancelCurrentToolCall.ts deleted file mode 100644 index f90d80ff6..000000000 --- a/gui/src/redux/thunks/cancelCurrentToolCall.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; - -export const cancelCurrentToolCall = createAsyncThunk< - void, - undefined, - ThunkApiType ->("chat/cancelTool", async (_, { dispatch, extra, getState }) => { - const state = getState(); - const toolCallState = selectCurrentToolCall(state); - - if (!toolCallState) { - return; - } - - if (toolCallState.status !== "generated") { - return; - } - - const { toolCallId } = toolCallState; - dispatch( - cancelToolCall({ - toolCallId, - }), - ); - - dispatch( - updateToolCallOutput({ - toolCallId, - contextItems: [ - { - name: "Tool Cancelled", - description: "Tool Cancelled", - content: - "The tool call was cancelled by the user. Please try something else or request further instructions.", - hidden: true, - }, - ], - }), - ); - const output = await dispatch( - streamResponseAfterToolCall({ - toolCallId, - }), - ); - unwrapResult(output); -}); diff --git a/gui/src/redux/thunks/cancelStream.ts b/gui/src/redux/thunks/cancelStream.ts index 515a02cfc..4cac7e9c7 100644 --- a/gui/src/redux/thunks/cancelStream.ts +++ b/gui/src/redux/thunks/cancelStream.ts @@ -1,7 +1,7 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { abortStream, - clearLastEmptyResponse, + clearDanglingMessages, setInactive, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -12,9 +12,7 @@ export const cancelStream = createAsyncThunk( dispatch(setInactive()); dispatch(abortStream()); - // In the case tool calls were being generated, - // Replace them with - // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box - dispatch(clearLastEmptyResponse()); + // Clear any dangling incomplete tool calls, thinking messages, etc. + dispatch(clearDanglingMessages()); }, ); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 292c973f9..0133a101a 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,5 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, LLMFullCompletionOptions } from "core"; +import { LLMFullCompletionOptions } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { ToCoreProtocol } from "core/protocol"; import { selectActiveTools } from "../selectors/selectActiveTools"; @@ -9,38 +9,40 @@ import { abortStream, addPromptCompletionPair, setActive, + setAppliedRulesAtIndex, setInactive, setToolGenerated, streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { + constructMessages, + getBaseSystemMessage, +} from "../util/constructMessages"; import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< void, { - messages: ChatMessage[]; legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; }, ThunkApiType >( "chat/streamNormalInput", - async ( - { messages, legacySlashCommandData }, - { dispatch, extra, getState }, - ) => { - // Gather state + async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { const state = getState(); const selectedChatModel = selectSelectedChatModel(state); - const streamAborter = state.session.streamAborter; if (!selectedChatModel) { - throw new Error("Default model not defined"); + throw new Error("No chat model selected"); } - let completionOptions: LLMFullCompletionOptions = {}; + // Get tools const activeTools = selectActiveTools(state); const toolsSupported = modelSupportsTools(selectedChatModel); + + // Construct completion options + let completionOptions: LLMFullCompletionOptions = {}; if (toolsSupported && activeTools.length > 0) { completionOptions = { tools: activeTools, @@ -55,20 +57,46 @@ export const streamNormalInput = createAsyncThunk< }; } + // Construct messages (excluding system message) + const baseSystemMessage = getBaseSystemMessage( + state.session.mode, + selectedChatModel, + ); + + const withoutMessageIds = state.session.history.map((item) => { + const { id, ...messageWithoutId } = item.message; + return { ...item, message: messageWithoutId }; + }); + const { messages, appliedRules, appliedRuleIndex } = constructMessages( + withoutMessageIds, + baseSystemMessage, + state.config.config.rules, + state.ui.ruleSettings, + ); + + // TODO parallel tool calls will cause issues with this + // because there will be multiple tool messages, so which one should have applied rules? + dispatch( + setAppliedRulesAtIndex({ + index: appliedRuleIndex, + appliedRules: appliedRules, + }), + ); + dispatch(setActive()); - // Send request + // Send request and stream response + const streamAborter = state.session.streamAborter; const gen = extra.ideMessenger.llmStreamChat( { completionOptions, title: selectedChatModel.title, - messages, + messages: messages, legacySlashCommandData, }, streamAborter.signal, ); - // Stream response let next = await gen.next(); while (!next.done) { if (!getState().session.isStreaming) { diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 5dc031e56..11763a462 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,15 +1,11 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; -import { constructMessages } from "core/llm/constructMessages"; -import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; +import { InputModifiers } from "core"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; -import { getBaseSystemMessage } from "../../util"; import { selectSelectedChatModel } from "../slices/configSlice"; import { - setAppliedRulesAtIndex, submitEditorAndInitAtIndex, updateHistoryItemAtIndex, } from "../slices/sessionSlice"; @@ -77,7 +73,7 @@ export const streamResponseThunk = createAsyncThunk< .map((item) => item.uri!.value), ...selectedCode.map((rif) => rif.filepath), ]; - dispatch(updateFileSymbolsFromFiles(filesForSymbols)); + void dispatch(updateFileSymbolsFromFiles(filesForSymbols)); dispatch( updateHistoryItemAtIndex({ @@ -93,47 +89,6 @@ export const streamResponseThunk = createAsyncThunk< }), ); - // Get updated history after the update - const updatedHistory = getState().session.history; - - // Determine which rules apply to this message - const userMsg = updatedHistory[inputIndex].message; - const rules = getState().config.config.rules; - const rulePolicies = getState().ui.ruleSettings; - - // Calculate applicable rules once - // We need to check the message type to match what getApplicableRules expects - const applicableRules = getApplicableRules( - userMsg.role === "user" || userMsg.role === "tool" - ? (userMsg as UserChatMessage | ToolResultChatMessage) - : undefined, - rules, - selectedContextItems, - rulePolicies, - ); - - // Store in history for UI display - dispatch( - setAppliedRulesAtIndex({ - index: inputIndex, - appliedRules: applicableRules, - }), - ); - - const messageMode = getState().session.mode; - const baseChatOrAgentSystemMessage = getBaseSystemMessage( - selectedChatModel, - messageMode, - ); - - const messages = constructMessages( - messageMode, - [...updatedHistory], - baseChatOrAgentSystemMessage, - applicableRules, - rulePolicies, - ); - posthog.capture("step run", { step_name: "User Input", params: {}, @@ -150,7 +105,6 @@ export const streamResponseThunk = createAsyncThunk< unwrapResult( await dispatch( streamNormalInput({ - messages, legacySlashCommandData: legacyCommandWithInput ? { command: legacyCommandWithInput.command, diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 3a29491c5..010304557 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,10 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; -import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; -import { getBaseSystemMessage } from "../../util"; -import { selectSelectedChatModel } from "../slices/configSlice"; -import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; +import { streamUpdate } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { findToolCall } from "../util"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; @@ -21,15 +18,8 @@ export const streamResponseAfterToolCall = createAsyncThunk< await dispatch( streamThunkWrapper(async () => { const state = getState(); - const initialHistory = state.session.history; - const selectedChatModel = selectSelectedChatModel(state); - - if (!selectedChatModel) { - throw new Error("No model selected"); - } const toolCallState = findToolCall(state.session.history, toolCallId); - if (!toolCallState) { return; // in cases where edit tool is cancelled mid apply, this will be triggered } @@ -40,41 +30,15 @@ export const streamResponseAfterToolCall = createAsyncThunk< await new Promise((resolve) => setTimeout(resolve, 0)); + // TODO parallel tool calls - dispatch one tool message per tool call const newMessage: ChatMessage = { role: "tool", content: renderContextItems(toolOutput), toolCallId, }; dispatch(streamUpdate([newMessage])); - dispatch( - addContextItemsAtIndex({ - index: initialHistory.length, - contextItems: toolOutput.map((contextItem) => ({ - ...contextItem, - id: { - providerTitle: "toolCall", - itemId: toolCallId, - }, - })), - }), - ); - const updatedHistory = getState().session.history; - const messageMode = getState().session.mode; - - const baseChatOrAgentSystemMessage = getBaseSystemMessage( - selectedChatModel, - messageMode, - ); - - const messages = constructMessages( - messageMode, - [...updatedHistory], - baseChatOrAgentSystemMessage, - state.config.config.rules, - ); - - unwrapResult(await dispatch(streamNormalInput({ messages }))); + unwrapResult(await dispatch(streamNormalInput({}))); }), ); }, diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 2a6eb99b0..9e40f4f06 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -22,7 +22,7 @@ export const streamThunkWrapper = createAsyncThunk< ); } } catch (e) { - dispatch(cancelStream()); + await dispatch(cancelStream()); dispatch(setDialogMessage()); dispatch(setShowDialog(true)); } diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts new file mode 100644 index 000000000..18ab0ed45 --- /dev/null +++ b/gui/src/redux/util/constructMessages.test.ts @@ -0,0 +1,734 @@ +import { + AssistantChatMessage, + ChatHistoryItem, + ChatMessage, + ContextItemWithId, + ModelDescription, + RuleWithSource, + ThinkingChatMessage, + ToolResultChatMessage, + UserChatMessage, +} from "core"; +import { + DEFAULT_AGENT_SYSTEM_MESSAGE, + DEFAULT_CHAT_SYSTEM_MESSAGE, +} from "core/llm/defaultSystemMessages"; +import { renderChatMessage } from "core/util/messageContent"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { + CANCELLED_TOOL_CALL_MESSAGE, + constructMessages, + getBaseSystemMessage, + NO_TOOL_CALL_OUTPUT_MESSAGE, +} from "./constructMessages"; + +// For these tests we will mock the rules to simulate different scenarios +const CONTEXT_RULE: RuleWithSource = { + source: "rules-block", + rule: "CONTEXT_RULE", + description: "CONTEXT_TRIGGER", +}; +const LAST_MESSAGE_RULE: RuleWithSource = { + source: "rules-block", + rule: "LAST_MESSAGE_RULE", + description: "LAST_MESSAGE_TRIGGER", +}; +const NORMAL_RULE: RuleWithSource = { + source: "rules-block", + rule: "Always apply rule", +}; + +vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => { + const original = (await importOriginal()) as any; + return { + ...original, + getSystemMessageWithRules: ({ + baseSystemMessage, + availableRules, + userMessage, + contextItems, + rulePolicies, + }: { + baseSystemMessage: string; + availableRules: RuleWithSource[]; + userMessage?: UserChatMessage | ToolResultChatMessage; + contextItems: ContextItemWithId[]; + rulePolicies?: Record; + }) => { + // Filter rules based on our mock logic + const appliedRules = availableRules.filter((rule) => { + if (rule.rule === LAST_MESSAGE_RULE.rule) { + if (userMessage) { + return renderChatMessage(userMessage).includes( + LAST_MESSAGE_RULE.description!, + ); + } else { + return false; + } + } + if (rule.rule === CONTEXT_RULE.rule) { + return contextItems.some((item) => + item.content.includes(CONTEXT_RULE.description!), + ); + } + return true; + }); + + // Build the system message with applied rules + let systemMessage = baseSystemMessage || ""; + if (appliedRules.length > 0) { + systemMessage += "\n\nRules to follow:\n"; + for (const rule of appliedRules) { + systemMessage += `- ${rule.rule}\n`; + } + } + + return { systemMessage, appliedRules }; + }, + }; +}); + +test("getBaseSystemMessage should return the correct system message based on mode", () => { + const mockModel = { + baseAgentSystemMessage: "Custom Agent System Message", + baseChatSystemMessage: "Custom Chat System Message", + } as ModelDescription; + + // Test agent mode with custom message + expect(getBaseSystemMessage("agent", mockModel)).toBe( + "Custom Agent System Message", + ); + + // Test chat mode with custom message + expect(getBaseSystemMessage("chat", mockModel)).toBe( + "Custom Chat System Message", + ); + + // Test agent mode with default message + expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe( + DEFAULT_AGENT_SYSTEM_MESSAGE, + ); + + // Test chat mode with default message + expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe( + DEFAULT_CHAT_SYSTEM_MESSAGE, + ); +}); + +describe("constructMessages", () => { + // Setup mock data + let mockHistory: ChatHistoryItem[]; + const mockRules: RuleWithSource[] = [ + CONTEXT_RULE, + LAST_MESSAGE_RULE, + NORMAL_RULE, + ]; + + const createContextItem = ( + id: string, + content: string, + ): ContextItemWithId => ({ + id: { + providerTitle: "test-provider", + itemId: id, + }, + content, + name: `Context Item ${id}`, + description: `Description for ${id}`, + }); + + beforeEach(() => { + // Reset mock history before each test + mockHistory = []; + }); + + test("should ignore empty, tool, and system messages that go in", () => { + // Setup history with various message types including ones to be ignored + mockHistory = [ + { + message: { + role: "system", + content: "I should be ignored", + } as ChatMessage, + contextItems: [], + }, + { + message: { + role: "tool", + content: "I should be ignored", + toolCallId: "123", + } as ToolResultChatMessage, + contextItems: [], + }, + { + message: { role: "user", content: "" } as ChatMessage, // Empty message + contextItems: [], + }, + { + message: { role: "user", content: "Valid user message" } as ChatMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should only contain a system message (added by the function) and the valid user message + expect(messages.length).toBe(2); + expect(messages[0].role).toBe("system"); + expect(messages[1].role).toBe("user"); + expect(messages[1].content).toEqual([ + { type: "text", text: "Valid user message" }, + ]); + expect(messages.some((msg) => msg.content === "I should be ignored")).toBe( + false, + ); + }); + + test("should convert user messages to message parts arrays with context items", () => { + const contextItems = [ + createContextItem("1", "Context content 1"), + createContextItem("2", "Context content 2"), + ]; + + mockHistory = [ + { + message: { + role: "user", + content: "User message with context", + } as ChatMessage, + contextItems, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Check that user message was converted to parts array with context items first + expect(messages.length).toBe(2); // System message + user message + expect(messages[1].role).toBe("user"); + + // Check content structure + const content = messages[1].content as any[]; + expect(content.length).toBe(3); // 2 context items + original message + expect(content[0].text).toContain("Context content 1"); + expect(content[1].text).toContain("Context content 2"); + expect(content[2].text).toBe("User message with context"); + }); + + test("should inject thinking messages with no changes", () => { + const thinkingMessage: ThinkingChatMessage = { + role: "thinking", + content: "Thinking process...", + }; + + mockHistory = [ + { + message: thinkingMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system message + thinking message + expect(messages.length).toBe(2); + expect(messages[1].role).toBe("thinking"); + expect(messages[1].content).toBe("Thinking process..."); + }); + + test("should inject assistant messages with no changes", () => { + const assistantMessage: AssistantChatMessage = { + role: "assistant", + content: "Assistant response", + }; + + mockHistory = [ + { + message: assistantMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system message + assistant message + expect(messages.length).toBe(2); + expect(messages[1].role).toBe("assistant"); + expect(messages[1].content).toBe("Assistant response"); + }); + + test("should follow assistant messages with tool calls by tool messages containing the tool output", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // With tool output + mockHistory = [ + { + message: { + role: "user", + content: "Can you search for something?", + } as UserChatMessage, + contextItems: [], + }, + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: [createContextItem("search-result", "Search result content")], + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have: system + user + assistant + tool messages + expect(messages.length).toBe(4); + expect(messages[2].role).toBe("assistant"); + expect(messages[3].role).toBe("tool"); + const toolMessage = messages[3] as ToolResultChatMessage; + expect(toolMessage.toolCallId).toBe("tool-call-1"); + expect(toolMessage.content).toContain("Search result content"); + }); + + test("should show cancelled message for cancelled tool calls", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // With cancelled tool call + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "canceled", + parsedArgs: { query: "test" }, + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system + assistant + tool message with cancelled message + expect(messages.length).toBe(3); + expect(messages[2].role).toBe("tool"); + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.toolCallId).toBe("tool-call-1"); + expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE); + }); + + test('should show "No tool output" for tool calls without output', () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // With tool call but no output + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "generating", // Not done yet + parsedArgs: { query: "test" }, + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system + assistant + tool message with "No tool output" + expect(messages.length).toBe(3); + expect(messages[2].role).toBe("tool"); + expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); + }); + + test("should start with system message using base message if provided", () => { + mockHistory = [ + { + message: { role: "user", content: "Hello" } as UserChatMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Custom Base System Message", + mockRules, + {}, + ); + + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Custom Base System Message"); + }); + + test("should handle multiple tool calls in a single assistant message", () => { + const assistantWithMultipleToolCalls: AssistantChatMessage = { + role: "assistant", + content: "I will search and check the weather", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + { + id: "tool-call-2", + type: "function", + function: { + name: "weather", + arguments: '{"location": "New York"}', + }, + }, + ], + }; + + // Only the first tool call has output + mockHistory = [ + { + message: assistantWithMultipleToolCalls, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: [createContextItem("search-result", "Search result content")], + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have: system + assistant + 2 tool messages + expect(messages.length).toBe(4); + expect(messages[1].role).toBe("assistant"); + + // First tool message should have output + expect(messages[2].role).toBe("tool"); + expect(messages[3].role).toBe("tool"); + + const toolMessage1 = messages[2] as ToolResultChatMessage; + const toolMessage2 = messages[3] as ToolResultChatMessage; + expect(toolMessage1.toolCallId).toBe("tool-call-1"); + expect(toolMessage1.content).toContain("Search result content"); + + // Second tool message should have "No tool output" + expect(toolMessage2.toolCallId).toBe("tool-call-2"); + expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); + }); + + test("should handle messages with array content", () => { + // User message with array content (including an image) + const userMessageWithArray: UserChatMessage = { + role: "user", + content: [ + { type: "text", text: "Here is some text" }, + { + type: "imageUrl", + imageUrl: { url: "https://example.com/image.jpg" }, + }, + ], + }; + + mockHistory = [ + { + message: userMessageWithArray, + contextItems: [createContextItem("ctx", "Context text")], + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Check the user message content structure + expect(messages.length).toBe(2); + expect(messages[1].role).toBe("user"); + + const content = messages[1].content as any[]; + // Should have context item + original 2 parts + expect(content.length).toBe(3); + expect(content[0].type).toBe("text"); + expect(content[0].text).toContain("Context text"); + expect(content[1].type).toBe("text"); + expect(content[1].text).toBe("Here is some text"); + expect(content[2].type).toBe("imageUrl"); + expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg"); + + // This also verifies that rules are NOT applied if the triggers are not present + expect(appliedRules).toHaveLength(1); + expect(appliedRules).toContainEqual(NORMAL_RULE); + }); + + test("system message should include rules triggered by context items from the last user message forward", () => { + // Create context item that should trigger the CONTEXT_RULE + const triggeringContextItem = createContextItem( + "trigger", + `Some content with ${CONTEXT_RULE.description} in it`, + ); + + mockHistory = [ + // First user message with non-triggering context + { + message: { role: "user", content: "First message" } as UserChatMessage, + contextItems: [createContextItem("normal", "Normal context")], + }, + // Assistant response + { + message: { + role: "assistant", + content: "Assistant response", + } as AssistantChatMessage, + contextItems: [], + }, + // Last user message with triggering context + { + message: { role: "user", content: "Last message" } as UserChatMessage, + contextItems: [triggeringContextItem], + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Verify context rule was applied in the system message + expect(appliedRules).toHaveLength(2); + expect(appliedRules).toContainEqual(NORMAL_RULE); + expect(appliedRules).toContainEqual(CONTEXT_RULE); + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Base System Message"); + expect(messages[0].content).toContain(CONTEXT_RULE.rule); + }); + + test("system message should include rules triggered by tool output after the last user message", () => { + // Create a history with a user message, assistant with tool call, and tool output containing triggering content + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // Tool output containing the trigger for CONTEXT_RULE + const triggeringToolOutput = createContextItem( + "search-result", + `Search result with ${CONTEXT_RULE.description} trigger`, + ); + + mockHistory = [ + { + message: { + role: "user", + content: "Can you search for something?", + } as UserChatMessage, + contextItems: [], + }, + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: [triggeringToolOutput], + }, + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Verify context rule was applied in the system message due to the tool output + expect(appliedRules).toHaveLength(2); + expect(appliedRules).toContainEqual(NORMAL_RULE); + expect(appliedRules).toContainEqual(CONTEXT_RULE); + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Base System Message"); + expect(messages[0].content).toContain(CONTEXT_RULE.rule); + }); + + test("system message should only apply rules triggered by the last user message", () => { + // First user message with trigger for LAST_MESSAGE_RULE + const firstUserMessage = { + role: "user", + content: `This contains ${LAST_MESSAGE_RULE.description}`, + } as UserChatMessage; + + // Last user message without any triggers + const lastUserMessage = { + role: "user", + content: "This is a normal message", + } as UserChatMessage; + + mockHistory = [ + { + message: firstUserMessage, + contextItems: [], + }, + { + message: { + role: "assistant", + content: "First response", + } as AssistantChatMessage, + contextItems: [], + }, + { + message: lastUserMessage, + contextItems: [], + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message + expect(appliedRules).toHaveLength(1); + expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Base System Message"); + expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule); + }); +}); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts new file mode 100644 index 000000000..15f8120db --- /dev/null +++ b/gui/src/redux/util/constructMessages.ts @@ -0,0 +1,173 @@ +import { + ChatHistoryItem, + ChatMessage, + ContextItemWithId, + ModelDescription, + RuleWithSource, + TextMessagePart, + ToolResultChatMessage, + UserChatMessage, +} from "core"; +import { + DEFAULT_AGENT_SYSTEM_MESSAGE, + DEFAULT_CHAT_SYSTEM_MESSAGE, +} from "core/llm/defaultSystemMessages"; +import { chatMessageIsEmpty } from "core/llm/messages"; +import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; +import { RulePolicies } from "core/llm/rules/types"; +import { findLast, findLastIndex } from "core/util/findLast"; +import { + normalizeToMessageParts, + renderContextItems, +} from "core/util/messageContent"; +import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; + +export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; +export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; + +interface MessageWithContextItems { + ctxItems: ContextItemWithId[]; + message: ChatMessage; +} +export function constructMessages( + history: ChatHistoryItem[], + baseSystemMessage: string | undefined, + availableRules: RuleWithSource[], + rulePolicies: RulePolicies, +): { + messages: ChatMessage[]; + appliedRules: RuleWithSource[]; + appliedRuleIndex: number; +} { + const historyCopy = [...history]; + + const msgs: MessageWithContextItems[] = []; + let appliedRuleIndex = -1; + let index = -1; + for (const item of historyCopy) { + index++; + if ( + item.message.role === "system" || + item.message.role === "tool" || + chatMessageIsEmpty(item.message) + ) { + // Tool messages will be re-inserted + continue; + } + + if (item.message.role === "user") { + appliedRuleIndex = index; + // Gather context items for user messages + let content = normalizeToMessageParts(item.message); + + const ctxItemParts = item.contextItems + .map((ctxItem) => { + return { + type: "text", + text: `${ctxItem.content}\n`, + } as TextMessagePart; + }) + .filter((part) => !!part.text.trim()); + + content = [...ctxItemParts, ...content]; + msgs.push({ + ctxItems: item.contextItems, + message: { + ...item.message, + content, + }, + }); + } else if (item.message.role === "thinking") { + msgs.push({ + ctxItems: item.contextItems, + message: item.message, + }); + } else if (item.message.role === "assistant") { + msgs.push({ + ctxItems: item.contextItems, + message: item.message, + }); + + // Add a tool message for each tool call + if (item.message.toolCalls?.length) { + // If the assistant message has tool calls, we need to insert tool messages + for (const toolCall of item.message.toolCalls) { + let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE; + // TODO parallel tool calls: toolCallState only supports one tool call per message for now + if (item.toolCallState?.status === "canceled") { + content = CANCELLED_TOOL_CALL_MESSAGE; + } else if ( + item.toolCallState?.toolCallId === toolCall.id && + item.toolCallState?.output + ) { + content = renderContextItems(item.toolCallState.output); + } + msgs.push({ + ctxItems: toolCallStateToContextItems(item.toolCallState), + message: { + role: "tool", + content, + toolCallId: toolCall.id!, + }, + }); + } + } + } + } + + // Some rules only apply to the last user or tool message + const lastUserOrToolMsg = findLast( + msgs, + (item) => item.message.role === "user" || item.message.role === "tool", + )?.message as UserChatMessage | ToolResultChatMessage; + + // Some rules apply to all context items since the last user message, inclusiv + const lastUserMsgIndex = findLastIndex( + msgs, + (item) => item.message.role === "user", + ); + const itemsBackToLastUserMessage = msgs + .slice(lastUserMsgIndex, msgs.length) + .filter( + (item) => item.message.role === "tool" || item.message.role === "user", + ); + const rulesContextItems = itemsBackToLastUserMessage + .map((item) => item.ctxItems) + .flat(); + + const { systemMessage, appliedRules } = getSystemMessageWithRules({ + baseSystemMessage, + availableRules, + userMessage: lastUserOrToolMsg, + contextItems: rulesContextItems, + rulePolicies, + }); + + if (systemMessage.trim()) { + msgs.unshift({ + ctxItems: [], + message: { + role: "system", + content: systemMessage, + }, + }); + } + + const messages = msgs.map((m) => m.message); + return { + messages, + appliedRules, + appliedRuleIndex, + }; +} + +export function getBaseSystemMessage( + messageMode: string, + model: ModelDescription, +): string { + if (messageMode === "agent") { + return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; + } else { + return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; + } +} diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index eab18ae60..8bf006ba8 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -1,4 +1,7 @@ -import { ToolCallState } from "core"; +import { ContextItem, ToolCallState } from "core"; +import { safeParseToolCallArgs } from "core/tools/parseArgs"; +import { IIdeMessenger } from "../../context/IdeMessenger"; +import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice"; import { RootState } from "../store"; export function findCurrentToolCall( @@ -7,6 +10,7 @@ export function findCurrentToolCall( return chatHistory[chatHistory.length - 1]?.toolCallState; } +// TODO parallel tool calls - find tool call must search within arrays export function findToolCall( chatHistory: RootState["session"]["history"], toolCallId: string, @@ -15,3 +19,32 @@ export function findToolCall( (item) => item.toolCallState?.toolCallId === toolCallId, )?.toolCallState; } + +export function findToolOutput( + chatHistory: RootState["session"]["history"], + toolCallId: string, +): ChatHistoryItemWithMessageId | undefined { + return chatHistory.find( + (item) => + item.message.role === "tool" && item.message.toolCallId === toolCallId, + ); +} + +export function logToolUsage( + toolCallState: ToolCallState, + success: boolean, + messenger: IIdeMessenger, + finalOutput?: ContextItem[], +) { + messenger.post("devdata/log", { + name: "toolUsage", + data: { + toolCallId: toolCallState.toolCallId, + functionName: toolCallState.toolCall?.function?.name, + functionArgs: toolCallState.toolCall?.function?.arguments, + toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), + output: finalOutput || toolCallState.output || [], + succeeded: success, + }, + }); +} diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index dc581b51b..d4cc451f4 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -1,10 +1,4 @@ -import { MessageModes, ModelDescription } from "core"; import { ProfileDescription } from "core/config/ProfileLifecycleManager"; -import { - DEFAULT_AGENT_SYSTEM_MESSAGE, - DEFAULT_CHAT_SYSTEM_MESSAGE, -} from "core/llm/constructMessages"; -import _ from "lodash"; import { KeyboardEvent as ReactKeyboardEvent } from "react"; import { getLocalStorage } from "./localStorage"; @@ -88,52 +82,6 @@ export function isPrerelease() { return false; } -/** - * Updates the values of an object's properties based on the specified paths. - * - * This function creates a deep clone of the provided object and updates its properties - * based on the given path-to-value mappings. If a value in the mapping is a function, - * it will be used to determine the new value for the property. Otherwise, the value itself - * will be set for the property. - * - * @param {Object} old - The original object to be cloned and updated. - * @param {Object} pathToValue - An object where the keys represent the paths to the properties - * to be updated and the values represent the new values or functions - * to determine the new values. - * @returns {Object} A new object with the updated values. - */ -export function updatedObj(old: any, pathToValue: { [key: string]: any }) { - const newObject = _.cloneDeep(old); - - for (const key in pathToValue) { - if (typeof pathToValue[key] === "function") { - _.updateWith(newObject, key, pathToValue[key]); - } else { - _.updateWith(newObject, key, (__) => pathToValue[key]); - } - } - - return newObject; -} - export function isLocalProfile(profile: ProfileDescription): boolean { return profile.profileType === "local"; } - -/** - * Get the base system message for the agent or chat mode from the model description. - */ -export function getBaseSystemMessage( - modelDetails: ModelDescription | null, - mode: MessageModes, -) { - let baseChatOrAgentSystemMessage: string | undefined; - if (mode === "agent") { - baseChatOrAgentSystemMessage = - modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; - } else { - baseChatOrAgentSystemMessage = - modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; - } - return baseChatOrAgentSystemMessage; -} diff --git a/packages/config-yaml/src/schemas/data/index.ts b/packages/config-yaml/src/schemas/data/index.ts index 1353d9c54..57c820ab3 100644 --- a/packages/config-yaml/src/schemas/data/index.ts +++ b/packages/config-yaml/src/schemas/data/index.ts @@ -28,6 +28,7 @@ import { editInteractionEventSchema_0_2_0, editInteractionEventSchema_0_2_0_noCode, } from "./editInteraction/v0.2.0.js"; +import { editOutcomeEventAllSchema } from "./editOutcome/index.js"; import { editOutcomeEventSchema_0_2_0, editOutcomeEventSchema_0_2_0_noCode, @@ -51,6 +52,11 @@ import { tokensGeneratedEventSchema_0_2_0, tokensGeneratedEventSchema_0_2_0_noCode, } from "./tokensGenerated/v0.2.0.js"; +import { toolUsageEventAllSchema } from "./toolUsage/index.js"; +import { + toolUsageEventSchema_0_2_0, + toolUsageEventSchema_0_2_0_noCode, +} from "./toolUsage/v0.2.0.js"; const semverRegex = /^(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 @@ const devEventAllVersionDataSchemas = z.object({ tokensGenerated: tokensGeneratedEventAllSchema, chatInteraction: chatInteractionEventAllSchema, editInteraction: editInteractionEventAllSchema, + editOutcome: editOutcomeEventAllSchema, nextEdit: nextEditEventAllSchema, + toolUsage: toolUsageEventAllSchema, }); // Version and level specific schemas are organized here @@ -109,6 +117,7 @@ export const devDataVersionedSchemas = { editInteraction: editInteractionEventSchema_0_2_0, editOutcome: editOutcomeEventSchema_0_2_0, nextEdit: nextEditEventSchema_0_2_0, + toolUsage: toolUsageEventSchema_0_2_0, }, noCode: { autocomplete: autocompleteEventSchema_0_2_0_noCode, @@ -118,6 +127,7 @@ export const devDataVersionedSchemas = { editInteraction: editInteractionEventSchema_0_2_0_noCode, editOutcome: editOutcomeEventSchema_0_2_0_noCode, nextEdit: nextEditEventSchema_0_2_0_noCode, + toolUsage: toolUsageEventSchema_0_2_0_noCode, }, }, }; diff --git a/packages/config-yaml/src/schemas/data/toolUsage/index.ts b/packages/config-yaml/src/schemas/data/toolUsage/index.ts new file mode 100644 index 000000000..5e30b354b --- /dev/null +++ b/packages/config-yaml/src/schemas/data/toolUsage/index.ts @@ -0,0 +1,11 @@ +import { z } from "zod"; +import { baseDevDataAllSchema } from "../base.js"; + +export const toolUsageEventAllSchema = baseDevDataAllSchema.extend({ + toolCallId: z.string(), + functionName: z.string(), + functionArgs: z.string(), + toolCallArgs: z.any(), + succeeded: z.boolean(), + output: z.array(z.any()).optional(), +}); diff --git a/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts b/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts new file mode 100644 index 000000000..d77c34b51 --- /dev/null +++ b/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts @@ -0,0 +1,26 @@ +import { toolUsageEventAllSchema } from "./index.js"; + +export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({ + // base + timestamp: true, + userId: true, + userAgent: true, + selectedProfileId: true, + eventName: true, + schema: true, + + // tool-usage-specific + toolCallId: true, + functionName: true, + functionArgs: true, + toolCallArgs: true, + succeeded: true, + output: true, +}); + +export const toolUsageEventSchema_0_2_0_noCode = + toolUsageEventSchema_0_2_0.omit({ + functionArgs: true, + toolCallArgs: true, + output: true, + });