From 1bcb9b2199c9dd9bc70db9aeda88d05b5177d594 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 12 Jun 2025 18:15:29 +0530 Subject: [PATCH 01/57] migrate core config tests to vitest --- core/config/ConfigHandler.test.ts | 5 +++-- core/config/markdown/createMarkdownRule.test.ts | 1 + core/config/markdown/parseMarkdownRule.test.ts | 1 + core/config/util.test.ts | 1 + core/config/workspace/workspaceBlocks.test.ts | 2 +- core/jest.config.js | 5 +---- core/vitest.config.ts | 2 +- 7 files changed, 9 insertions(+), 8 deletions(-) diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 4b4be0762..5af9d6bb8 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.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/markdown/createMarkdownRule.test.ts b/core/config/markdown/createMarkdownRule.test.ts index fdc6536ee..57242a55e 100644 --- a/core/config/markdown/createMarkdownRule.test.ts +++ b/core/config/markdown/createMarkdownRule.test.ts @@ -1,3 +1,4 @@ +import { describe, expect, it } from "vitest"; import { createMarkdownWithFrontmatter, createRuleFilePath, diff --git a/core/config/markdown/parseMarkdownRule.test.ts b/core/config/markdown/parseMarkdownRule.test.ts index d05928574..c23aae7f0 100644 --- a/core/config/markdown/parseMarkdownRule.test.ts +++ b/core/config/markdown/parseMarkdownRule.test.ts @@ -1,3 +1,4 @@ +import { describe, expect, it } from "vitest"; import { convertMarkdownRuleToContinueRule, parseMarkdownRule, diff --git a/core/config/util.test.ts b/core/config/util.test.ts index e7de79e1b..5ea63c879 100644 --- a/core/config/util.test.ts +++ b/core/config/util.test.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.test.ts index 75c50cabd..e7b2fd77f 100644 --- a/core/config/workspace/workspaceBlocks.test.ts +++ b/core/config/workspace/workspaceBlocks.test.ts @@ -1,5 +1,5 @@ import { BlockType } from "@continuedev/config-yaml"; -import { describe, expect, test } from "@jest/globals"; +import { describe, expect, test } from "vitest"; import { RULE_FILE_EXTENSION } from "../markdown"; import { findAvailableFilename, getFileContent } from "./workspaceBlocks"; diff --git a/core/jest.config.js b/core/jest.config.js index 75bb11e9a..7c2a14634 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -32,8 +32,5 @@ export default { // modulePathIgnorePatterns: [ // "/config/yaml/LocalPlatformClient.test.ts", // ], - testPathIgnorePatterns: [ - "/config/yaml/LocalPlatformClient.test.ts", - "/autocomplete/", - ], + testPathIgnorePatterns: ["/config/", "/autocomplete/"], }; diff --git a/core/vitest.config.ts b/core/vitest.config.ts index d781d152d..21ddc79e2 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ fileParallelism: false, include: [ "**/*.vitest.ts", - "config/yaml/LocalPlatformClient.test.ts", + "config/**/*.test.ts", "autocomplete/**/*.test.ts", ], }, From b6f7143882b78e433d22045aa2c96f5db70e0aef Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 13 Jun 2025 19:34:10 +0530 Subject: [PATCH 02/57] migrate `context` foler --- core/context/mcp/MCPConnection.test.ts | 24 +++++++++---------- core/context/mcp/MCPManagerSingleton.test.ts | 24 +++++++++---------- .../providers/_context-providers.test.ts | 8 ++++++- core/context/retrieval/utils.test.ts | 2 +- core/jest.config.js | 6 ++++- core/vitest.config.ts | 1 + 6 files changed, 38 insertions(+), 27 deletions(-) diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.test.ts index f8f146f07..7736ebec9 100644 --- a/core/context/mcp/MCPConnection.test.ts +++ b/core/context/mcp/MCPConnection.test.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.test.ts index 49e2389d6..f361c13a1 100644 --- a/core/context/mcp/MCPManagerSingleton.test.ts +++ b/core/context/mcp/MCPManagerSingleton.test.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.test.ts index 468aac6ec..7ae55d32e 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.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/retrieval/utils.test.ts b/core/context/retrieval/utils.test.ts index 4b8d9d3fe..133e30c8e 100644 --- a/core/context/retrieval/utils.test.ts +++ b/core/context/retrieval/utils.test.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/jest.config.js b/core/jest.config.js index 7c2a14634..01cff7760 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -32,5 +32,9 @@ export default { // modulePathIgnorePatterns: [ // "/config/yaml/LocalPlatformClient.test.ts", // ], - testPathIgnorePatterns: ["/config/", "/autocomplete/"], + testPathIgnorePatterns: [ + "/config/", + "/autocomplete/", + "/context/", + ], }; diff --git a/core/vitest.config.ts b/core/vitest.config.ts index 21ddc79e2..746b1fa3d 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -13,6 +13,7 @@ export default defineConfig({ "**/*.vitest.ts", "config/**/*.test.ts", "autocomplete/**/*.test.ts", + "context/**/*.test.ts", ], }, }); From 64dbf42395738596b8557be2dab436e96447cbcd Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Sat, 21 Jun 2025 13:20:06 +0800 Subject: [PATCH 03/57] =?UTF-8?q?add=20tool=20support=20for=20deepseek-cha?= =?UTF-8?q?t=E3=80=81deepseek-reasoner(Only=20for=20deepseek=20official=20?= =?UTF-8?q?API=20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/llm/autodetect.ts | 4 +- core/llm/llms/Deepseek.ts | 115 +++++++++++++++++++++++++++++++++++++- core/llm/toolSupport.ts | 6 +- 3 files changed, 121 insertions(+), 4 deletions(-) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index dd65cc2d9..4993cee1d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -10,7 +10,6 @@ import { chatmlTemplateMessages, codeLlama70bTemplateMessages, codestralTemplateMessages, - deepseekTemplateMessages, gemmaTemplateMessage, graniteTemplateMessages, llama2TemplateMessages, @@ -293,7 +292,8 @@ function autodetectTemplateFunction( zephyr: zephyrTemplateMessages, anthropic: anthropicTemplateMessages, chatml: chatmlTemplateMessages, - deepseek: deepseekTemplateMessages, + // deepseek: deepseekTemplateMessages, + deepseek: null, openchat: openchatTemplateMessages, "xwin-coder": xWinCoderTemplateMessages, "neural-chat": neuralChatTemplateMessages, diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index 305d177e7..193f82ace 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -1,7 +1,14 @@ import { streamSse } from "@continuedev/fetch"; -import { CompletionOptions, LLMOptions } from "../../index.js"; +import { + AssistantChatMessage, + ChatMessage, + CompletionOptions, + LLMOptions, + ThinkingChatMessage, +} from "../../index.js"; import { osModelsEditPrompt } from "../templates/edit.js"; +import { LlmApiRequestType } from "../openaiTypeConverters"; import OpenAI from "./OpenAI.js"; class Deepseek extends OpenAI { @@ -16,6 +23,8 @@ class Deepseek extends OpenAI { }; maxStopWords: number | undefined = 16; + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = []; + supportsFim(): boolean { return true; } @@ -52,6 +61,110 @@ class Deepseek extends OpenAI { yield chunk.choices[0].text; } } + + protected async *_streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const body = this._convertArgs(options, messages); + + const response = await this.fetch(this._getEndpoint("chat/completions"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify({ + ...body, + ...this.extraBodyProperties(), + }), + signal, + }); + + // Handle non-streaming response + if (body.stream === false) { + if (response.status === 499) { + return; // Aborted by user + } + const data = await response.json(); + yield data.choices[0].message; + return; + } + + let message: AssistantChatMessage | ThinkingChatMessage | undefined; + let myArguments: string | undefined; + let lastMessageRole: "assistant" | "thinking" | undefined; + + function fromChatCompletionChunk(chunk: any): ChatMessage | undefined { + const delta = chunk.choices?.[0]?.delta; + + if (delta?.content) { + lastMessageRole = "assistant"; + return { + role: "assistant", + content: delta.content, + }; + } else if (delta?.reasoning_content) { + lastMessageRole = "thinking"; + return { + role: "thinking", + content: delta.reasoning_content, + }; + } else if (delta?.tool_calls) { + if (!message) { + message = { + role: "assistant", + content: "", + toolCalls: delta?.tool_calls.map((tool_call: any) => ({ + id: tool_call.id, + type: tool_call.type, + function: { + name: tool_call.function?.name, + arguments: tool_call.function?.arguments, + }, + })), + }; + myArguments = ""; + return message; + } else { + // @ts-ignore + myArguments += delta?.tool_calls[0].function.arguments; + } + return undefined; + } + + if (chunk.choices?.[0]?.finish_reason === "tool_calls") { + if (message) { + message = { + role: message.role, + content: message.content, + toolCalls: [ + { + id: message.toolCalls?.[0].id, + type: message.toolCalls?.[0].type, + function: { + name: message.toolCalls?.[0].function?.name, + arguments: myArguments, + }, + }, + ], + }; + const tempMessage = message; + message = undefined; + return tempMessage; + } else { + return undefined; + } + } else { + return undefined; + } + } + + for await (const value of streamSse(response)) { + const chunk = fromChatCompletionChunk(value); + if (chunk) { + yield chunk; + } + } + } } export default Deepseek; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 5f6ffbce8..a5d3f1632 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -179,7 +179,11 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, deepseek: (model) => { - if (model !== "deepseek-reasoner") { + if ( + model == "deepseek-reasoner" || + model == "deepseek-chat" || + model == "deepseek-coder" + ) { return true; } From 8f67a00bdb7b51f838bebd75b3c728c2a5950057 Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Sat, 21 Jun 2025 13:28:46 +0800 Subject: [PATCH 04/57] use "===" instead of "==" --- core/llm/toolSupport.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index a5d3f1632..fba0b15f5 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -180,9 +180,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = }, deepseek: (model) => { if ( - model == "deepseek-reasoner" || - model == "deepseek-chat" || - model == "deepseek-coder" + model === "deepseek-reasoner" || + model === "deepseek-chat" || + model === "deepseek-coder" ) { return true; } From d51054124787519dc1e3caf21b7baa365896a20c Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 23 Jun 2025 18:46:59 +0530 Subject: [PATCH 05/57] rename to vitest --- .../config/{ConfigHandler.test.ts => ConfigHandler.vitest.ts} | 0 ...dLocalAssistants.test.ts => loadLocalAssistants.vitest.ts} | 0 ...sFreeTrialApiKey.test.ts => usesFreeTrialApiKey.vitest.ts} | 4 ++-- core/config/{util.test.ts => util.vitest.ts} | 0 .../{workspaceBlocks.test.ts => workspaceBlocks.vitest.ts} | 0 .../mcp/{MCPConnection.test.ts => MCPConnection.vitest.ts} | 0 ...ManagerSingleton.test.ts => MCPManagerSingleton.vitest.ts} | 0 ...context-providers.test.ts => _context-providers.vitest.ts} | 0 core/context/retrieval/{utils.test.ts => utils.vitest.ts} | 0 9 files changed, 2 insertions(+), 2 deletions(-) rename core/config/{ConfigHandler.test.ts => ConfigHandler.vitest.ts} (100%) rename core/config/{loadLocalAssistants.test.ts => loadLocalAssistants.vitest.ts} (100%) rename core/config/{usesFreeTrialApiKey.test.ts => usesFreeTrialApiKey.vitest.ts} (98%) rename core/config/{util.test.ts => util.vitest.ts} (100%) rename core/config/workspace/{workspaceBlocks.test.ts => workspaceBlocks.vitest.ts} (100%) rename core/context/mcp/{MCPConnection.test.ts => MCPConnection.vitest.ts} (100%) rename core/context/mcp/{MCPManagerSingleton.test.ts => MCPManagerSingleton.vitest.ts} (100%) rename core/context/providers/{_context-providers.test.ts => _context-providers.vitest.ts} (100%) rename core/context/retrieval/{utils.test.ts => utils.vitest.ts} (100%) diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.vitest.ts similarity index 100% rename from core/config/ConfigHandler.test.ts rename to core/config/ConfigHandler.vitest.ts diff --git a/core/config/loadLocalAssistants.test.ts b/core/config/loadLocalAssistants.vitest.ts similarity index 100% rename from core/config/loadLocalAssistants.test.ts rename to core/config/loadLocalAssistants.vitest.ts diff --git a/core/config/usesFreeTrialApiKey.test.ts b/core/config/usesFreeTrialApiKey.vitest.ts similarity index 98% rename from core/config/usesFreeTrialApiKey.test.ts rename to core/config/usesFreeTrialApiKey.vitest.ts index 8e8727084..7fc42ebcc 100644 --- a/core/config/usesFreeTrialApiKey.test.ts +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -1,11 +1,11 @@ -import { jest } from "@jest/globals"; +import { beforeEach, test, vi } from "vitest"; import { BrowserSerializedContinueConfig } from ".."; // Create the mock before importing anything else const mockDecodeSecretLocation = jest.fn(); // Mock the module -jest.unstable_mockModule("@continuedev/config-yaml", () => ({ +vi.mock("@continuedev/config-yaml", () => ({ SecretType: { User: "user", Organization: "organization", diff --git a/core/config/util.test.ts b/core/config/util.vitest.ts similarity index 100% rename from core/config/util.test.ts rename to core/config/util.vitest.ts diff --git a/core/config/workspace/workspaceBlocks.test.ts b/core/config/workspace/workspaceBlocks.vitest.ts similarity index 100% rename from core/config/workspace/workspaceBlocks.test.ts rename to core/config/workspace/workspaceBlocks.vitest.ts diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.vitest.ts similarity index 100% rename from core/context/mcp/MCPConnection.test.ts rename to core/context/mcp/MCPConnection.vitest.ts diff --git a/core/context/mcp/MCPManagerSingleton.test.ts b/core/context/mcp/MCPManagerSingleton.vitest.ts similarity index 100% rename from core/context/mcp/MCPManagerSingleton.test.ts rename to core/context/mcp/MCPManagerSingleton.vitest.ts diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.vitest.ts similarity index 100% rename from core/context/providers/_context-providers.test.ts rename to core/context/providers/_context-providers.vitest.ts diff --git a/core/context/retrieval/utils.test.ts b/core/context/retrieval/utils.vitest.ts similarity index 100% rename from core/context/retrieval/utils.test.ts rename to core/context/retrieval/utils.vitest.ts From 94031da6b46b1b7085015a727864af971cfdf317 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 23 Jun 2025 18:51:04 +0530 Subject: [PATCH 06/57] add vitest imports --- core/config/loadLocalAssistants.vitest.ts | 1 + core/config/usesFreeTrialApiKey.vitest.ts | 6 +++--- core/config/workspace/workspaceBlocks.vitest.ts | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/core/config/loadLocalAssistants.vitest.ts b/core/config/loadLocalAssistants.vitest.ts index 2865a5b34..a366316d4 100644 --- a/core/config/loadLocalAssistants.vitest.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.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts index 7fc42ebcc..ddf9b3f83 100644 --- a/core/config/usesFreeTrialApiKey.vitest.ts +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -1,8 +1,8 @@ -import { beforeEach, test, vi } from "vitest"; +import { beforeEach, expect, test, vi } from "vitest"; import { BrowserSerializedContinueConfig } from ".."; // Create the mock before importing anything else -const mockDecodeSecretLocation = jest.fn(); +const mockDecodeSecretLocation = vi.fn(); // Mock the module vi.mock("@continuedev/config-yaml", () => ({ @@ -259,7 +259,7 @@ test("usesFreeTrialApiKey should return true when free trial model is in a diffe }); test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => { - const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); const config: BrowserSerializedContinueConfig = { modelsByRole: { diff --git a/core/config/workspace/workspaceBlocks.vitest.ts b/core/config/workspace/workspaceBlocks.vitest.ts index 532444196..281a4d785 100644 --- a/core/config/workspace/workspaceBlocks.vitest.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", () => { From 5648c21bb75a4c7610fd8d3a813edbfc6237940b Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Wed, 25 Jun 2025 10:28:47 +0800 Subject: [PATCH 07/57] remove "deepseek" from TemplateType --- core/index.d.ts | 2 +- core/llm/autodetect.ts | 12 +++--------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index d2792a228..649eb62ef 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -903,7 +903,7 @@ export type TemplateType = | "chatml" | "none" | "openchat" - | "deepseek" + // | "deepseek" ---- remove this because add tool call support for deepseek models | "xwin-coder" | "neural-chat" | "codellama-70b" diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 4993cee1d..977d2b1ea 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -186,7 +186,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("gemini") || lower.includes("grok") || lower.includes("moonshot") || - lower.includes("mercury") + lower.includes("mercury") || + lower.includes("deepseek") ) { return undefined; } @@ -247,10 +248,6 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return "llama2"; } - if (lower.includes("deepseek")) { - return "deepseek"; - } - if (lower.includes("ninja") || lower.includes("openchat")) { return "openchat"; } @@ -293,7 +290,6 @@ function autodetectTemplateFunction( anthropic: anthropicTemplateMessages, chatml: chatmlTemplateMessages, // deepseek: deepseekTemplateMessages, - deepseek: null, openchat: openchatTemplateMessages, "xwin-coder": xWinCoderTemplateMessages, "neural-chat": neuralChatTemplateMessages, @@ -316,7 +312,7 @@ const USES_OS_MODELS_EDIT_PROMPT: TemplateType[] = [ "alpaca", "chatml", // "codellama-70b", Doesn't respond well to this prompt - "deepseek", + // "deepseek", "gemma", "llama2", "llava", @@ -356,8 +352,6 @@ function autodetectPromptTemplates( } } else if (templateType === "alpaca") { editTemplate = alpacaEditPrompt; - } else if (templateType === "deepseek") { - editTemplate = deepseekEditPrompt; } else if (templateType === "openchat") { editTemplate = openchatEditPrompt; } else if (templateType === "xwin-coder") { From 8b0f32d0c4c303d245b6f4f8171e17e15ccbfc52 Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Wed, 25 Jun 2025 11:06:03 +0800 Subject: [PATCH 08/57] Currently working fine, so rolling back. --- core/llm/llms/Deepseek.ts | 115 +------------------------------------- 1 file changed, 1 insertion(+), 114 deletions(-) diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index 193f82ace..305d177e7 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -1,14 +1,7 @@ import { streamSse } from "@continuedev/fetch"; -import { - AssistantChatMessage, - ChatMessage, - CompletionOptions, - LLMOptions, - ThinkingChatMessage, -} from "../../index.js"; +import { CompletionOptions, LLMOptions } from "../../index.js"; import { osModelsEditPrompt } from "../templates/edit.js"; -import { LlmApiRequestType } from "../openaiTypeConverters"; import OpenAI from "./OpenAI.js"; class Deepseek extends OpenAI { @@ -23,8 +16,6 @@ class Deepseek extends OpenAI { }; maxStopWords: number | undefined = 16; - protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = []; - supportsFim(): boolean { return true; } @@ -61,110 +52,6 @@ class Deepseek extends OpenAI { yield chunk.choices[0].text; } } - - protected async *_streamChat( - messages: ChatMessage[], - signal: AbortSignal, - options: CompletionOptions, - ): AsyncGenerator { - const body = this._convertArgs(options, messages); - - const response = await this.fetch(this._getEndpoint("chat/completions"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify({ - ...body, - ...this.extraBodyProperties(), - }), - signal, - }); - - // Handle non-streaming response - if (body.stream === false) { - if (response.status === 499) { - return; // Aborted by user - } - const data = await response.json(); - yield data.choices[0].message; - return; - } - - let message: AssistantChatMessage | ThinkingChatMessage | undefined; - let myArguments: string | undefined; - let lastMessageRole: "assistant" | "thinking" | undefined; - - function fromChatCompletionChunk(chunk: any): ChatMessage | undefined { - const delta = chunk.choices?.[0]?.delta; - - if (delta?.content) { - lastMessageRole = "assistant"; - return { - role: "assistant", - content: delta.content, - }; - } else if (delta?.reasoning_content) { - lastMessageRole = "thinking"; - return { - role: "thinking", - content: delta.reasoning_content, - }; - } else if (delta?.tool_calls) { - if (!message) { - message = { - role: "assistant", - content: "", - toolCalls: delta?.tool_calls.map((tool_call: any) => ({ - id: tool_call.id, - type: tool_call.type, - function: { - name: tool_call.function?.name, - arguments: tool_call.function?.arguments, - }, - })), - }; - myArguments = ""; - return message; - } else { - // @ts-ignore - myArguments += delta?.tool_calls[0].function.arguments; - } - return undefined; - } - - if (chunk.choices?.[0]?.finish_reason === "tool_calls") { - if (message) { - message = { - role: message.role, - content: message.content, - toolCalls: [ - { - id: message.toolCalls?.[0].id, - type: message.toolCalls?.[0].type, - function: { - name: message.toolCalls?.[0].function?.name, - arguments: myArguments, - }, - }, - ], - }; - const tempMessage = message; - message = undefined; - return tempMessage; - } else { - return undefined; - } - } else { - return undefined; - } - } - - for await (const value of streamSse(response)) { - const chunk = fromChatCompletionChunk(value); - if (chunk) { - yield chunk; - } - } - } } export default Deepseek; From 38342fa3852d52e3535b1799b9fc3a004857002e Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Wed, 25 Jun 2025 11:27:03 +0800 Subject: [PATCH 09/57] remove "deepseek" from templateSchema to adapt remove "deepseek" from TemplateType --- packages/config-yaml/src/schemas/models.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 893f7117a..2ddedf794 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -95,7 +95,7 @@ const templateSchema = z.enum([ "chatml", "none", "openchat", - "deepseek", + // "deepseek", "xwin-coder", "neural-chat", "codellama-70b", From ba37b5706a715570d84ec9c654fc9af4c72c67ba Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 26 Jun 2025 17:16:01 +0200 Subject: [PATCH 10/57] perf: Avoid storing services as a field in long-lived components We should never acquire service instances prematurely or store them in fields for later use. This is considered as bad practice due to potential memory leaks. More details: https://plugins.jetbrains.com/docs/intellij/plugin-services.html#retrieving-a-service FYI there's a nice extension method for retrieving services like `project.service` or `service` for application-level services (like Continue settings). I've applied this everywhere. --- .../actions/ContinueActionPromote.kt | 4 +-- .../actions/utils.kt | 13 ++------- .../activities/ContinuePluginDisposable.kt | 13 --------- .../ContinuePluginStartupActivity.kt | 11 ++----- .../autocomplete/AutocompleteService.kt | 13 ++++----- .../AutocompleteSpinnerWidgetFactory.kt | 2 +- .../continue/ApplyToFileHandler.kt | 3 +- .../continue/Diffs.kt | 14 ++------- .../continue/IdeProtocolClient.kt | 5 ++-- .../editor/DiffStreamHandler.kt | 9 +++--- .../ContinueExtensionSettingsService.kt | 2 +- .../toolWindow/ContinueBrowser.kt | 29 +++++++++---------- .../ContinuePluginToolWindowFactory.kt | 8 ++--- 13 files changed, 44 insertions(+), 82 deletions(-) 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 8cb05dc31..39c3d9b78 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 @@ -174,7 +175,7 @@ class ApplyToFileHandler( else EditorUtils.getEditorByCreateFile(project, params.filepath) - val diffStreamService = project.getService(DiffStreamService::class.java) + val diffStreamService = project.service() val handler = ApplyToFileHandler( project, 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..547adfca1 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 @@ -46,7 +46,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 +67,7 @@ class IdeProtocolClient( } "jetbrains/isOSREnabled" -> { - val isOSREnabled = - ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = service().continueState.enableOSR respond(isOSREnabled) } 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 67e49a87f..0b843b40f 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/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 } From 76c216999bc518a4b68223081c5fa567523c628e Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 26 Jun 2025 13:14:31 -0700 Subject: [PATCH 11/57] working toolUsage devdata events added --- core/core.ts | 10 ++++++- core/protocol/webview.ts | 4 +++ gui/src/hooks/ParallelListeners.tsx | 29 +++++++++++++++++++ gui/src/redux/slices/sessionSlice.ts | 21 -------------- gui/src/redux/thunks/callCurrentTool.ts | 20 +++++++++++++ .../src/schemas/data/toolUsage/index.ts | 1 + .../src/schemas/data/toolUsage/v0.2.0.ts | 1 + 7 files changed, 64 insertions(+), 22 deletions(-) diff --git a/core/core.ts b/core/core.ts index 5e8d4d060..71451de51 100644 --- a/core/core.ts +++ b/core/core.ts @@ -809,7 +809,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, @@ -820,6 +820,14 @@ export class Core { onPartialOutput, codeBaseIndexer: this.codeBaseIndexer, }); + + this.messenger.send("toolCallCompleted", { + toolCallId: toolCall.id, + contextItems: result.contextItems, + succeeded: !result.errorMessage, + }); + + return result; } private async isItemTooBig(item: ContextItemWithId) { diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 1a8d40313..524975031 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -43,5 +43,9 @@ export type ToWebviewFromIdeOrCoreProtocol = { "jetbrains/setColors": [Record, void]; sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; + toolCallCompleted: [ + { toolCallId: string; contextItems: any[]; succeeded: boolean }, + void, + ]; freeTrialExceeded: [undefined, void]; }; diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 5bf2c977a..2036dc365 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -27,10 +27,13 @@ import { setTTSActive } from "../redux/slices/uiSlice"; import { exitEdit } from "../redux/thunks/edit"; import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall"; +import { safeParseToolCallArgs } from "core/tools/parseArgs"; +import { store } from "../redux/store"; import { cancelStream } from "../redux/thunks/cancelStream"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; +import { findToolCall } from "../redux/util"; import { setDocumentStylesFromLocalStorage, setDocumentStylesFromTheme, @@ -285,6 +288,32 @@ function ParallelListeners() { [currentToolCallApplyState, history], ); + useWebviewListener( + "toolCallCompleted", + async (data) => { + const state = store.getState(); + const toolCallState = findToolCall( + state.session.history, + data.toolCallId, + ); + if (toolCallState) { + ideMessenger.post("devdata/log", { + name: "toolUsage", + data: { + toolCallId: toolCallState.toolCallId, + functionName: toolCallState.toolCall.function.name, + functionArgs: toolCallState.toolCall.function.arguments, + toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), + parsedArgs: toolCallState.parsedArgs, + output: data.contextItems, + succeeded: data.succeeded, + }, + }); + } + }, + [ideMessenger, store], + ); + useEffect(() => { if (!isInEdit) { dispatch(setLastNonEditSessionEmpty(history.length === 0)); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 50ff37320..1794559a6 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -18,9 +18,7 @@ import { RuleWithSource, Session, SessionMetadata, - ToolCallState, } from "core"; -import { safeParseToolCallArgs } from "core/tools/parseArgs"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; import { findUriInDirs, getUriPathBasename } from "core/util/uri"; @@ -32,23 +30,6 @@ import { findCurrentToolCall, findToolCall } from "../util"; const getIdeMessenger = () => (window as any).ideMessenger; -const logToolUsage = (toolCallState: ToolCallState, success: boolean) => { - const ideMessenger = getIdeMessenger(); - if (ideMessenger) { - ideMessenger.post("devdata/log", { - name: "toolUsage", - data: { - toolCallId: toolCallState.toolCallId, - functionName: toolCallState.toolCall.function.name, - functionArgs: toolCallState.toolCall.function.arguments, - parsedArgs: safeParseToolCallArgs(toolCallState.toolCall), - succeeded: success, - output: toolCallState.output || [], - }, - }); - } -}; - // 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. export type ChatHistoryItemWithMessageId = ChatHistoryItem & { @@ -580,7 +561,6 @@ export const sessionSlice = createSlice({ ); if (toolCallState) { toolCallState.status = "errored"; - logToolUsage(toolCallState, false); } }, acceptToolCall: ( @@ -595,7 +575,6 @@ export const sessionSlice = createSlice({ ); if (toolCallState) { toolCallState.status = "done"; - logToolUsage(toolCallState, true); } }, setToolCallCalling: ( diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index 02137d822..a9a823a65 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -1,6 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ContextItem } from "core"; import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn"; +import { safeParseToolCallArgs } from "core/tools/parseArgs"; import posthog from "posthog-js"; import { callClientTool } from "../../util/clientTools/callClientTool"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; @@ -28,6 +29,21 @@ export const callCurrentTool = createAsyncThunk( return; } + const logToolUsage = (success: boolean, finalOutput?: ContextItem[]) => { + extra.ideMessenger.post("devdata/log", { + name: "toolUsage", + data: { + toolCallId: toolCallState.toolCallId, + functionName: toolCallState.toolCall.function.name, + functionArgs: toolCallState.toolCall.function.arguments, + toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), + parsedArgs: toolCallState.parsedArgs, + output: finalOutput || toolCallState.output || [], + succeeded: success, + }, + }); + }; + const selectedChatModel = selectSelectedChatModel(state); if (!selectedChatModel) { @@ -105,6 +121,8 @@ export const callCurrentTool = createAsyncThunk( ], }), ); + + logToolUsage(false, output); } else if (output?.length) { dispatch( updateToolCallOutput({ @@ -112,6 +130,8 @@ export const callCurrentTool = createAsyncThunk( contextItems: output, }), ); + + logToolUsage(true, output); } // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` diff --git a/packages/config-yaml/src/schemas/data/toolUsage/index.ts b/packages/config-yaml/src/schemas/data/toolUsage/index.ts index 8119366f3..225b5c0ab 100644 --- a/packages/config-yaml/src/schemas/data/toolUsage/index.ts +++ b/packages/config-yaml/src/schemas/data/toolUsage/index.ts @@ -5,6 +5,7 @@ export const toolUsageEventAllSchema = baseDevDataAllSchema.extend({ toolCallId: z.string(), functionName: z.string(), functionArgs: z.string(), + toolCallArgs: z.any(), parsedArgs: 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 index 533e33218..c1045104a 100644 --- a/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts @@ -13,6 +13,7 @@ export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({ toolCallId: true, functionName: true, functionArgs: true, + toolCallArgs: true, parsedArgs: true, succeeded: true, output: true, From 90c1c0486e1f4094e7bf3480bad44f6bcb6c5079 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 26 Jun 2025 13:29:59 -0700 Subject: [PATCH 12/57] optional chaining to for recurse bot --- gui/src/redux/thunks/callCurrentTool.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index a9a823a65..4b76c7201 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -34,8 +34,8 @@ export const callCurrentTool = createAsyncThunk( name: "toolUsage", data: { toolCallId: toolCallState.toolCallId, - functionName: toolCallState.toolCall.function.name, - functionArgs: toolCallState.toolCall.function.arguments, + functionName: toolCallState.toolCall?.function?.name, + functionArgs: toolCallState.toolCall?.function?.arguments, toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), parsedArgs: toolCallState.parsedArgs, output: finalOutput || toolCallState.output || [], From 155525db20877fdc1ec99cbc5dfd07a91f96e2e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 26 Jun 2025 14:52:40 -0700 Subject: [PATCH 13/57] add resubmit button to simple tool UI --- gui/src/components/mainInput/icons.ts | 2 + gui/src/pages/gui/Chat.tsx | 1 - .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 43 ++++++++++++------- gui/src/pages/gui/ToolCallDiv/index.tsx | 9 +--- .../ToolCallDiv/toolCallStateToContextItem.ts | 15 +++++++ 5 files changed, 45 insertions(+), 25 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts diff --git a/gui/src/components/mainInput/icons.ts b/gui/src/components/mainInput/icons.ts index d8d04cc83..62d69e65b 100644 --- a/gui/src/components/mainInput/icons.ts +++ b/gui/src/components/mainInput/icons.ts @@ -18,6 +18,7 @@ import { PlusIcon, SparklesIcon, TrashIcon, + WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { DiscordIcon } from "../svg/DiscordIcon"; import { GithubIcon } from "../svg/GithubIcon"; @@ -55,4 +56,5 @@ export const NAMED_ICONS: { [key: string]: any } = { "gitlab-mr": GitlabIcon, http: GlobeAltIcon, trash: TrashIcon, + toolCall: WrenchScrewdriverIcon, }; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 4a6d33849..5ba60e7e9 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -330,7 +330,6 @@ export function Chat() { key={i} toolCallState={item.toolCallState!} toolCall={toolCall} - output={history[index + 1]?.contextItems} historyIndex={index} /> ); diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 07b7838a7..e8af9569a 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,26 +1,27 @@ -import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { ContextItemWithId, Tool, ToolCallState } from "core"; +import { ArrowPathIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { Tool, ToolCallState } from "core"; import { ComponentType, useMemo, useState } from "react"; import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; +import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; +import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; tool: Tool | undefined; - contextItems: ContextItemWithId[]; icon?: ComponentType>; } export function SimpleToolCallUI({ - contextItems, icon: Icon, toolCallState, tool, }: SimpleToolCallUIProps) { - const ctxItems = useMemo(() => { - return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; - }, [contextItems]); + const shownContextItems = useMemo(() => { + const contextItems = toolCallStateToContextItems(toolCallState); + return contextItems.filter((item) => !item.hidden); + }, [toolCallState]); const [open, setOpen] = useState(false); const [isHovered, setIsHovered] = useState(false); @@ -54,13 +55,23 @@ export function SimpleToolCallUI({ - {args.length > 0 ? ( - - ) : null} +
+ { + console.log("Resubmit clicked"); + }} + > + + + {args.length > 0 ? ( + + ) : null} +
- {ctxItems.length ? ( - ctxItems.map((contextItem, idx) => ( + {shownContextItems.length ? ( + shownContextItems.map((contextItem, idx) => ( )) ) : ( diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 9f867356e..b9614f250 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -12,12 +12,7 @@ import { PencilIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { - ContextItemWithId, - ToolCallDelta, - ToolCallState, - ToolStatus, -} from "core"; +import { ToolCallDelta, ToolCallState, ToolStatus } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { ComponentType, useMemo } from "react"; import { vscButtonBackground } from "../../../components"; @@ -30,7 +25,6 @@ import { ToolCallDisplay } from "./ToolCall"; interface ToolCallDivProps { toolCall: ToolCallDelta; toolCallState: ToolCallState; - output?: ContextItemWithId[]; historyIndex: number; } @@ -86,7 +80,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={ props.toolCallState.status === "generated" ? ArrowRightIcon : icon } - contextItems={props.output ?? []} /> ); } diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts new file mode 100644 index 000000000..ccb8a7976 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -0,0 +1,15 @@ +import { ContextItemWithId, ToolCallState } from "core"; + +export function toolCallStateToContextItems( + toolCallState: ToolCallState, +): ContextItemWithId[] { + return ( + toolCallState.output?.map((item) => ({ + ...item, + id: { + providerTitle: "toolCall", + itemId: toolCallState.toolCallId, + }, + })) ?? [] + ); +} From ec7c497faf0ab75c31a7620d9307076b38d35bfb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 19:18:09 -0700 Subject: [PATCH 14/57] truncate history icon on non-last tool messages --- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 20 ++++++------ gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 20 +++++++----- .../gui/ToolCallDiv/TruncateHistoryIcon.tsx | 31 +++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 2 ++ gui/src/redux/slices/sessionSlice.ts | 22 +++++++++++++ 5 files changed, 77 insertions(+), 18 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index e8af9569a..1f19ea438 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,23 +1,28 @@ -import { ArrowPathIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { ChevronRightIcon } from "@heroicons/react/24/outline"; import { Tool, ToolCallState } from "core"; import { ComponentType, useMemo, useState } from "react"; import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; -import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; +import { TruncateHistoryIcon } from "./TruncateHistoryIcon"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; tool: Tool | undefined; icon?: ComponentType>; + historyIndex: number; } export function SimpleToolCallUI({ icon: Icon, toolCallState, tool, + historyIndex, }: SimpleToolCallUIProps) { + const history = useAppSelector((state) => state.session.history); + const dispatch = useAppDispatch(); const shownContextItems = useMemo(() => { const contextItems = toolCallStateToContextItems(toolCallState); return contextItems.filter((item) => !item.hidden); @@ -55,15 +60,8 @@ export function SimpleToolCallUI({
-
- { - console.log("Resubmit clicked"); - }} - > - - +
+ {args.length > 0 ? (
- {!!args.length ? ( - - ) : null} +
+ + {!!args.length ? ( + + ) : null} +
{argsExpanded && !!args.length && ( diff --git a/gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx new file mode 100644 index 000000000..296cbc4e4 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx @@ -0,0 +1,31 @@ +import { ArrowUpTrayIcon } from "@heroicons/react/24/outline"; +import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { truncateHistoryToMessage } from "../../../redux/slices/sessionSlice"; + +export function TruncateHistoryIcon({ + historyIndex, +}: { + historyIndex: number; +}) { + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const history = useAppSelector((state) => state.session.history); + const dispatch = useAppDispatch(); + if (isStreaming || historyIndex === history.length - 1) { + return null; + } + return ( + { + dispatch( + truncateHistoryToMessage({ + index: historyIndex, + }), + ); + }} + > + + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index b9614f250..4141631bb 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -80,6 +80,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={ props.toolCallState.status === "generated" ? ArrowRightIcon : icon } + historyIndex={props.historyIndex} /> ); } @@ -89,6 +90,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={getStatusIcon(props.toolCallState.status)} tool={tool} toolCallState={props.toolCallState} + historyIndex={props.historyIndex} > , + ) => { + const { index } = payload; + + if (state.history.length && index < state.history.length) { + state.history = state.history.slice(0, index + 1).concat({ + message: { + id: uuidv4(), + role: "assistant", + content: "", // IMPORTANT - this is subsequently updated by response streaming + }, + contextItems: [], + }); + } + }, submitEditorAndInitAtIndex: ( state, { @@ -676,6 +697,7 @@ export const { addPromptCompletionPair, setActive, submitEditorAndInitAtIndex, + truncateHistoryToMessage, updateHistoryItemAtIndex, clearLastEmptyResponse, setMainEditorContentTrigger, From 62381e87907820dcff83801a6ac11c59932641e1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 19:30:01 -0700 Subject: [PATCH 15/57] don't focus main editor if another editor is focused --- gui/src/components/ModeSelect/ModeSelect.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index a5792d721..8989583ff 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -34,7 +34,9 @@ export function ModeSelect() { const cycleMode = useCallback(() => { dispatch(setMode(mode === "chat" ? "agent" : "chat")); - mainEditor?.commands.focus(); + if (!document.activeElement?.classList.contains("ProseMirror")) { + mainEditor?.commands.focus(); + } }, [mode, mainEditor]); const selectMode = useCallback( From c28f70a9f0f9603a2e52925ef4f2317e20f899da Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 20:23:03 -0700 Subject: [PATCH 16/57] context peek formatting and fix last index logic for tool truncation logic --- core/util/findLast.ts | 6 +- .../belowMainInput/ContextItemsPeek.tsx | 58 +++++++++---------- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 6 +- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 6 +- ...ryIcon.tsx => ToolTruncateHistoryIcon.tsx} | 18 ++++-- 5 files changed, 52 insertions(+), 42 deletions(-) rename gui/src/pages/gui/ToolCallDiv/{TruncateHistoryIcon.tsx => ToolTruncateHistoryIcon.tsx} (54%) 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/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 3c7ce9390..cb3009675 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -117,40 +117,36 @@ export function ContextItemsPeekItem({ return (
-
- {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} + adsfasdfasdjk; asdfl;kjasdl;fkjasdlk;fja asdfklj;asdl;fkjasdf + {isUrl && ( - + )}
diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 1f19ea438..9ba9ae60d 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -6,7 +6,7 @@ import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; -import { TruncateHistoryIcon } from "./TruncateHistoryIcon"; +import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; @@ -61,7 +61,9 @@ export function SimpleToolCallUI({
- + {!!toolCallState.output?.length && ( + + )} {args.length > 0 ? (
- + {!!toolCallState.output && ( + + )} {!!args.length ? ( state.session.isStreaming); const history = useAppSelector((state) => state.session.history); + const lastMessageIndex = useMemo(() => { + return findLastIndex(history, (item) => !chatMessageIsEmpty(item.message)); + }, [history]); const dispatch = useAppDispatch(); - if (isStreaming || historyIndex === history.length - 1) { + const { mainEditor } = useMainEditor(); + if (isStreaming || lastMessageIndex) { return null; } return ( @@ -23,9 +31,11 @@ export function TruncateHistoryIcon({ index: historyIndex, }), ); + mainEditor?.commands.focus(); }} > - + {historyIndex}/{history.length - 1} + ); } From 9700a10e50ea4bbdbecea64dacf39932b781535e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 21:34:21 -0700 Subject: [PATCH 17/57] WIP: only add tool messages in construct messages --- core/llm/constructMessages.ts | 82 +++++++++++++++---- .../belowMainInput/ContextItemsPeek.tsx | 1 - .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 3 - .../ToolCallDiv/ToolTruncateHistoryIcon.tsx | 5 +- gui/src/redux/slices/sessionSlice.ts | 1 + gui/src/redux/thunks/streamResponse.ts | 7 ++ .../thunks/streamResponseAfterToolCall.ts | 7 ++ 7 files changed, 82 insertions(+), 24 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 49115cb6f..5a3967361 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -4,11 +4,15 @@ import { ContextItemWithId, RuleWithSource, TextMessagePart, + Tool, ToolResultChatMessage, UserChatMessage, } from "../"; import { findLast } from "../util/findLast"; -import { normalizeToMessageParts } from "../util/messageContent"; +import { + normalizeToMessageParts, + renderContextItems, +} from "../util/messageContent"; import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; import { RulePolicies } from "./rules/types"; @@ -109,30 +113,38 @@ export function constructMessages( history: ChatHistoryItem[], baseChatOrAgentSystemMessage: string | undefined, rules: RuleWithSource[], + tools: Tool[], rulePolicies?: RulePolicies, ): ChatMessage[] { + const validTools = new Set(tools.map((tool) => tool.function.name)); + 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; - } + for (const item of filteredHistory) { + if (item.message.role === "tool") { + continue; // Tool messages will be re-inserted } - if (historyItem.message.role === "user") { - // Gather context items for user messages - let content = normalizeToMessageParts(historyItem.message); + // This was implemented for APIs that require all tool calls to have + // A corresponsing tool sent, which means if a user excluded a tool + // Then sessions with that tool call in the history would fail + // if (messageMode === "chat") { + // const toolMessage: ToolResultChatMessage = + // historyItem.message as ToolResultChatMessage; + // if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { + // // remove all tool calls from the history + // continue; + // } + // } - const ctxItems = historyItem.contextItems + if (item.message.role === "user") { + // Gather context items for user messages + let content = normalizeToMessageParts(item.message); + + const ctxItems = item.contextItems .map((ctxItem) => { return { type: "text", @@ -143,11 +155,47 @@ export function constructMessages( content = [...ctxItems, ...content]; msgs.push({ - ...historyItem.message, + ...item.message, content, }); } else { - msgs.push(historyItem.message); + msgs.push(item.message); + } + + if (item.message.role === "assistant") { + // First, push a version of the message with any valid tools calls + const validToolCalls = item.message.toolCalls?.filter( + (toolCall) => + toolCall.function?.name && + toolCall.id && + validTools.has(toolCall.function.name), + ); + + // Case where no valid tool calls or content are present + msgs.push({ + ...item.message, + toolCalls: validToolCalls, + }); + + // Then push a tool message for each valid tool call + if (validToolCalls?.length) { + // If the assistant message has tool calls, we need to insert tool messages + for (const toolCall of validToolCalls) { + let content: string = "No tool output"; + // TODO toolCallState only supports one tool call per message for now + if ( + item.toolCallState?.toolCallId === toolCall.id && + item.toolCallState?.output + ) { + content = renderContextItems(item.toolCallState.output); + } + msgs.push({ + role: "tool", + content, + toolCallId: toolCall.id!, + }); + } + } } } diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index cb3009675..31c392bf1 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -143,7 +143,6 @@ export function ContextItemsPeekItem({ {contextItem.uri?.type === "file" ? getUriPathBasename(contextItem.description) : contextItem.description} - adsfasdfasdjk; asdfl;kjasdl;fkjasdlk;fja asdfklj;asdl;fkjasdf {isUrl && ( diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 9ba9ae60d..51af15c77 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -2,7 +2,6 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; import { Tool, ToolCallState } from "core"; import { ComponentType, useMemo, useState } from "react"; import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; @@ -21,8 +20,6 @@ export function SimpleToolCallUI({ tool, historyIndex, }: SimpleToolCallUIProps) { - const history = useAppSelector((state) => state.session.history); - const dispatch = useAppDispatch(); const shownContextItems = useMemo(() => { const contextItems = toolCallStateToContextItems(toolCallState); return contextItems.filter((item) => !item.hidden); diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx index cf57a6c08..e4f0a1cc8 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx @@ -19,7 +19,7 @@ export function ToolTruncateHistoryIcon({ }, [history]); const dispatch = useAppDispatch(); const { mainEditor } = useMainEditor(); - if (isStreaming || lastMessageIndex) { + if (isStreaming || historyIndex === lastMessageIndex) { return null; } return ( @@ -34,8 +34,7 @@ export function ToolTruncateHistoryIcon({ mainEditor?.commands.focus(); }} > - {historyIndex}/{history.length - 1} - + ); } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 80c88dc54..339369cd9 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -157,6 +157,7 @@ export const sessionSlice = createSlice({ const { index } = payload; if (state.history.length && index < state.history.length) { + state.codeBlockApplyStates.curIndex = 0; state.history = state.history.slice(0, index + 1).concat({ message: { id: uuidv4(), diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index caeded723..facc987c7 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,11 +1,13 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; +import { modelSupportsTools } from "core/llm/autodetect"; import { constructMessages } from "core/llm/constructMessages"; import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; import { getBaseSystemMessage } from "../../util"; +import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { setAppliedRulesAtIndex, @@ -119,11 +121,16 @@ export const streamResponseThunk = createAsyncThunk< messageMode, ); + const activeTools = selectActiveTools(state); + const toolsSupported = modelSupportsTools(selectedChatModel); + const availableTools = toolsSupported ? activeTools : []; + const messages = constructMessages( messageMode, [...updatedHistory], baseChatOrAgentSystemMessage, applicableRules, + availableTools, rulePolicies, ); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 3a29491c5..75134b951 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,8 +1,10 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; +import { modelSupportsTools } from "core/llm/autodetect"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; import { getBaseSystemMessage } from "../../util"; +import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -67,11 +69,16 @@ export const streamResponseAfterToolCall = createAsyncThunk< messageMode, ); + const activeTools = selectActiveTools(state); + const toolsSupported = modelSupportsTools(selectedChatModel); + const availableTools = toolsSupported ? activeTools : []; + const messages = constructMessages( messageMode, [...updatedHistory], baseChatOrAgentSystemMessage, state.config.config.rules, + availableTools, ); unwrapResult(await dispatch(streamNormalInput({ messages }))); From 1c390db596fab0a8b5dff1d1436e2e9526d417bc Mon Sep 17 00:00:00 2001 From: Jacob Date: Sat, 28 Jun 2025 23:14:09 +0800 Subject: [PATCH 18/57] Fix retrieval reranker sorting issue --- core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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; From fc618652aac26ca84dd2579c44a626521ccae5d4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 29 Jun 2025 19:16:35 -0700 Subject: [PATCH 19/57] WIP - broken tool message progress --- core/llm/constructMessages.ts | 51 ++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 5a3967361..eb33cb413 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,5 @@ import { + AssistantChatMessage, ChatHistoryItem, ChatMessage, ContextItemWithId, @@ -13,7 +14,7 @@ import { normalizeToMessageParts, renderContextItems, } from "../util/messageContent"; -import { isUserOrToolMsg } from "./messages"; +import { chatMessageIsEmpty, isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; import { RulePolicies } from "./rules/types"; @@ -118,28 +119,17 @@ export function constructMessages( ): ChatMessage[] { const validTools = new Set(tools.map((tool) => tool.function.name)); - const filteredHistory = history.filter( - (item) => item.message.role !== "system", - ); const msgs: ChatMessage[] = []; - - for (const item of filteredHistory) { - if (item.message.role === "tool") { - continue; // Tool messages will be re-inserted + for (const item of history) { + if ( + item.message.role === "system" || + item.message.role === "tool" || + chatMessageIsEmpty(item.message) + ) { + continue; + // Tool messages will be re-inserted } - // This was implemented for APIs that require all tool calls to have - // A corresponsing tool sent, which means if a user excluded a tool - // Then sessions with that tool call in the history would fail - // 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 (item.message.role === "user") { // Gather context items for user messages let content = normalizeToMessageParts(item.message); @@ -171,13 +161,26 @@ export function constructMessages( validTools.has(toolCall.function.name), ); - // Case where no valid tool calls or content are present - msgs.push({ + const msgWithValidToolCalls: AssistantChatMessage = { ...item.message, toolCalls: validToolCalls, - }); + }; - // Then push a tool message for each valid tool call + if (chatMessageIsEmpty(msgWithValidToolCalls)) { + msgs.push({ + role: "assistant", + content: "Message redacted", // TODO this might be confusing, edge case situation where tools are excluded + }); + } + + // This was implemented for APIs that require all tool calls to have + // A corresponsing tool sent, which means if a user excluded a tool + // Then sessions with that tool call in the history would fail + + // Case where no valid tool calls or content are present + msgs.push(msgWithValidToolCalls); + + // Add a tool message for each valid tool call if (validToolCalls?.length) { // If the assistant message has tool calls, we need to insert tool messages for (const toolCall of validToolCalls) { From bebc8bc71e20b2a231ef30c4cb8ff2c52394f566 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 11:15:48 -0700 Subject: [PATCH 20/57] construct message: tool messages --- core/edit/streamDiffLines.ts | 4 +- core/llm/constructMessages.ts | 104 +++++++++--------- core/llm/rules/getSystemMessageWithRules.ts | 20 ++-- gui/src/redux/slices/sessionSlice.ts | 24 +++- gui/src/redux/thunks/streamNormalInput.ts | 41 +++++-- gui/src/redux/thunks/streamResponse.ts | 57 +--------- .../thunks/streamResponseAfterToolCall.ts | 49 +-------- gui/src/redux/util/index.ts | 11 ++ gui/src/util/index.ts | 52 --------- 9 files changed, 138 insertions(+), 224 deletions(-) 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 index eb33cb413..4cb7673bf 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -2,19 +2,19 @@ import { AssistantChatMessage, ChatHistoryItem, ChatMessage, - ContextItemWithId, + ModelDescription, RuleWithSource, TextMessagePart, Tool, ToolResultChatMessage, UserChatMessage, } from "../"; -import { findLast } from "../util/findLast"; +import { findLastIndex } from "../util/findLast"; import { normalizeToMessageParts, renderContextItems, } from "../util/messageContent"; -import { chatMessageIsEmpty, isUserOrToolMsg } from "./messages"; +import { chatMessageIsEmpty } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; import { RulePolicies } from "./rules/types"; @@ -84,50 +84,30 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ ${EDIT_MESSAGE} `; -/** - * 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[], + model: ModelDescription, + availableRules: RuleWithSource[], + rulePolicies: RulePolicies, tools: Tool[], - rulePolicies?: RulePolicies, -): ChatMessage[] { +): { + messages: ChatMessage[]; + appliedRulesIndex: number; + appliedRules: RuleWithSource[]; +} { + const historyCopy = [...history]; const validTools = new Set(tools.map((tool) => tool.function.name)); const msgs: ChatMessage[] = []; - for (const item of history) { + for (const item of historyCopy) { if ( item.message.role === "system" || item.message.role === "tool" || chatMessageIsEmpty(item.message) ) { - continue; // Tool messages will be re-inserted + continue; } if (item.message.role === "user") { @@ -169,7 +149,7 @@ export function constructMessages( if (chatMessageIsEmpty(msgWithValidToolCalls)) { msgs.push({ role: "assistant", - content: "Message redacted", // TODO this might be confusing, edge case situation where tools are excluded + content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded }); } @@ -202,21 +182,41 @@ export function constructMessages( } } - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as - | UserChatMessage - | ToolResultChatMessage - | undefined; - - // Get context items for the last user message - const lastUserContextItems = getUserContextItems( - lastUserMsg, - filteredHistory, + const lastUserMsgIndex = findLastIndex( + historyCopy, + (item) => item.message.role === "user", ); - const systemMessage = getSystemMessageWithRules({ + const lastUserOrToolMsgIndex = findLastIndex( + historyCopy, + (item) => item.message.role === "user" || item.message.role === "tool", + ); + const lastUserOrToolMsg = historyCopy[lastUserOrToolMsgIndex]?.message as + | UserChatMessage + | ToolResultChatMessage; + const itemsBackToLastUserMessage = history + .slice(lastUserMsgIndex, historyCopy.length) + .filter( + (item) => item.message.role === "tool" || item.message.role === "user", + ); + const rulesContextItems = itemsBackToLastUserMessage + .map((item) => item.contextItems) + .flat(); + + // Get system message + let baseChatOrAgentSystemMessage: string | undefined; + if (messageMode === "agent") { + baseChatOrAgentSystemMessage = + model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; + } else { + baseChatOrAgentSystemMessage = + model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; + } + + const { systemMessage } = getSystemMessageWithRules({ baseSystemMessage: baseChatOrAgentSystemMessage, - rules, - userMessage: lastUserMsg, - contextItems: lastUserContextItems, + availableRules, + userMessage: lastUserOrToolMsg, + contextItems: rulesContextItems, rulePolicies, }); @@ -227,9 +227,13 @@ export function constructMessages( }); } - // Remove the "id" from all of the messages - return msgs.map((msg) => { + const messages = msgs.map((msg) => { const { id, ...rest } = msg as any; return rest; }); + return { + messages, + appliedRulesIndex: lastUserOrToolMsgIndex, + appliedRules: availableRules, + }; } diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index c005a5f92..5b7eb4865 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -327,27 +327,33 @@ 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) { + for (const rule of appliedRules) { systemMessage += `\n\n${rule.rule}`; } - return systemMessage; + return { + systemMessage, + appliedRules, + }; }; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 339369cd9..1a0ceb5c9 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -20,13 +20,16 @@ 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 { v4 as uuidv4 } from "uuid"; 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"; // 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. @@ -547,6 +550,7 @@ export const sessionSlice = createSlice({ contextItems: ContextItem[]; }>, ) => { + // Update tool call state and corresponding tool output message const toolCallState = findToolCall( state.history, action.payload.toolCallId, @@ -554,6 +558,22 @@ 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, + ); + } + // addContextItemsAtIndex({ + // index: initialHistory.length, + // contextItems: toolOutput.map((contextItem) => ({ + // ...contextItem, + // id: { + // providerTitle: "toolCall", + // itemId: toolCallId, + // }, + // })), + // }), }, cancelToolCall: ( state, diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 292c973f9..8eb319cc8 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,6 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, LLMFullCompletionOptions } from "core"; +import { LLMFullCompletionOptions } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; +import { constructMessages } from "core/llm/constructMessages"; import { ToCoreProtocol } from "core/protocol"; import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; @@ -9,6 +10,7 @@ import { abortStream, addPromptCompletionPair, setActive, + setAppliedRulesAtIndex, setInactive, setToolGenerated, streamUpdate, @@ -19,28 +21,30 @@ 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 = {}; + const chatHistory = state.session.history; + const messageMode = state.session.mode; + const rulePolicies = state.ui.ruleSettings; + const streamAborter = state.session.streamAborter; + + // 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,6 +59,23 @@ export const streamNormalInput = createAsyncThunk< }; } + // Construct messages + const { messages, appliedRules, appliedRulesIndex } = constructMessages( + messageMode, + chatHistory, + selectedChatModel, + state.config.config.rules, + rulePolicies, + toolsSupported ? activeTools : [], + ); + + dispatch( + setAppliedRulesAtIndex({ + index: appliedRulesIndex, + appliedRules: appliedRules, + }), + ); + dispatch(setActive()); // Send request diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index f7334df2b..11763a462 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,17 +1,11 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; -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 { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { - setAppliedRulesAtIndex, submitEditorAndInitAtIndex, updateHistoryItemAtIndex, } from "../slices/sessionSlice"; @@ -79,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({ @@ -95,52 +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 activeTools = selectActiveTools(state); - const toolsSupported = modelSupportsTools(selectedChatModel); - const availableTools = toolsSupported ? activeTools : []; - - const messages = constructMessages( - messageMode, - [...updatedHistory], - baseChatOrAgentSystemMessage, - applicableRules, - availableTools, - rulePolicies, - ); - posthog.capture("step run", { step_name: "User Input", params: {}, @@ -157,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 75134b951..8caf6625a 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,12 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; -import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; -import { getBaseSystemMessage } from "../../util"; -import { selectActiveTools } from "../selectors/selectActiveTools"; -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"; @@ -23,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 } @@ -42,46 +30,15 @@ export const streamResponseAfterToolCall = createAsyncThunk< await new Promise((resolve) => setTimeout(resolve, 0)); + // TODO paralell 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 activeTools = selectActiveTools(state); - const toolsSupported = modelSupportsTools(selectedChatModel); - const availableTools = toolsSupported ? activeTools : []; - - const messages = constructMessages( - messageMode, - [...updatedHistory], - baseChatOrAgentSystemMessage, - state.config.config.rules, - availableTools, - ); - - unwrapResult(await dispatch(streamNormalInput({ messages }))); + unwrapResult(await dispatch(streamNormalInput({}))); }), ); }, diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index eab18ae60..fb0f96c00 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -1,4 +1,5 @@ import { ToolCallState } from "core"; +import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice"; import { RootState } from "../store"; export function findCurrentToolCall( @@ -15,3 +16,13 @@ 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, + ); +} 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; -} From 744f2297d1682798814d0b1d92c788ac2a45d252 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 11:34:28 -0700 Subject: [PATCH 21/57] clear dangling messages logic --- .../Lump/LumpToolbar/LumpToolbar.tsx | 8 ++- .../LumpToolbar/PendingToolCallToolbar.tsx | 18 +++++-- gui/src/redux/slices/sessionSlice.ts | 37 ++++++++++---- gui/src/redux/thunks/cancelCurrentToolCall.ts | 50 ------------------- gui/src/redux/thunks/cancelStream.ts | 8 ++- 5 files changed, 51 insertions(+), 70 deletions(-) delete mode 100644 gui/src/redux/thunks/cancelCurrentToolCall.ts 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/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 1a0ceb5c9..ee8e153a2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -25,6 +25,7 @@ import { renderContextItems, } from "core/util/messageContent"; import { findUriInDirs, getUriPathBasename } from "core/util/uri"; +import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; @@ -108,19 +109,35 @@ 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 === "generated" + ) { + validAssistantMessageIdx = i; + 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 @@ -720,7 +737,7 @@ export const { submitEditorAndInitAtIndex, truncateHistoryToMessage, updateHistoryItemAtIndex, - clearLastEmptyResponse, + clearDanglingMessages, setMainEditorContentTrigger, deleteMessage, setIsGatheringContext, 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()); }, ); From 089808f1630038aa0d0b994b6b2600d4970f347d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:05:55 -0700 Subject: [PATCH 22/57] move construct messages to GUI side, fix duplicate tool calls bug --- core/config/util.ts | 2 +- core/llm/llms/index.ts | 2 +- core/tsconfig.json | 7 +- .../ToolCallDiv/toolCallStateToContextItem.ts | 5 +- gui/src/redux/slices/sessionSlice.ts | 3 +- gui/src/redux/thunks/streamNormalInput.ts | 6 +- .../src/redux/util}/constructMessages.ts | 86 +++++++++++-------- 7 files changed, 71 insertions(+), 40 deletions(-) rename {core/llm => gui/src/redux/util}/constructMessages.ts (75%) diff --git a/core/config/util.ts b/core/config/util.ts index 9128fc0b5..5cb2f6c3a 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 "../../gui/src/redux/util/constructMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 74c58e9da..1737780af 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -7,8 +7,8 @@ import { JSONModelDescription, LLMOptions, } from "../.."; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../../../gui/src/redux/util/constructMessages"; import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; diff --git a/core/tsconfig.json b/core/tsconfig.json index 69966e2de..273476b9d 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -18,6 +18,11 @@ "noEmitOnError": false, "types": ["jest", "node"] }, - "include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"], + "include": [ + "./**/*.ts", + "./**/*.js", + "./**/*.d.ts", + "../gui/src/redux/util/constructMessages.ts" + ], "exclude": ["dist"] } diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts index ccb8a7976..7a25ead3a 100644 --- a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -1,8 +1,11 @@ import { ContextItemWithId, ToolCallState } from "core"; export function toolCallStateToContextItems( - toolCallState: ToolCallState, + toolCallState: ToolCallState | undefined, ): ContextItemWithId[] { + if (!toolCallState) { + return []; + } return ( toolCallState.output?.map((item) => ({ ...item, diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index ee8e153a2..20ea7ca86 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -34,8 +34,9 @@ import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; // 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. +export type ChatMessageWithId = ChatMessage & { id: string }; export type ChatHistoryItemWithMessageId = ChatHistoryItem & { - message: ChatMessage & { id: string }; + message: ChatMessageWithId; }; type SessionState = { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 8eb319cc8..f07a11376 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -60,9 +60,13 @@ export const streamNormalInput = createAsyncThunk< } // Construct messages + const withoutMessageIds = chatHistory.map((item) => { + const { id, ...messageWithoutId } = item.message; + return { ...item, message: messageWithoutId }; + }); const { messages, appliedRules, appliedRulesIndex } = constructMessages( messageMode, - chatHistory, + withoutMessageIds, selectedChatModel, state.config.config.rules, rulePolicies, diff --git a/core/llm/constructMessages.ts b/gui/src/redux/util/constructMessages.ts similarity index 75% rename from core/llm/constructMessages.ts rename to gui/src/redux/util/constructMessages.ts index 4cb7673bf..ec0fc3cfa 100644 --- a/core/llm/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -2,27 +2,29 @@ import { AssistantChatMessage, ChatHistoryItem, ChatMessage, + ContextItemWithId, ModelDescription, RuleWithSource, TextMessagePart, Tool, ToolResultChatMessage, UserChatMessage, -} from "../"; -import { findLastIndex } from "../util/findLast"; +} from "core"; +import { chatMessageIsEmpty } from "core/llm/messages"; +import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; +import { RulePolicies } from "core/llm/rules/types"; +import { findLastIndex } from "core/util/findLast"; import { normalizeToMessageParts, renderContextItems, -} from "../util/messageContent"; -import { chatMessageIsEmpty } from "./messages"; -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -import { RulePolicies } from "./rules/types"; +} from "core/util/messageContent"; +import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; + "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; + "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; const EDIT_MESSAGE = `\ Always include the language and file name in the info string when you write code blocks. @@ -99,7 +101,10 @@ export function constructMessages( const historyCopy = [...history]; const validTools = new Set(tools.map((tool) => tool.function.name)); - const msgs: ChatMessage[] = []; + const msgs: { + ctxItems: ContextItemWithId[]; + message: ChatMessage; + }[] = []; for (const item of historyCopy) { if ( item.message.role === "system" || @@ -125,14 +130,18 @@ export function constructMessages( content = [...ctxItems, ...content]; msgs.push({ - ...item.message, - content, + ctxItems: item.contextItems, + message: { + ...item.message, + content, + }, }); - } else { - msgs.push(item.message); - } - - if (item.message.role === "assistant") { + } else if (item.message.role === "thinking") { + msgs.push({ + ctxItems: item.contextItems, + message: item.message, + }); + } else if (item.message.role === "assistant") { // First, push a version of the message with any valid tools calls const validToolCalls = item.message.toolCalls?.filter( (toolCall) => @@ -148,8 +157,11 @@ export function constructMessages( if (chatMessageIsEmpty(msgWithValidToolCalls)) { msgs.push({ - role: "assistant", - content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded + ctxItems: [], + message: { + role: "assistant", + content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded + }, }); } @@ -158,7 +170,10 @@ export function constructMessages( // Then sessions with that tool call in the history would fail // Case where no valid tool calls or content are present - msgs.push(msgWithValidToolCalls); + msgs.push({ + ctxItems: item.contextItems, + message: msgWithValidToolCalls, + }); // Add a tool message for each valid tool call if (validToolCalls?.length) { @@ -173,9 +188,12 @@ export function constructMessages( content = renderContextItems(item.toolCallState.output); } msgs.push({ - role: "tool", - content, - toolCallId: toolCall.id!, + ctxItems: toolCallStateToContextItems(item.toolCallState), + message: { + role: "tool", + content, + toolCallId: toolCall.id!, + }, }); } } @@ -183,23 +201,23 @@ export function constructMessages( } const lastUserMsgIndex = findLastIndex( - historyCopy, + msgs, (item) => item.message.role === "user", ); const lastUserOrToolMsgIndex = findLastIndex( - historyCopy, + msgs, (item) => item.message.role === "user" || item.message.role === "tool", ); - const lastUserOrToolMsg = historyCopy[lastUserOrToolMsgIndex]?.message as + const lastUserOrToolMsg = msgs[lastUserOrToolMsgIndex]?.message as | UserChatMessage | ToolResultChatMessage; - const itemsBackToLastUserMessage = history - .slice(lastUserMsgIndex, historyCopy.length) + const itemsBackToLastUserMessage = msgs + .slice(lastUserMsgIndex, msgs.length) .filter( (item) => item.message.role === "tool" || item.message.role === "user", ); const rulesContextItems = itemsBackToLastUserMessage - .map((item) => item.contextItems) + .map((item) => item.ctxItems) .flat(); // Get system message @@ -222,15 +240,15 @@ export function constructMessages( if (systemMessage.trim()) { msgs.unshift({ - role: "system", - content: systemMessage, + ctxItems: [], + message: { + role: "system", + content: systemMessage, + }, }); } - const messages = msgs.map((msg) => { - const { id, ...rest } = msg as any; - return rest; - }); + const messages = msgs.map((m) => m.message); return { messages, appliedRulesIndex: lastUserOrToolMsgIndex, From c69521fb95a9a7b8a560e34e6585308342fc281f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:14:20 -0700 Subject: [PATCH 23/57] specific file for default system messages --- core/llm/defaultSystemMessages.ts | 65 +++++++++++++++++ .../mainInput/Lump/sections/RulesSection.tsx | 2 +- gui/src/redux/thunks/streamNormalInput.ts | 2 +- gui/src/redux/util/constructMessages.ts | 70 ++----------------- 4 files changed, 71 insertions(+), 68 deletions(-) create mode 100644 core/llm/defaultSystemMessages.ts diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts new file mode 100644 index 000000000..64ea23dd0 --- /dev/null +++ b/core/llm/defaultSystemMessages.ts @@ -0,0 +1,65 @@ +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"; + +const EDIT_MESSAGE = `\ + 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' + + 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. + +${EDIT_MESSAGE} +`; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ + + You are in agent mode. + +${EDIT_MESSAGE} +`; 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/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index f07a11376..aa1744ed4 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,7 +1,6 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { LLMFullCompletionOptions } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; -import { constructMessages } from "core/llm/constructMessages"; import { ToCoreProtocol } from "core/protocol"; import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; @@ -16,6 +15,7 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { constructMessages } from "../util/constructMessages"; import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index ec0fc3cfa..f1163a3be 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -10,6 +10,10 @@ import { 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"; @@ -20,72 +24,6 @@ import { } from "core/util/messageContent"; import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; - -const EDIT_MESSAGE = `\ - 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' - - 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. - -${EDIT_MESSAGE} -`; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ - - You are in agent mode. - -${EDIT_MESSAGE} -`; - export function constructMessages( messageMode: string, history: ChatHistoryItem[], From aa962b1fa610bda612cb7652fc669e343c4d041c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:15:27 -0700 Subject: [PATCH 24/57] fix broken imports --- core/config/util.ts | 2 +- core/llm/llms/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/config/util.ts b/core/config/util.ts index 5cb2f6c3a..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 "../../gui/src/redux/util/constructMessages"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 1737780af..318e4e88f 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -7,8 +7,8 @@ import { JSONModelDescription, LLMOptions, } from "../.."; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../../../gui/src/redux/util/constructMessages"; import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; From fa1253bae54fd69c9dbe0b7ef50671dafaf7fea1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:28:02 -0700 Subject: [PATCH 25/57] agent papercuts + tool message updates - cleanup --- core/tsconfig.json | 7 +------ .../mainInput/belowMainInput/ContextItemsPeek.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 2 +- gui/src/redux/slices/sessionSlice.ts | 3 +-- gui/src/redux/thunks/streamResponseAfterToolCall.ts | 2 +- 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/core/tsconfig.json b/core/tsconfig.json index 273476b9d..69966e2de 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -18,11 +18,6 @@ "noEmitOnError": false, "types": ["jest", "node"] }, - "include": [ - "./**/*.ts", - "./**/*.js", - "./**/*.d.ts", - "../gui/src/redux/util/constructMessages.ts" - ], + "include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"], "exclude": ["dist"] } diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 31c392bf1..a77e2fc98 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -121,7 +121,7 @@ export function ContextItemsPeekItem({ data-testid="context-items-peek-item" > {getContextItemIcon()} - + {contextItem.name}
-
+
{!!toolCallState.output && ( )} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 20ea7ca86..ee8e153a2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -34,9 +34,8 @@ import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; // 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. -export type ChatMessageWithId = ChatMessage & { id: string }; export type ChatHistoryItemWithMessageId = ChatHistoryItem & { - message: ChatMessageWithId; + message: ChatMessage & { id: string }; }; type SessionState = { diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 8caf6625a..010304557 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -30,7 +30,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< await new Promise((resolve) => setTimeout(resolve, 0)); - // TODO paralell tool calls - dispatch one tool message per tool call + // TODO parallel tool calls - dispatch one tool message per tool call const newMessage: ChatMessage = { role: "tool", content: renderContextItems(toolOutput), From 2b022ad86d7ec59c368760f1fceb02a3afa058e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:38:19 -0700 Subject: [PATCH 26/57] update tool message context items in redux --- .../ToolCallDiv/toolCallStateToContextItem.ts | 25 +++++++++++++------ gui/src/redux/slices/sessionSlice.ts | 14 +++-------- gui/src/redux/util/index.ts | 1 + 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts index 7a25ead3a..b3e132cad 100644 --- a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -1,4 +1,4 @@ -import { ContextItemWithId, ToolCallState } from "core"; +import { ContextItem, ContextItemWithId, ToolCallState } from "core"; export function toolCallStateToContextItems( toolCallState: ToolCallState | undefined, @@ -7,12 +7,21 @@ export function toolCallStateToContextItems( return []; } return ( - toolCallState.output?.map((item) => ({ - ...item, - id: { - providerTitle: "toolCall", - itemId: toolCallState.toolCallId, - }, - })) ?? [] + 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 ee8e153a2..14c1d1dc9 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -27,6 +27,7 @@ import { 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"; @@ -580,17 +581,10 @@ export const sessionSlice = createSlice({ toolItem.message.content = renderContextItems( action.payload.contextItems, ); + toolItem.contextItems = action.payload.contextItems.map((item) => + toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId), + ); } - // addContextItemsAtIndex({ - // index: initialHistory.length, - // contextItems: toolOutput.map((contextItem) => ({ - // ...contextItem, - // id: { - // providerTitle: "toolCall", - // itemId: toolCallId, - // }, - // })), - // }), }, cancelToolCall: ( state, diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index fb0f96c00..825c19c09 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -8,6 +8,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, From 60aee4e36a4ad68a6dc458a8e60d5e7853050647 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:51:16 -0700 Subject: [PATCH 27/57] tweak clear dangling messages logic --- gui/src/redux/slices/sessionSlice.ts | 6 +++++- gui/src/redux/thunks/streamThunkWrapper.tsx | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 14c1d1dc9..9cc15863b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -128,9 +128,13 @@ export const sessionSlice = createSlice({ const message = state.history[i]; if ( message.message.content || - message.toolCallState?.status === "generated" + 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; } } 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)); } From fc9ef88668195a6c42edf72eff336c73ef011ca9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 18:27:02 -0700 Subject: [PATCH 28/57] merge main --- core/llm/constructMessages.ts | 187 ------------------ core/llm/defaultSystemMessages.ts | 9 +- .../belowMainInput/ContextItemsPeek.tsx | 7 +- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 51 +---- 4 files changed, 13 insertions(+), 241 deletions(-) delete mode 100644 core/llm/constructMessages.ts 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 index 64ea23dd0..c2f82bac4 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -4,10 +4,12 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; -const EDIT_MESSAGE = `\ +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: @@ -54,12 +56,13 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ 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. -${EDIT_MESSAGE} +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +${EDIT_CODE_INSTRUCTIONS} `; export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. -${EDIT_MESSAGE} +${CODEBLOCK_FORMATTING_INSTRUCTIONS} `; diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 14d44fadf..4b344ecea 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -122,13 +122,8 @@ 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" ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 + 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()} diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 059f6e20b..07c547468 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,17 +1,11 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; -<<<<<<< HEAD import { Tool, ToolCallState } from "core"; -import { ComponentType, useMemo, useState } from "react"; -import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; -======= -import { ContextItemWithId, Tool, ToolCallState } from "core"; import { ComponentType, useContext, useMemo, useState } from "react"; import { ContextItemsPeekItem, openContextItem, } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; @@ -30,18 +24,11 @@ export function SimpleToolCallUI({ tool, historyIndex, }: SimpleToolCallUIProps) { -<<<<<<< HEAD + const ideMessenger = useContext(IdeMessengerContext); const shownContextItems = useMemo(() => { const contextItems = toolCallStateToContextItems(toolCallState); return contextItems.filter((item) => !item.hidden); }, [toolCallState]); -======= - const ideMessenger = useContext(IdeMessengerContext); - - const ctxItems = useMemo(() => { - return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; - }, [contextItems]); ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 const [open, setOpen] = useState(false); const [isHovered, setIsHovered] = useState(false); @@ -51,8 +38,8 @@ export function SimpleToolCallUI({ return Object.entries(toolCallState.parsedArgs); }, [toolCallState.parsedArgs]); - const isToggleable = ctxItems.length > 1; - const isSingleItem = ctxItems.length === 1; + const isToggleable = shownContextItems.length > 1; + const isSingleItem = shownContextItems.length === 1; const shouldShowContent = isToggleable ? open : false; const isClickable = isToggleable || isSingleItem; @@ -60,7 +47,7 @@ export function SimpleToolCallUI({ if (isToggleable) { setOpen((prev) => !prev); } else if (isSingleItem) { - openContextItem(ctxItems[0], ideMessenger); + openContextItem(shownContextItems[0], ideMessenger); } } @@ -102,7 +89,6 @@ export function SimpleToolCallUI({
-<<<<<<< HEAD
{!!toolCallState.output?.length && ( @@ -116,31 +102,6 @@ export function SimpleToolCallUI({ ) : null}
- -
- {shownContextItems.length ? ( - shownContextItems.map((contextItem, idx) => ( - - )) - ) : ( -
- No tool call output -
-======= - {args.length > 0 && ( - ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 - )} -
- {isToggleable && ( @@ -149,8 +110,8 @@ export function SimpleToolCallUI({ shouldShowContent ? "max-h-[50vh] opacity-100" : "max-h-0 opacity-0" }`} > - {ctxItems.length > 0 ? ( - ctxItems.map((contextItem, idx) => ( + {shownContextItems.length > 0 ? ( + shownContextItems.map((contextItem, idx) => ( )) ) : ( From 401b3bbf502fe9ef4a9df1c3c43ffee83e0e1e0d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 18:27:27 -0700 Subject: [PATCH 29/57] fix import error --- core/tools/definitions/editFile.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 { From b6eaae62785b2d8575f1063cbbc63096f3949116 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 1 Jul 2025 08:21:41 +0530 Subject: [PATCH 30/57] fix imports --- core/config/usesFreeTrialApiKey.vitest.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/core/config/usesFreeTrialApiKey.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts index ddf9b3f83..28a8bd850 100644 --- a/core/config/usesFreeTrialApiKey.vitest.ts +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -1,5 +1,7 @@ +import { SecretType } from "@continuedev/config-yaml"; import { beforeEach, expect, test, vi } from "vitest"; import { BrowserSerializedContinueConfig } from ".."; +import { usesFreeTrialApiKey } from "./usesFreeTrialApiKey"; // Create the mock before importing anything else const mockDecodeSecretLocation = vi.fn(); @@ -14,10 +16,6 @@ vi.mock("@continuedev/config-yaml", () => ({ decodeSecretLocation: mockDecodeSecretLocation, })); -// Import after mocking -const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey"); -const { SecretType } = await import("@continuedev/config-yaml"); - beforeEach(() => { mockDecodeSecretLocation.mockReset(); }); From 5530aee9decbd6f0842b5e5255ecb6d3fc8834ad Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Tue, 1 Jul 2025 12:08:27 +0800 Subject: [PATCH 31/57] Revert "remove "deepseek" from templateSchema to adapt remove "deepseek" from TemplateType" This reverts commit 38342fa3852d52e3535b1799b9fc3a004857002e. --- packages/config-yaml/src/schemas/models.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 2ddedf794..893f7117a 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -95,7 +95,7 @@ const templateSchema = z.enum([ "chatml", "none", "openchat", - // "deepseek", + "deepseek", "xwin-coder", "neural-chat", "codellama-70b", From 38917ab3f13968c2b0cdbcf50c3305f544ac1ef6 Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Tue, 1 Jul 2025 12:17:56 +0800 Subject: [PATCH 32/57] revert change in autodetect.ts and index.d.ts --- core/index.d.ts | 2 +- core/llm/autodetect.ts | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 649eb62ef..d2792a228 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -903,7 +903,7 @@ export type TemplateType = | "chatml" | "none" | "openchat" - // | "deepseek" ---- remove this because add tool call support for deepseek models + | "deepseek" | "xwin-coder" | "neural-chat" | "codellama-70b" diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 977d2b1ea..dd65cc2d9 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -10,6 +10,7 @@ import { chatmlTemplateMessages, codeLlama70bTemplateMessages, codestralTemplateMessages, + deepseekTemplateMessages, gemmaTemplateMessage, graniteTemplateMessages, llama2TemplateMessages, @@ -186,8 +187,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("gemini") || lower.includes("grok") || lower.includes("moonshot") || - lower.includes("mercury") || - lower.includes("deepseek") + lower.includes("mercury") ) { return undefined; } @@ -248,6 +248,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return "llama2"; } + if (lower.includes("deepseek")) { + return "deepseek"; + } + if (lower.includes("ninja") || lower.includes("openchat")) { return "openchat"; } @@ -289,7 +293,7 @@ function autodetectTemplateFunction( zephyr: zephyrTemplateMessages, anthropic: anthropicTemplateMessages, chatml: chatmlTemplateMessages, - // deepseek: deepseekTemplateMessages, + deepseek: deepseekTemplateMessages, openchat: openchatTemplateMessages, "xwin-coder": xWinCoderTemplateMessages, "neural-chat": neuralChatTemplateMessages, @@ -312,7 +316,7 @@ const USES_OS_MODELS_EDIT_PROMPT: TemplateType[] = [ "alpaca", "chatml", // "codellama-70b", Doesn't respond well to this prompt - // "deepseek", + "deepseek", "gemma", "llama2", "llava", @@ -352,6 +356,8 @@ function autodetectPromptTemplates( } } else if (templateType === "alpaca") { editTemplate = alpacaEditPrompt; + } else if (templateType === "deepseek") { + editTemplate = deepseekEditPrompt; } else if (templateType === "openchat") { editTemplate = openchatEditPrompt; } else if (templateType === "xwin-coder") { From cda175830e9727bc286efff3e1cf8be939429dad Mon Sep 17 00:00:00 2001 From: QiuYang Shen <1741258352@qq.com> Date: Tue, 1 Jul 2025 12:42:18 +0800 Subject: [PATCH 33/57] add a comment linking back to the tool calling docs for deepseek --- core/llm/toolSupport.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index fba0b15f5..e0a543637 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -179,6 +179,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, deepseek: (model) => { + // https://api-docs.deepseek.com/guides/function_calling if ( model === "deepseek-reasoner" || model === "deepseek-chat" || From 287c1fac0a3b548a53211b025509ea4585704f8f Mon Sep 17 00:00:00 2001 From: Ting-Wai To Date: Mon, 30 Jun 2025 18:01:04 -0700 Subject: [PATCH 34/57] Add @codebase as experimental tool for agent mode --- core/tools/builtIn.ts | 1 + core/tools/callTool.ts | 3 ++ core/tools/definitions/codebaseTool.ts | 29 ++++++++++ core/tools/implementations/codebaseTool.ts | 61 ++++++++++++++++++++++ core/tools/index.ts | 8 ++- 5 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 core/tools/definitions/codebaseTool.ts create mode 100644 core/tools/implementations/codebaseTool.ts 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..c6e19b068 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -3,6 +3,7 @@ import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; 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,6 +165,8 @@ 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`); } 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/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]), ]; From cde9a12c4fe424ad1e7fe0e0b3858f1c88f19c8e Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 1 Jul 2025 11:11:41 +0530 Subject: [PATCH 35/57] fix dynamic imports in tests --- core/config/usesFreeTrialApiKey.vitest.ts | 650 +++++++++++----------- 1 file changed, 328 insertions(+), 322 deletions(-) diff --git a/core/config/usesFreeTrialApiKey.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts index 28a8bd850..b92dd90a2 100644 --- a/core/config/usesFreeTrialApiKey.vitest.ts +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -1,7 +1,5 @@ -import { SecretType } from "@continuedev/config-yaml"; -import { beforeEach, expect, test, vi } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; import { BrowserSerializedContinueConfig } from ".."; -import { usesFreeTrialApiKey } from "./usesFreeTrialApiKey"; // Create the mock before importing anything else const mockDecodeSecretLocation = vi.fn(); @@ -16,327 +14,335 @@ vi.mock("@continuedev/config-yaml", () => ({ decodeSecretLocation: mockDecodeSecretLocation, })); -beforeEach(() => { - mockDecodeSecretLocation.mockReset(); -}); +describe("usesFreeTrialApiKey", () => { + let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey; + let SecretType: typeof 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"); + beforeEach(async () => { + mockDecodeSecretLocation.mockReset(); + usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey")) + .usesFreeTrialApiKey; + SecretType = (await import("@continuedev/config-yaml")).SecretType; }); - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(consoleSpy).toHaveBeenCalledWith( - "Error checking for free trial API key:", - expect.any(Error), - ); + test("usesFreeTrialApiKey should return false when config is null", () => { + const result = usesFreeTrialApiKey(null); + expect(result).toBe(false); + }); - 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(); + 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(); + }); }); From 6e3d42e80e9ccf4ee78e930315fc2770901d3dec Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 01:57:41 -0700 Subject: [PATCH 36/57] update message cancelaltion and rejection logic --- gui/src/components/AcceptRejectDiffButtons.tsx | 15 ++++++++++++++- gui/src/components/mainInput/InputToolbar.tsx | 14 +------------- gui/src/hooks/ParallelListeners.tsx | 11 +++++------ gui/src/pages/gui/Chat.tsx | 2 +- .../pages/gui/ToolCallDiv/SimpleToolCallUI.tsx | 2 +- gui/src/redux/util/constructMessages.ts | 4 +++- 6 files changed, 25 insertions(+), 23 deletions(-) diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index a19b56068..9420fc551 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,18 @@ 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 (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/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/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 126c4e894..a965f9559 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -319,7 +319,7 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : item.message.role === + ) : item.message.role === "tool" ? null : item.message.role === // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // +
Date: Tue, 1 Jul 2025 17:00:54 +0800 Subject: [PATCH 37/57] consider more --- core/llm/toolSupport.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index e0a543637..c74b6c564 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -179,12 +179,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, deepseek: (model) => { + // https://api-docs.deepseek.com/quick_start/pricing // https://api-docs.deepseek.com/guides/function_calling - if ( - model === "deepseek-reasoner" || - model === "deepseek-chat" || - model === "deepseek-coder" - ) { + if (model === "deepseek-reasoner" || model === "deepseek-chat") { return true; } From 0dca48ccf93e5bc469ece4c648b23779c244dfa4 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 1 Jul 2025 16:11:55 +0530 Subject: [PATCH 38/57] add telemetry for context providers --- core/context/providers/index.ts | 10 +++++++++- core/core.ts | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) 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/core.ts b/core/core.ts index 9896411ee..2cb6b8c3f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1105,6 +1105,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, From 7fae1485eac810e4471e6d62226c9013831ab1d3 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Tue, 1 Jul 2025 15:32:25 +0200 Subject: [PATCH 39/57] build: Simplify runIde args --- extensions/intellij/build.gradle.kts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) 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 { From 8fb7a3fa198d3974a11e0c822ce7dca6a4736c50 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Tue, 1 Jul 2025 16:12:32 +0200 Subject: [PATCH 40/57] feat: Attach thread dumps to Sentry events Also: add exception messages (like "Access is allowed from event dispatch thread only") --- .../error/ContinueErrorSubmitter.kt | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) 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..245d62658 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 @@ -8,6 +8,8 @@ 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.Attachment +import io.sentry.Hint import io.sentry.Sentry import io.sentry.SentryEvent import io.sentry.protocol.Message @@ -34,12 +36,9 @@ 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 + reportToSentry(event, additionalInfo) } catch (_: Exception) { consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED)) return false @@ -48,8 +47,18 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { return true } + private fun reportToSentry(event: IdeaReportingEvent, additionalInfo: String?) { + val sentryEvent = SentryEvent() + sentryEvent.throwable = event.data.throwable + sentryEvent.message = Message().apply { message = additionalInfo ?: event.data.message } + val hint = Hint.withAttachments(event.data.allAttachments.map { Attachment(it.bytes, it.path) }) + sentryEvent.setTag("plugin_version", event.plugin?.version) + Sentry.captureEvent(sentryEvent, hint) + } + private companion object { - private const val SENTRY_DSN = "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" + private const val SENTRY_DSN = + "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" } } From 1603e8d4b544618cd170208c35a6734ac0148a0d Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Tue, 1 Jul 2025 18:47:01 +0200 Subject: [PATCH 41/57] feat: Report ignored exceptions --- .../continue/IdeProtocolClient.kt | 7 ++- .../continue/IntelliJIde.kt | 25 ++++------ .../error/ContinueErrorService.kt | 50 +++++++++++++++++++ .../error/ContinueErrorSubmitter.kt | 32 +++--------- 4 files changed, 73 insertions(+), 41 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt 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..460257f6c 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.* @@ -463,8 +464,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..d6fcee0a1 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 @@ -38,9 +37,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, @@ -344,11 +341,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 +382,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/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" - } - } From bfb97a6415a0618e829651d946cf2accd4e54f4e Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Tue, 1 Jul 2025 19:20:10 +0200 Subject: [PATCH 42/57] fix: Read virtual files on EDT (getOpenFiles, getCurrentFile) --- .../continue/IntelliJIde.kt | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) 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..99381dae4 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,8 @@ 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.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.* @@ -11,7 +10,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 +17,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 +37,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 +294,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 From b4a2ad8af7390ca4bfd0381d3ee98ed4696c0514 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 1 Jul 2025 10:26:24 -0700 Subject: [PATCH 43/57] moved logToolUsage to outside thunk --- extensions/vscode/package-lock.json | 8 ++++---- gui/package-lock.json | 11 ++++++++--- gui/src/redux/thunks/callCurrentTool.ts | 21 +++------------------ gui/src/redux/util/index.ts | 24 +++++++++++++++++++++++- packages/config-yaml/package-lock.json | 4 ++-- 5 files changed, 40 insertions(+), 28 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 9ebbad2d0..29de81832 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.50", + "version": "1.1.52", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.50", + "version": "1.1.52", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -108,9 +108,9 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.13", + "@continuedev/fetch": "^1.0.14", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "file:../packages/openai-adapters", + "@continuedev/openai-adapters": "1.0.42", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/gui/package-lock.json b/gui/package-lock.json index 62eea45da..5cbf9ede7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -114,9 +114,9 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.13", + "@continuedev/fetch": "^1.0.14", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "file:../packages/openai-adapters", + "@continuedev/openai-adapters": "1.0.42", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -215,7 +215,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.94", + "version": "1.0.95", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -226,10 +226,15 @@ "config-yaml": "dist/cli.js" }, "devDependencies": { + "@semantic-release/changelog": "^6.0.3", + "@semantic-release/git": "^10.0.1", + "@semantic-release/github": "^9.2.6", + "@semantic-release/npm": "^10.0.6", "@types/jest": "^29.5.14", "@types/node": "^20.0.0", "cross-env": "^7.0.3", "jest": "^29.7.0", + "semantic-release": "^21.1.2", "ts-jest": "^29.2.3", "ts-node": "^10.9.2", "zod-to-json-schema": "^3.24.5" diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index 4b76c7201..997b01225 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -1,7 +1,6 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ContextItem } from "core"; import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn"; -import { safeParseToolCallArgs } from "core/tools/parseArgs"; import posthog from "posthog-js"; import { callClientTool } from "../../util/clientTools/callClientTool"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; @@ -13,6 +12,7 @@ import { updateToolCallOutput, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { logToolUsage } from "../util"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; export const callCurrentTool = createAsyncThunk( @@ -29,21 +29,6 @@ export const callCurrentTool = createAsyncThunk( return; } - const logToolUsage = (success: boolean, finalOutput?: ContextItem[]) => { - extra.ideMessenger.post("devdata/log", { - name: "toolUsage", - data: { - toolCallId: toolCallState.toolCallId, - functionName: toolCallState.toolCall?.function?.name, - functionArgs: toolCallState.toolCall?.function?.arguments, - toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), - parsedArgs: toolCallState.parsedArgs, - output: finalOutput || toolCallState.output || [], - succeeded: success, - }, - }); - }; - const selectedChatModel = selectSelectedChatModel(state); if (!selectedChatModel) { @@ -122,7 +107,7 @@ export const callCurrentTool = createAsyncThunk( }), ); - logToolUsage(false, output); + logToolUsage(toolCallState, false, extra.ideMessenger, output); } else if (output?.length) { dispatch( updateToolCallOutput({ @@ -131,7 +116,7 @@ export const callCurrentTool = createAsyncThunk( }), ); - logToolUsage(true, 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/util/index.ts b/gui/src/redux/util/index.ts index eab18ae60..175b304c1 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -1,4 +1,6 @@ -import { ToolCallState } from "core"; +import { ContextItem, ToolCallState } from "core"; +import { safeParseToolCallArgs } from "core/tools/parseArgs"; +import { IIdeMessenger } from "../../context/IdeMessenger"; import { RootState } from "../store"; export function findCurrentToolCall( @@ -15,3 +17,23 @@ export function findToolCall( (item) => item.toolCallState?.toolCallId === toolCallId, )?.toolCallState; } + +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), + parsedArgs: toolCallState.parsedArgs, + output: finalOutput || toolCallState.output || [], + succeeded: success, + }, + }); +} diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 7f2b8b2f2..014ecac95 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.94", + "version": "1.0.95", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.94", + "version": "1.0.95", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From 30d8b14d58a3457f7a9981355b52527c1fc59949 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 1 Jul 2025 10:47:10 -0700 Subject: [PATCH 44/57] removed toolCallCompleted message --- core/core.ts | 6 ----- core/protocol/webview.ts | 4 ---- core/tools/callTool.ts | 23 ++++++++++++++++++++ gui/src/hooks/ParallelListeners.tsx | 29 ------------------------- gui/src/redux/thunks/callCurrentTool.ts | 2 ++ 5 files changed, 25 insertions(+), 39 deletions(-) diff --git a/core/core.ts b/core/core.ts index 71451de51..22719d5e6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -821,12 +821,6 @@ export class Core { codeBaseIndexer: this.codeBaseIndexer, }); - this.messenger.send("toolCallCompleted", { - toolCallId: toolCall.id, - contextItems: result.contextItems, - succeeded: !result.errorMessage, - }); - return result; } diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 524975031..1a8d40313 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -43,9 +43,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { "jetbrains/setColors": [Record, void]; sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; - toolCallCompleted: [ - { toolCallId: string; contextItems: any[]; succeeded: boolean }, - void, - ]; freeTrialExceeded: [undefined, void]; }; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 40dd7abe2..c1510713e 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,5 +1,6 @@ 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"; @@ -169,6 +170,26 @@ async function callBuiltInTool( } } +function logToolUsage( + toolCall: ToolCall, + args: Record, + contextItems: ContextItem[], + success: boolean, +) { + void DataLogger.getInstance().logDevData({ + name: "toolUsage", + data: { + toolCallId: toolCall.id, + functionName: toolCall.function.name, + functionArgs: toolCall.function.arguments, + toolCallArgs: args, + parsedArgs: 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 +211,7 @@ export async function callTool( item.icon = tool.faviconUrl; }); } + logToolUsage(toolCall, args, contextItems, true); return { contextItems, errorMessage: undefined, @@ -199,6 +221,7 @@ export async function callTool( if (e instanceof Error) { errorMessage = e.message; } + logToolUsage(toolCall, {}, [], false); return { contextItems: [], errorMessage, diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 2036dc365..5bf2c977a 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -27,13 +27,10 @@ import { setTTSActive } from "../redux/slices/uiSlice"; import { exitEdit } from "../redux/thunks/edit"; import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall"; -import { safeParseToolCallArgs } from "core/tools/parseArgs"; -import { store } from "../redux/store"; import { cancelStream } from "../redux/thunks/cancelStream"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; -import { findToolCall } from "../redux/util"; import { setDocumentStylesFromLocalStorage, setDocumentStylesFromTheme, @@ -288,32 +285,6 @@ function ParallelListeners() { [currentToolCallApplyState, history], ); - useWebviewListener( - "toolCallCompleted", - async (data) => { - const state = store.getState(); - const toolCallState = findToolCall( - state.session.history, - data.toolCallId, - ); - if (toolCallState) { - ideMessenger.post("devdata/log", { - name: "toolUsage", - data: { - toolCallId: toolCallState.toolCallId, - functionName: toolCallState.toolCall.function.name, - functionArgs: toolCallState.toolCall.function.arguments, - toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), - parsedArgs: toolCallState.parsedArgs, - output: data.contextItems, - succeeded: data.succeeded, - }, - }); - } - }, - [ideMessenger, store], - ); - useEffect(() => { if (!isInEdit) { dispatch(setLastNonEditSessionEmpty(history.length === 0)); diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index 997b01225..7e8ff9ab1 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -107,6 +107,7 @@ export const callCurrentTool = createAsyncThunk( }), ); + console.log("logging Tool from callCurrentTool"); logToolUsage(toolCallState, false, extra.ideMessenger, output); } else if (output?.length) { dispatch( @@ -116,6 +117,7 @@ export const callCurrentTool = createAsyncThunk( }), ); + console.log("logging Tool from callCurrentTool"); logToolUsage(toolCallState, true, extra.ideMessenger, output); } From b0902368f444fa24413d756a94459da824a6ef22 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 1 Jul 2025 10:50:48 -0700 Subject: [PATCH 45/57] remove console logs --- gui/src/redux/thunks/callCurrentTool.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index 7e8ff9ab1..997b01225 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -107,7 +107,6 @@ export const callCurrentTool = createAsyncThunk( }), ); - console.log("logging Tool from callCurrentTool"); logToolUsage(toolCallState, false, extra.ideMessenger, output); } else if (output?.length) { dispatch( @@ -117,7 +116,6 @@ export const callCurrentTool = createAsyncThunk( }), ); - console.log("logging Tool from callCurrentTool"); logToolUsage(toolCallState, true, extra.ideMessenger, output); } From 100dce546185eee7e14b36f30661406abf55ddfb Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 1 Jul 2025 10:51:20 -0700 Subject: [PATCH 46/57] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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" From 517f439c666e12039fe07aa7cdc74f2d2280f2fb Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 1 Jul 2025 11:20:42 -0700 Subject: [PATCH 47/57] fix type errors --- packages/config-yaml/src/schemas/data/index.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) 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, }, }, }; From c31c1ed887c88c978e27a33cc695a3d025547c39 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 12:23:39 -0700 Subject: [PATCH 48/57] revert mode select fix for simplification (opened another PR) --- gui/src/components/ModeSelect/ModeSelect.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 8989583ff..a5792d721 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -34,9 +34,7 @@ export function ModeSelect() { const cycleMode = useCallback(() => { dispatch(setMode(mode === "chat" ? "agent" : "chat")); - if (!document.activeElement?.classList.contains("ProseMirror")) { - mainEditor?.commands.focus(); - } + mainEditor?.commands.focus(); }, [mode, mainEditor]); const selectMode = useCallback( From eb7a5b63d50c5fd220ef3b0d969449e72d093ba0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 12:40:46 -0700 Subject: [PATCH 49/57] move the tool truncation icon to a different PR --- gui/src/components/mainInput/icons.ts | 2 - gui/src/pages/gui/Chat.tsx | 3 +- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 48 ++++++++----------- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 22 +++------ .../ToolCallDiv/ToolTruncateHistoryIcon.tsx | 40 ---------------- gui/src/pages/gui/ToolCallDiv/index.tsx | 11 +++-- gui/src/redux/slices/sessionSlice.ts | 23 --------- 7 files changed, 38 insertions(+), 111 deletions(-) delete mode 100644 gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx diff --git a/gui/src/components/mainInput/icons.ts b/gui/src/components/mainInput/icons.ts index 62d69e65b..d8d04cc83 100644 --- a/gui/src/components/mainInput/icons.ts +++ b/gui/src/components/mainInput/icons.ts @@ -18,7 +18,6 @@ import { PlusIcon, SparklesIcon, TrashIcon, - WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { DiscordIcon } from "../svg/DiscordIcon"; import { GithubIcon } from "../svg/GithubIcon"; @@ -56,5 +55,4 @@ export const NAMED_ICONS: { [key: string]: any } = { "gitlab-mr": GitlabIcon, http: GlobeAltIcon, trash: TrashIcon, - toolCall: WrenchScrewdriverIcon, }; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index a965f9559..fb75d200c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -319,7 +319,7 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : item.message.role === // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // ); diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 644638309..4a44a8ef3 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,5 +1,5 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { Tool, ToolCallState } from "core"; +import { ContextItemWithId, Tool, ToolCallState } from "core"; import { ComponentType, useContext, useMemo, useState } from "react"; import { ContextItemsPeekItem, @@ -7,28 +7,26 @@ import { } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; -import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; -import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; tool: Tool | undefined; + contextItems: ContextItemWithId[]; icon?: ComponentType>; - historyIndex: number; } export function SimpleToolCallUI({ + contextItems, icon: Icon, toolCallState, tool, - historyIndex, }: SimpleToolCallUIProps) { const ideMessenger = useContext(IdeMessengerContext); - const shownContextItems = useMemo(() => { - const contextItems = toolCallStateToContextItems(toolCallState); - return contextItems.filter((item) => !item.hidden); - }, [toolCallState]); + + const ctxItems = useMemo(() => { + return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; + }, [contextItems]); const [open, setOpen] = useState(false); const [isHovered, setIsHovered] = useState(false); @@ -38,8 +36,8 @@ export function SimpleToolCallUI({ return Object.entries(toolCallState.parsedArgs); }, [toolCallState.parsedArgs]); - const isToggleable = shownContextItems.length > 1; - const isSingleItem = shownContextItems.length === 1; + const isToggleable = ctxItems.length > 1; + const isSingleItem = ctxItems.length === 1; const shouldShowContent = isToggleable ? open : false; const isClickable = isToggleable || isSingleItem; @@ -47,7 +45,7 @@ export function SimpleToolCallUI({ if (isToggleable) { setOpen((prev) => !prev); } else if (isSingleItem) { - openContextItem(shownContextItems[0], ideMessenger); + openContextItem(ctxItems[0], ideMessenger); } } @@ -73,7 +71,7 @@ export function SimpleToolCallUI({ } return ( -
+
-
- {!!toolCallState.output?.length && ( - - )} - {args.length > 0 ? ( - - ) : null} -
+ {args.length > 0 && ( + + )}
+ {isToggleable && ( @@ -110,8 +104,8 @@ export function SimpleToolCallUI({ shouldShowContent ? "max-h-[50vh] opacity-100" : "max-h-0 opacity-0" }`} > - {shownContextItems.length > 0 ? ( - shownContextItems.map((contextItem, idx) => ( + {ctxItems.length > 0 ? ( + ctxItems.map((contextItem, idx) => ( )) ) : ( diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 956ef791b..dcfd186c7 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -2,14 +2,12 @@ import { Tool, ToolCallState } from "core"; import { useMemo, useState } from "react"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; -import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface ToolCallDisplayProps { children: React.ReactNode; icon: React.ReactNode; tool: Tool | undefined; toolCallState: ToolCallState; - historyIndex: number; } export function ToolCallDisplay({ @@ -17,7 +15,6 @@ export function ToolCallDisplay({ toolCallState, children, icon, - historyIndex, }: ToolCallDisplayProps) { const [argsExpanded, setArgsExpanded] = useState(false); @@ -42,18 +39,13 @@ export function ToolCallDisplay({ toolCallState={toolCallState} />
-
- {!!toolCallState.output && ( - - )} - {!!args.length ? ( - - ) : null} -
+ {!!args.length ? ( + + ) : null}
{argsExpanded && !!args.length && ( diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx deleted file mode 100644 index e4f0a1cc8..000000000 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { BarsArrowUpIcon } from "@heroicons/react/24/outline"; -import { chatMessageIsEmpty } from "core/llm/messages"; -import { findLastIndex } from "core/util/findLast"; -import { useMemo } from "react"; -import { useMainEditor } from "../../../components/mainInput/TipTapEditor"; -import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { truncateHistoryToMessage } from "../../../redux/slices/sessionSlice"; - -export function ToolTruncateHistoryIcon({ - historyIndex, -}: { - historyIndex: number; -}) { - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const history = useAppSelector((state) => state.session.history); - const lastMessageIndex = useMemo(() => { - return findLastIndex(history, (item) => !chatMessageIsEmpty(item.message)); - }, [history]); - const dispatch = useAppDispatch(); - const { mainEditor } = useMainEditor(); - if (isStreaming || historyIndex === lastMessageIndex) { - return null; - } - return ( - { - dispatch( - truncateHistoryToMessage({ - index: historyIndex, - }), - ); - mainEditor?.commands.focus(); - }} - > - - - ); -} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 4141631bb..9f867356e 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -12,7 +12,12 @@ import { PencilIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { ToolCallDelta, ToolCallState, ToolStatus } from "core"; +import { + ContextItemWithId, + ToolCallDelta, + ToolCallState, + ToolStatus, +} from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { ComponentType, useMemo } from "react"; import { vscButtonBackground } from "../../../components"; @@ -25,6 +30,7 @@ import { ToolCallDisplay } from "./ToolCall"; interface ToolCallDivProps { toolCall: ToolCallDelta; toolCallState: ToolCallState; + output?: ContextItemWithId[]; historyIndex: number; } @@ -80,7 +86,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={ props.toolCallState.status === "generated" ? ArrowRightIcon : icon } - historyIndex={props.historyIndex} + contextItems={props.output ?? []} /> ); } @@ -90,7 +96,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={getStatusIcon(props.toolCallState.status)} tool={tool} toolCallState={props.toolCallState} - historyIndex={props.historyIndex} > , - ) => { - const { index } = payload; - - if (state.history.length && index < state.history.length) { - state.codeBlockApplyStates.curIndex = 0; - state.history = state.history.slice(0, index + 1).concat({ - message: { - id: uuidv4(), - role: "assistant", - content: "", // IMPORTANT - this is subsequently updated by response streaming - }, - contextItems: [], - }); - } - }, submitEditorAndInitAtIndex: ( state, { @@ -733,7 +711,6 @@ export const { addPromptCompletionPair, setActive, submitEditorAndInitAtIndex, - truncateHistoryToMessage, updateHistoryItemAtIndex, clearDanglingMessages, setMainEditorContentTrigger, From ecca042749a1892de076b0fcf7aa16cdb665e8c9 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 1 Jul 2025 13:47:43 -0700 Subject: [PATCH 50/57] hotfix to add query --- .../mainInput/TipTapEditor/utils/processEditorContent.ts | 1 + 1 file changed, 1 insertion(+) 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; From 6b0c022fd93e80530d574bc0345628b933b47b55 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 16:10:10 -0700 Subject: [PATCH 51/57] constructMessages tests --- core/llm/rules/getSystemMessageWithRules.ts | 5 +- gui/src/redux/thunks/streamNormalInput.ts | 37 +- gui/src/redux/util/constructMessages.test.ts | 734 +++++++++++++++++++ gui/src/redux/util/constructMessages.ts | 113 +-- 4 files changed, 789 insertions(+), 100 deletions(-) create mode 100644 gui/src/redux/util/constructMessages.test.ts diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 5b7eb4865..f017f24fd 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -349,7 +349,10 @@ export const getSystemMessageWithRules = ({ let systemMessage = baseSystemMessage ?? ""; for (const rule of appliedRules) { - systemMessage += `\n\n${rule.rule}`; + if (systemMessage) { + systemMessage += "\n\n"; + } + systemMessage += rule.rule; } return { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index aa1744ed4..4dc78adaa 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -15,7 +15,10 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { constructMessages } from "../util/constructMessages"; +import { + constructMessages, + getBaseSystemMessage, +} from "../util/constructMessages"; import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< @@ -34,11 +37,6 @@ export const streamNormalInput = createAsyncThunk< throw new Error("No chat model selected"); } - const chatHistory = state.session.history; - const messageMode = state.session.mode; - const rulePolicies = state.ui.ruleSettings; - const streamAborter = state.session.streamAborter; - // Get tools const activeTools = selectActiveTools(state); const toolsSupported = modelSupportsTools(selectedChatModel); @@ -59,41 +57,46 @@ export const streamNormalInput = createAsyncThunk< }; } - // Construct messages - const withoutMessageIds = chatHistory.map((item) => { + // 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, appliedRulesIndex } = constructMessages( - messageMode, + const { messages, appliedRules } = constructMessages( withoutMessageIds, - selectedChatModel, + baseSystemMessage, state.config.config.rules, - rulePolicies, - toolsSupported ? activeTools : [], + 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: appliedRulesIndex, + index: messages.length - 1, 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/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 index 811b92c46..419e9af64 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -5,7 +5,6 @@ import { ModelDescription, RuleWithSource, TextMessagePart, - Tool, ToolResultChatMessage, UserChatMessage, } from "core"; @@ -16,31 +15,30 @@ import { import { chatMessageIsEmpty } from "core/llm/messages"; import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; import { RulePolicies } from "core/llm/rules/types"; -import { findLastIndex } from "core/util/findLast"; +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( - messageMode: string, history: ChatHistoryItem[], - model: ModelDescription, + baseSystemMessage: string | undefined, availableRules: RuleWithSource[], rulePolicies: RulePolicies, - tools: Tool[], ): { messages: ChatMessage[]; - appliedRulesIndex: number; appliedRules: RuleWithSource[]; } { const historyCopy = [...history]; - const validTools = new Set(tools.map((tool) => tool.function.name)); const msgs: MessageWithContextItems[] = []; for (const item of historyCopy) { @@ -57,7 +55,7 @@ export function constructMessages( // Gather context items for user messages let content = normalizeToMessageParts(item.message); - const ctxItems = item.contextItems + const ctxItemParts = item.contextItems .map((ctxItem) => { return { type: "text", @@ -66,7 +64,7 @@ export function constructMessages( }) .filter((part) => !!part.text.trim()); - content = [...ctxItems, ...content]; + content = [...ctxItemParts, ...content]; msgs.push({ ctxItems: item.contextItems, message: { @@ -80,42 +78,19 @@ export function constructMessages( message: item.message, }); } else if (item.message.role === "assistant") { - // This was implemented for APIs that require all tool calls to have - // A corresponsing tool sent, which means if a user excluded a tool - // Then sessions with that tool call in the history would fail - - // // First, push a version of the message with any valid tools calls - // const validToolCalls = item.message.toolCalls?.filter( - // (toolCall) => - // toolCall.function?.name && - // toolCall.id && - // validTools.has(toolCall.function.name), - // ); - - // const msgWithValidToolCalls: AssistantChatMessage = { - // ...item.message, - // toolCalls: validToolCalls, - // }; - - // if (chatMessageIsEmpty(msgWithValidToolCalls)) { - // msgs.push(...getChatSafeMessagesFromAgentToolCall(item)); - // } - - // Case where no valid tool calls or content are present msgs.push({ ctxItems: item.contextItems, message: item.message, }); - // Add a tool message for each valid tool call - // if(validToolCalls?.length) { + // 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 output"; - // TODO toolCallState only supports one tool call per message for now + 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 = "The user cancelled this tool call."; + content = CANCELLED_TOOL_CALL_MESSAGE; } else if ( item.toolCallState?.toolCallId === toolCall.id && item.toolCallState?.output @@ -135,17 +110,17 @@ export function constructMessages( } } + // 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 lastUserOrToolMsgIndex = findLastIndex( - msgs, - (item) => item.message.role === "user" || item.message.role === "tool", - ); - const lastUserOrToolMsg = msgs[lastUserOrToolMsgIndex]?.message as - | UserChatMessage - | ToolResultChatMessage; const itemsBackToLastUserMessage = msgs .slice(lastUserMsgIndex, msgs.length) .filter( @@ -155,18 +130,8 @@ export function constructMessages( .map((item) => item.ctxItems) .flat(); - // Get system message - let baseChatOrAgentSystemMessage: string | undefined; - if (messageMode === "agent") { - baseChatOrAgentSystemMessage = - model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; - } else { - baseChatOrAgentSystemMessage = - model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; - } - - const { systemMessage } = getSystemMessageWithRules({ - baseSystemMessage: baseChatOrAgentSystemMessage, + const { systemMessage, appliedRules } = getSystemMessageWithRules({ + baseSystemMessage, availableRules, userMessage: lastUserOrToolMsg, contextItems: rulesContextItems, @@ -186,33 +151,17 @@ export function constructMessages( const messages = msgs.map((m) => m.message); return { messages, - appliedRulesIndex: lastUserOrToolMsgIndex, - appliedRules: availableRules, + appliedRules, }; } -// function getChatSafeMessagesFromAgentToolCall(item: ChatHistoryItem): MessageWithContextItems[] { -// if(item.message.role !== "assistant" || !item.message.toolCalls?.length) { -// console.error("Misusing getChatSafeMessagesFromAgentToolCall") -// return [] -// } -// const assistantItem: MessageWithContextItems = { -// ctxItems: item.toolCallState?.output ?? [], -// message: { -// role: "assistant", -// content: item.message.content + "\n\n" + item.message.toolCalls.map(tc => tc.function.name).join(", ") -// } -// } -// const userItem: MessageWithContextItems = { -// ctxItems: item.toolCallState?.output, -// message: { -// role: "user", -// content: item.message.content, -// } -// return [item, userItem] - -// if(message) - -// const msgs: MessageWithContextItems[] = []; -// if (message.message.role === "assistant" && message.message.toolCalls) { -// } +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; + } +} From fc0f9e3042cacd6bc925df758efdaf3e2867a7ac Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 17:31:38 -0700 Subject: [PATCH 52/57] bedrock message conversions --- core/llm/llms/Bedrock.ts | 335 +++++++++++++++++++++------------------ 1 file changed, 184 insertions(+), 151 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 371713905..5b9895c06 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,25 +376,75 @@ class Bedrock extends BaseLLM { }; } - private _convertMessage( - message: ChatMessage, - addCaching: boolean = false, - ): Message | null { - // Handle system messages explicitly - if (message.role === "system") { - return null; + private _convertMessages( + messages: ChatMessage[], + availableTools: Set, + ): Message[] { + const nonSystemMessages = messages.filter((m) => m.role !== "system"); + + const lastTwoUserMsgIndices: number[] = []; + for (let i = nonSystemMessages.length - 1; i >= 0; i--) { + if (nonSystemMessages[i].role === "user") { + lastTwoUserMsgIndices.push(i); + if (lastTwoUserMsgIndices.length === 2) { + break; + } + } } - const cachePoint = addCaching - ? { cachePoint: { type: "default" } } - : undefined; + let currentRole: "user" | "assistant" = "user"; + let currentBlocks: ContentBlock[] = []; + let addCachePoint = false; - // Tool response handling - if (message.role === "tool") { - return { - role: "user", - 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`, + ); + } + if (currentBlocks.length > 0) { + if (addCachePoint) { + currentBlocks.push({ cachePoint: { type: "default" } }); + } + converted.push({ + role: currentRole, + content: currentBlocks, + }); + } + // Change roles and reset + currentBlocks = []; + addCachePoint = false; + }; + + for (let idx = 0; idx < nonSystemMessages.length; idx++) { + const message = nonSystemMessages[idx]; + if (message.role === "user" || message.role === "tool") { + pushCurrentMessage(); + currentRole = ConversationRole.USER; + + if (message.role === "user") { + if (message.content) { + // 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 messageIsCached = !!( + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(idx) + ); + if (messageIsCached) { + addCachePoint = true; + } + currentBlocks.push( + ...this._convertMessageContentToBlocks( + message.content, + messageIsCached, + ), + ); + } + } else if (message.role === "tool") { + currentBlocks.push({ toolResult: { toolUseId: message.toolCallId, content: [ @@ -395,140 +453,115 @@ class Bedrock extends BaseLLM { }, ], }, - }, - ], - }; - } - - // 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], - }; + pushCurrentMessage(); + currentRole = ConversationRole.ASSISTANT; + + if (message.role === "assistant") { + if (message.content) { + currentBlocks.push( + ...this._convertMessageContentToBlocks(message.content, false), + ); + } + if (message.toolCalls) { + for (const toolCall of message.toolCalls) { + if (availableTools.has(toolCall.function?.name || "")) { + currentBlocks.push({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function?.name, + input: safeParseToolCallArgs(toolCall), + }, + }); + } else { + console.warn( + `Tool ${toolCall.function?.name} is not available for this model.`, + ); + } + } + } + } else if (message.role === "thinking") { + 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); + } + } } } - // Standard text message - if (typeof message.content === "string") { - if (addCaching) { - message.content += getSecureID(); - } - const content: any[] = [{ text: message.content }]; - if (addCaching) { - content.push({ cachePoint: { type: "default" } }); - } - return { - role: message.role, - content, - }; - } + return converted; + } - // Improved multimodal content handling - if (Array.isArray(message.content)) { - const content: any[] = []; - - // Process all parts first - message.content.forEach((part) => { + private _convertMessageContentToBlocks( + content: MessageContent, + addCaching: boolean, + ): ContentBlock[] { + const blocks: ContentBlock[] = []; + if (typeof content === "string") { + let contentText = content; + if (addCaching) { + contentText += getSecureID(); + } + blocks.push({ text: contentText }); + if (addCaching) { + blocks.push({ cachePoint: { type: "default" } }); + } + } else { + for (const part of content) { if (part.type === "text") { if (addCaching) { part.text += getSecureID(); } - content.push({ text: part.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() { From c2e8905cbffd2dadd4e0bcfabc8532188eb17154 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 1 Jul 2025 17:33:42 -0700 Subject: [PATCH 53/57] removing functionally redundant items in dev data toolusage --- core/tools/callTool.ts | 2 +- gui/package-lock.json | 2 +- gui/src/redux/util/index.ts | 1 - packages/config-yaml/src/schemas/data/toolUsage/index.ts | 1 - packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts | 3 +-- 5 files changed, 3 insertions(+), 6 deletions(-) diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index c1510713e..e072f1c0b 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -176,6 +176,7 @@ function logToolUsage( contextItems: ContextItem[], success: boolean, ) { + console.log(toolCall.function.arguments); void DataLogger.getInstance().logDevData({ name: "toolUsage", data: { @@ -183,7 +184,6 @@ function logToolUsage( functionName: toolCall.function.name, functionArgs: toolCall.function.arguments, toolCallArgs: args, - parsedArgs: args, output: contextItems, succeeded: success, }, diff --git a/gui/package-lock.json b/gui/package-lock.json index 08583a0d8..8c53ca7ce 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -116,7 +116,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.14", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "1.0.42", + "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index 175b304c1..8a14d4d18 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -31,7 +31,6 @@ export function logToolUsage( functionName: toolCallState.toolCall?.function?.name, functionArgs: toolCallState.toolCall?.function?.arguments, toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), - parsedArgs: toolCallState.parsedArgs, output: finalOutput || toolCallState.output || [], succeeded: success, }, diff --git a/packages/config-yaml/src/schemas/data/toolUsage/index.ts b/packages/config-yaml/src/schemas/data/toolUsage/index.ts index 225b5c0ab..5e30b354b 100644 --- a/packages/config-yaml/src/schemas/data/toolUsage/index.ts +++ b/packages/config-yaml/src/schemas/data/toolUsage/index.ts @@ -6,7 +6,6 @@ export const toolUsageEventAllSchema = baseDevDataAllSchema.extend({ functionName: z.string(), functionArgs: z.string(), toolCallArgs: z.any(), - parsedArgs: 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 index c1045104a..d77c34b51 100644 --- a/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts @@ -14,7 +14,6 @@ export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({ functionName: true, functionArgs: true, toolCallArgs: true, - parsedArgs: true, succeeded: true, output: true, }); @@ -22,6 +21,6 @@ export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({ export const toolUsageEventSchema_0_2_0_noCode = toolUsageEventSchema_0_2_0.omit({ functionArgs: true, - parsedArgs: true, + toolCallArgs: true, output: true, }); From 4789babdbb159d87ee1a80c18e429bf3c241778f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 18:12:18 -0700 Subject: [PATCH 54/57] update bedrock tests --- core/llm/llms/Bedrock.test.ts | 344 +++++++++++++++++++++++++--------- core/llm/llms/Bedrock.ts | 89 ++++++--- 2 files changed, 317 insertions(+), 116 deletions(-) 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 5b9895c06..c50ad842e 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -392,6 +392,7 @@ class Bedrock extends BaseLLM { } } + const hasAddedToolCallIds = new Set(); let currentRole: "user" | "assistant" = "user"; let currentBlocks: ContentBlock[] = []; let addCachePoint = false; @@ -419,12 +420,19 @@ class Bedrock extends BaseLLM { for (let idx = 0; idx < nonSystemMessages.length; idx++) { const message = nonSystemMessages[idx]; + if (message.role === "user" || message.role === "tool") { - pushCurrentMessage(); - currentRole = ConversationRole.USER; + if (currentRole !== ConversationRole.USER) { + pushCurrentMessage(); + currentRole = ConversationRole.USER; + } if (message.role === "user") { - if (message.content) { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { // 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. @@ -438,47 +446,69 @@ class Bedrock extends BaseLLM { } currentBlocks.push( ...this._convertMessageContentToBlocks( - message.content, + trimmedContent, messageIsCached, ), ); } } else if (message.role === "tool") { - currentBlocks.push({ - toolResult: { - toolUseId: message.toolCallId, - content: [ - { - text: message.content || "", - }, - ], - }, - }); + 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") { + if (currentRole !== ConversationRole.ASSISTANT) { + pushCurrentMessage(); + currentRole = ConversationRole.ASSISTANT; } - } else { - pushCurrentMessage(); - currentRole = ConversationRole.ASSISTANT; if (message.role === "assistant") { - if (message.content) { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { currentBlocks.push( - ...this._convertMessageContentToBlocks(message.content, false), + ...this._convertMessageContentToBlocks(trimmedContent, false), ); } if (message.toolCalls) { for (const toolCall of message.toolCalls) { - if (availableTools.has(toolCall.function?.name || "")) { - currentBlocks.push({ - toolUse: { - toolUseId: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - }, - }); + if (toolCall.id && toolCall.function?.name) { + if (availableTools.has(toolCall.function.name)) { + hasAddedToolCallIds.add(toolCall.id); + currentBlocks.push({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function.name, + input: safeParseToolCallArgs(toolCall), + }, + }); + } 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( - `Tool ${toolCall.function?.name} is not available for this model.`, + `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, ); + continue; } } } @@ -506,6 +536,9 @@ class Bedrock extends BaseLLM { } } } + if (currentBlocks.length > 0) { + pushCurrentMessage(); + } return converted; } From d77684280b2a74354da9f8c9e563bc2f84ada1ab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 18:40:25 -0700 Subject: [PATCH 55/57] fix failing edit test - only cancel if rejectDiff --- gui/src/components/AcceptRejectDiffButtons.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index 9420fc551..252d19332 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -28,7 +28,10 @@ export default function AcceptRejectAllButtons({ ); const dispatch = useAppDispatch(); async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { - if (currentToolCallApplyState?.status === "done") { + if ( + status === "rejectDiff" && + currentToolCallApplyState?.status === "done" + ) { dispatch( cancelToolCall({ toolCallId: currentToolCallApplyState.toolCallId!, From 334282fc3415147424b196f16da5f20c33740ea8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 19:02:52 -0700 Subject: [PATCH 56/57] applied rules to user message --- gui/src/redux/thunks/streamNormalInput.ts | 4 ++-- gui/src/redux/util/constructMessages.ts | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 4dc78adaa..0133a101a 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -67,7 +67,7 @@ export const streamNormalInput = createAsyncThunk< const { id, ...messageWithoutId } = item.message; return { ...item, message: messageWithoutId }; }); - const { messages, appliedRules } = constructMessages( + const { messages, appliedRules, appliedRuleIndex } = constructMessages( withoutMessageIds, baseSystemMessage, state.config.config.rules, @@ -78,7 +78,7 @@ export const streamNormalInput = createAsyncThunk< // because there will be multiple tool messages, so which one should have applied rules? dispatch( setAppliedRulesAtIndex({ - index: messages.length - 1, + index: appliedRuleIndex, appliedRules: appliedRules, }), ); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index 419e9af64..15f8120db 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -37,11 +37,15 @@ export function constructMessages( ): { 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" || @@ -52,6 +56,7 @@ export function constructMessages( } if (item.message.role === "user") { + appliedRuleIndex = index; // Gather context items for user messages let content = normalizeToMessageParts(item.message); @@ -152,6 +157,7 @@ export function constructMessages( return { messages, appliedRules, + appliedRuleIndex, }; } From fb6ec5bbe9b692b2e1d21188e25cd59890072a58 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 20:14:56 -0700 Subject: [PATCH 57/57] fix bedrock caching, add comments to message conversions --- core/llm/llms/Bedrock.ts | 109 +++++++++++++++++++++------------------ 1 file changed, 60 insertions(+), 49 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index c50ad842e..1c1c61ed3 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -376,26 +376,16 @@ class Bedrock extends BaseLLM { }; } + /* + Converts the messages to the format expected by the Bedrock API. + + */ private _convertMessages( messages: ChatMessage[], availableTools: Set, ): Message[] { - const nonSystemMessages = messages.filter((m) => m.role !== "system"); - - const lastTwoUserMsgIndices: number[] = []; - for (let i = nonSystemMessages.length - 1; i >= 0; i--) { - if (nonSystemMessages[i].role === "user") { - lastTwoUserMsgIndices.push(i); - if (lastTwoUserMsgIndices.length === 2) { - break; - } - } - } - - const hasAddedToolCallIds = new Set(); let currentRole: "user" | "assistant" = "user"; let currentBlocks: ContentBlock[] = []; - let addCachePoint = false; const converted: Message[] = []; const pushCurrentMessage = () => { @@ -405,53 +395,46 @@ class Bedrock extends BaseLLM { ); } if (currentBlocks.length > 0) { - if (addCachePoint) { - currentBlocks.push({ cachePoint: { type: "default" } }); - } converted.push({ role: currentRole, content: currentBlocks, }); } - // Change roles and reset currentBlocks = []; - addCachePoint = false; }; + const nonSystemMessages = messages.filter((m) => m.role !== "system"); + const hasAddedToolCallIds = new Set(); + 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) { - // 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 messageIsCached = !!( - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(idx) - ); - if (messageIsCached) { - addCachePoint = true; - } currentBlocks.push( - ...this._convertMessageContentToBlocks( - trimmedContent, - messageIsCached, - ), + ...this._convertMessageContentToBlocks(trimmedContent), ); } - } else if (message.role === "tool") { + } + // 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({ @@ -471,11 +454,14 @@ class Bedrock extends BaseLLM { } } } 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" @@ -483,14 +469,18 @@ class Bedrock extends BaseLLM { : message.content; if (trimmedContent) { currentBlocks.push( - ...this._convertMessageContentToBlocks(trimmedContent, false), + ...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)) { - hasAddedToolCallIds.add(toolCall.id); currentBlocks.push({ toolUse: { toolUseId: toolCall.id, @@ -498,6 +488,7 @@ class Bedrock extends BaseLLM { 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({ @@ -513,6 +504,8 @@ class Bedrock extends BaseLLM { } } } 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: { @@ -540,29 +533,47 @@ class Bedrock extends BaseLLM { 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, - addCaching: boolean, ): ContentBlock[] { const blocks: ContentBlock[] = []; if (typeof content === "string") { - let contentText = content; - if (addCaching) { - contentText += getSecureID(); - } - blocks.push({ text: contentText }); - if (addCaching) { - blocks.push({ cachePoint: { type: "default" } }); - } + blocks.push({ text: content }); } else { for (const part of content) { if (part.type === "text") { - if (addCaching) { - part.text += getSecureID(); - } blocks.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { try {