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 001/169] 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 002/169] 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 0b929bf7994321cbb2fa8196bfca4081a4ad70f3 Mon Sep 17 00:00:00 2001 From: Josh Holmer Date: Mon, 16 Jun 2025 11:35:42 -0400 Subject: [PATCH 003/169] fix: do not delete docs indexes on resync --- core/indexing/docs/DocsService.ts | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 6bd285520..7ea3d444e 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -981,17 +981,11 @@ export default class DocsService { // Otherwise sync the index based on config changes const oldConfigDocs = oldConfig?.docs || []; const newConfigDocs = newConfig.docs || []; - const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // Anything found in sqlite but not in new config should be deleted - const deletedDocs = currentlyIndexedDocs.filter( - (doc) => !newConfigStartUrls.includes(doc.startUrl), - ); - // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed // TODO if only favicon and title change, only update, don't embed // Otherwise anything found in new config that isn't in sqlite should be added/indexed @@ -1038,10 +1032,6 @@ export default class DocsService { ...changedDocs.map((doc) => this.indexAndAdd(doc, true)), ...addedDocs.map((doc) => this.indexAndAdd(doc)), ]); - - for (const doc of deletedDocs) { - await this.deleteIndexes(doc.startUrl); - } } catch (e) { console.error("Error syncing docs index on config update", e); } finally { From fc950f4cd3ed92443fa6c49990b0d73942e1550f Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Mon, 16 Jun 2025 16:12:12 -0700 Subject: [PATCH 004/169] add llamastack support --- packages/openai-adapters/package-lock.json | 4 +- .../openai-adapters/src/apis/LlamaStack.ts | 55 +++++++ packages/openai-adapters/src/index.ts | 6 +- .../openai-adapters/src/test/main.test.ts | 146 +++--------------- packages/openai-adapters/src/types.ts | 7 + 5 files changed, 93 insertions(+), 125 deletions(-) create mode 100644 packages/openai-adapters/src/apis/LlamaStack.ts diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 1d88a8b5e..efba3b949 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.36", + "version": "1.0.38", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.36", + "version": "1.0.38", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", diff --git a/packages/openai-adapters/src/apis/LlamaStack.ts b/packages/openai-adapters/src/apis/LlamaStack.ts new file mode 100644 index 000000000..fe0ee5daf --- /dev/null +++ b/packages/openai-adapters/src/apis/LlamaStack.ts @@ -0,0 +1,55 @@ +import { streamSse } from "@continuedev/fetch"; +import { ChatCompletionChunk } from "openai/resources/index"; +import { LlamastackConfig } from "../types.js"; +import { chatChunk, customFetch } from "../util.js"; +import { OpenAIApi } from "./OpenAI.js"; +import { FimCreateParamsStreaming } from "./base.js"; + +export const Llamastack_API_BASE = "http://localhost:8321/v1/openai/v1/"; +export class LlamastackApi extends OpenAIApi { + constructor(config: LlamastackConfig) { + super({ + ...config, + provider: "openai", + apiBase: config.apiBase ?? Llamastack_API_BASE, + apiKey: config.apiKey ?? 'dummy', + }); + } + + async *fimStream( + body: FimCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const endpoint = new URL("completions", this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + prompt: body.prompt, + suffix: body.suffix, + max_tokens: body.max_tokens, + max_completion_tokens: (body as any).max_completion_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "x-api-key": this.config.apiKey ?? "", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + for await (const chunk of streamSse(resp as any)) { + yield chatChunk({ + content: chunk.choices[0].text, + finish_reason: chunk.finish_reason, + model: body.model, + }); + } +} +} \ No newline at end of file diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 9f0cf341c..70b9265b7 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -7,6 +7,7 @@ import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; import { InceptionApi } from "./apis/Inception.js"; import { JinaApi } from "./apis/Jina.js"; +import { LlamastackApi } from "./apis/LlamaStack.js"; import { MockApi } from "./apis/Mock.js"; import { MoonshotApi } from "./apis/Moonshot.js"; import { OpenAIApi } from "./apis/OpenAI.js"; @@ -51,6 +52,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { return new InceptionApi(config); case "watsonx": return new WatsonXApi(config); + case "llamastack": + return new LlamastackApi(config); case "x-ai": return openAICompatible("https://api.x.ai/v1/", config); case "voyage": @@ -117,9 +120,10 @@ export { type Completion, type CompletionCreateParams, type CompletionCreateParamsNonStreaming, - type CompletionCreateParamsStreaming, + type CompletionCreateParamsStreaming } from "openai/resources/index"; // export export type { BaseLlmApi } from "./apis/base.js"; export type { LLMConfig } from "./types.js"; + diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index 1d68a7782..eec06cb27 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -1,10 +1,8 @@ import { ModelConfig } from "@continuedev/config-yaml"; import * as dotenv from "dotenv"; -import { DEEPSEEK_API_BASE } from "../apis/DeepSeek.js"; -import { INCEPTION_API_BASE } from "../apis/Inception.js"; import { OpenAIApi } from "../apis/OpenAI.js"; import { constructLlmApi } from "../index.js"; -import { getLlmApi, testChat, testEmbed } from "./util.js"; +import { getLlmApi, testChat, testEmbed, testFim } from "./util.js"; dotenv.config(); @@ -33,99 +31,30 @@ function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) { if (config.roles?.includes("embed")) { testEmbed(api, model); } - - if (config.roles?.includes("embed")) { - testEmbed(api, model); + if (config.roles?.includes("autocomplete")) { + testFim(api, model); } + } - const TESTS: Omit[] = [ - { - provider: "openai", - model: "gpt-4o", - apiKey: process.env.OPENAI_API_KEY!, - roles: ["chat"], + { + provider: "llamastack", + model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", + apiBase: "http://localhost:8321/v1/openai/v1/", + roles: ["apply", "chat", "edit"], + options: { skipTools: false }, }, { - provider: "anthropic", - model: "claude-3-5-haiku-latest", - apiKey: process.env.ANTHROPIC_API_KEY!, - roles: ["chat"], - }, - { - provider: "gemini", - model: "gemini-1.5-flash-latest", - apiKey: process.env.GEMINI_API_KEY!, - roles: ["chat"], - }, - { - provider: "mistral", - model: "codestral-latest", - apiKey: process.env.MISTRAL_API_KEY!, - apiBase: "https://api.mistral.ai/v1", - roles: ["autocomplete"], - }, - { - provider: "deepseek", - model: "deepseek-coder", - apiKey: process.env.DEEPSEEK_API_KEY!, - roles: ["autocomplete"], - }, - { - provider: "openai", - model: "text-embedding-3-small", - apiKey: process.env.OPENAI_API_KEY!, + provider: "llamastack", + model: "all-MiniLM-L6-v2", + apiBase: "http://localhost:8321/v1/openai/v1/", roles: ["embed"], }, - { - provider: "voyage", - model: "voyage-code-3", - apiKey: process.env.VOYAGE_API_KEY!, - roles: ["embed"], - }, - // { - // provider: "cohere", - // model: "embed-v4.0", - // apiKey: process.env.COHERE_API_KEY!, - // roles: ["embed"], - // }, - // { - // provider: "gemini", - // model: "models/text-embedding-004", - // apiKey: process.env.GEMINI_API_KEY!, - // roles: ["embed"], - // }, - { - provider: "voyage", - model: "rerank-lite-1", - apiKey: process.env.VOYAGE_API_KEY!, - roles: ["rerank"], - }, - // { - // provider: "cohere", - // model: "rerank-v3.5", - // apiKey: process.env.COHERE_API_KEY!, - // roles: ["rerank"], - // }, - { - provider: "azure", - model: "gpt-4.1", - apiBase: "https://continue-openai.openai.azure.com", - apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY, - env: { - deployment: "gpt-4.1", - apiVersion: "2024-02-15-preview", - apiType: "azure-openai", - }, - roles: ["chat"], - }, - { - provider: "azure", - model: "mistral-small-2503", - apiBase: "https://nate-0276-resource.services.ai.azure.com/models", - apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY, - roles: ["chat"], - options: { skipTools: true }, + { + provider: "llamastack", + model: "qwen2.5-coder:1.5b", + apiBase: "http://localhost:8321/v1/openai/v1/", + roles: ["autocomplete"], }, ]; @@ -136,41 +65,14 @@ TESTS.forEach((config) => { }); describe("Configuration", () => { - it("should configure DeepSeek OpenAI client with correct apiBase and apiKey", () => { - const deepseek = constructLlmApi({ - provider: "deepseek", + it("should configure OpenAI client with correct apiBase and apiKey", () => { + const openai = constructLlmApi({ + provider: "openai", apiKey: "sk-xxx", + apiBase: "http://localhost:8321/v1/openai/v1/", }); - expect((deepseek as OpenAIApi).openai.baseURL).toBe(DEEPSEEK_API_BASE); - expect((deepseek as OpenAIApi).openai.apiKey).toBe("sk-xxx"); - - const deepseek2 = constructLlmApi({ - provider: "deepseek", - apiKey: "sk-xxx", - apiBase: "https://api.example.com", - }); - expect((deepseek2 as OpenAIApi).openai.baseURL).toBe( - "https://api.example.com", - ); - }); - - it("should configure Inception OpenAI client with correct apiBase and apiKey", () => { - const inception = constructLlmApi({ - provider: "inception", - apiKey: "sk-xxx", - }); - - expect((inception as OpenAIApi).openai.baseURL).toBe(INCEPTION_API_BASE); - expect((inception as OpenAIApi).openai.apiKey).toBe("sk-xxx"); - - const inception2 = constructLlmApi({ - provider: "inception", - apiKey: "sk-xxx", - apiBase: "https://api.example.com", - }); - expect((inception2 as OpenAIApi).openai.baseURL).toBe( - "https://api.example.com", - ); + expect((openai as OpenAIApi).openai.baseURL).toBe("http://localhost:8321/v1/openai/v1/"); + expect((openai as OpenAIApi).openai.apiKey).toBe("sk-xxx"); }); }); diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index 2f26a4c80..3c79db7bf 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -71,9 +71,15 @@ export const DeepseekConfigSchema = OpenAIConfigSchema.extend({ }); export type DeepseekConfig = z.infer; +export const LlamastackConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("llamastack"), +}); +export type LlamastackConfig = z.infer; + export const MockConfigSchema = BasePlusConfig.extend({ provider: z.literal("mock"), }); + export type MockConfig = z.infer; // Other APIs @@ -146,5 +152,6 @@ export const LLMConfigSchema = z.discriminatedUnion("provider", [ JinaConfigSchema, MockConfigSchema, InceptionConfigSchema, + LlamastackConfigSchema, ]); export type LLMConfig = z.infer; From e760f7ab753403e9d856dc45666b0fb4bac48fc5 Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Mon, 16 Jun 2025 16:13:13 -0700 Subject: [PATCH 005/169] revert main.ts --- .../openai-adapters/src/test/main.test.ts | 148 +++++++++++++++--- 1 file changed, 123 insertions(+), 25 deletions(-) diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index eec06cb27..9b3885b14 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -1,8 +1,10 @@ import { ModelConfig } from "@continuedev/config-yaml"; import * as dotenv from "dotenv"; +import { DEEPSEEK_API_BASE } from "../apis/DeepSeek.js"; +import { INCEPTION_API_BASE } from "../apis/Inception.js"; import { OpenAIApi } from "../apis/OpenAI.js"; import { constructLlmApi } from "../index.js"; -import { getLlmApi, testChat, testEmbed, testFim } from "./util.js"; +import { getLlmApi, testChat, testEmbed } from "./util.js"; dotenv.config(); @@ -31,30 +33,99 @@ function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) { if (config.roles?.includes("embed")) { testEmbed(api, model); } - if (config.roles?.includes("autocomplete")) { - testFim(api, model); + + if (config.roles?.includes("embed")) { + testEmbed(api, model); } - } + const TESTS: Omit[] = [ - { - provider: "llamastack", - model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", - apiBase: "http://localhost:8321/v1/openai/v1/", - roles: ["apply", "chat", "edit"], - options: { skipTools: false }, + { + provider: "openai", + model: "gpt-4o", + apiKey: process.env.OPENAI_API_KEY!, + roles: ["chat"], }, { - provider: "llamastack", - model: "all-MiniLM-L6-v2", - apiBase: "http://localhost:8321/v1/openai/v1/", + provider: "anthropic", + model: "claude-3-5-haiku-latest", + apiKey: process.env.ANTHROPIC_API_KEY!, + roles: ["chat"], + }, + { + provider: "gemini", + model: "gemini-1.5-flash-latest", + apiKey: process.env.GEMINI_API_KEY!, + roles: ["chat"], + }, + { + provider: "mistral", + model: "codestral-latest", + apiKey: process.env.MISTRAL_API_KEY!, + apiBase: "https://api.mistral.ai/v1", + roles: ["autocomplete"], + }, + { + provider: "deepseek", + model: "deepseek-coder", + apiKey: process.env.DEEPSEEK_API_KEY!, + roles: ["autocomplete"], + }, + { + provider: "openai", + model: "text-embedding-3-small", + apiKey: process.env.OPENAI_API_KEY!, roles: ["embed"], }, - { - provider: "llamastack", - model: "qwen2.5-coder:1.5b", - apiBase: "http://localhost:8321/v1/openai/v1/", - roles: ["autocomplete"], + { + provider: "voyage", + model: "voyage-code-3", + apiKey: process.env.VOYAGE_API_KEY!, + roles: ["embed"], + }, + // { + // provider: "cohere", + // model: "embed-v4.0", + // apiKey: process.env.COHERE_API_KEY!, + // roles: ["embed"], + // }, + // { + // provider: "gemini", + // model: "models/text-embedding-004", + // apiKey: process.env.GEMINI_API_KEY!, + // roles: ["embed"], + // }, + { + provider: "voyage", + model: "rerank-lite-1", + apiKey: process.env.VOYAGE_API_KEY!, + roles: ["rerank"], + }, + // { + // provider: "cohere", + // model: "rerank-v3.5", + // apiKey: process.env.COHERE_API_KEY!, + // roles: ["rerank"], + // }, + { + provider: "azure", + model: "gpt-4.1", + apiBase: "https://continue-openai.openai.azure.com", + apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY, + env: { + deployment: "gpt-4.1", + apiVersion: "2024-02-15-preview", + apiType: "azure-openai", + }, + roles: ["chat"], + }, + { + provider: "azure", + model: "mistral-small-2503", + apiBase: "https://nate-0276-resource.services.ai.azure.com/models", + apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY, + roles: ["chat"], + options: { skipTools: true }, }, ]; @@ -65,14 +136,41 @@ TESTS.forEach((config) => { }); describe("Configuration", () => { - it("should configure OpenAI client with correct apiBase and apiKey", () => { - const openai = constructLlmApi({ - provider: "openai", + it("should configure DeepSeek OpenAI client with correct apiBase and apiKey", () => { + const deepseek = constructLlmApi({ + provider: "deepseek", apiKey: "sk-xxx", - apiBase: "http://localhost:8321/v1/openai/v1/", }); - expect((openai as OpenAIApi).openai.baseURL).toBe("http://localhost:8321/v1/openai/v1/"); - expect((openai as OpenAIApi).openai.apiKey).toBe("sk-xxx"); + expect((deepseek as OpenAIApi).openai.baseURL).toBe(DEEPSEEK_API_BASE); + expect((deepseek as OpenAIApi).openai.apiKey).toBe("sk-xxx"); + + const deepseek2 = constructLlmApi({ + provider: "deepseek", + apiKey: "sk-xxx", + apiBase: "https://api.example.com", + }); + expect((deepseek2 as OpenAIApi).openai.baseURL).toBe( + "https://api.example.com", + ); }); -}); + + it("should configure Inception OpenAI client with correct apiBase and apiKey", () => { + const inception = constructLlmApi({ + provider: "inception", + apiKey: "sk-xxx", + }); + + expect((inception as OpenAIApi).openai.baseURL).toBe(INCEPTION_API_BASE); + expect((inception as OpenAIApi).openai.apiKey).toBe("sk-xxx"); + + const inception2 = constructLlmApi({ + provider: "inception", + apiKey: "sk-xxx", + apiBase: "https://api.example.com", + }); + expect((inception2 as OpenAIApi).openai.baseURL).toBe( + "https://api.example.com", + ); + }); +}); \ No newline at end of file From a378350b7d7d1e024cd9bcf9cd0a127a12c65bc4 Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Mon, 16 Jun 2025 17:53:07 -0700 Subject: [PATCH 006/169] add LlamaStack as new model --- core/llm/llms/LlamaStack.ts | 57 +++++++++++++++++++++++++++++ core/llm/llms/index.ts | 3 +- extensions/vscode/package-lock.json | 4 +- 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 core/llm/llms/LlamaStack.ts diff --git a/core/llm/llms/LlamaStack.ts b/core/llm/llms/LlamaStack.ts new file mode 100644 index 000000000..c4d83c248 --- /dev/null +++ b/core/llm/llms/LlamaStack.ts @@ -0,0 +1,57 @@ +import { streamSse } from "@continuedev/fetch"; +import { CompletionOptions, LLMOptions } from "../../index.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; + +import OpenAI from "./OpenAI.js"; + +class LlamaStack extends OpenAI { + static providerName = "llamastack"; + static defaultOptions: Partial = { + apiBase: "http://localhost:8321/v1/openai/v1/", + model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; + maxStopWords: number | undefined = 16; + + supportsFim(): boolean { + return true; + } + + async *_streamFim( + prefix: string, + suffix: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + prompt: prefix, + suffix, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].text; + } + } +} + +export default Deepseek; \ No newline at end of file diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index a003ce0cf..17442e5f6 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -33,6 +33,7 @@ import Inception from "./Inception"; import Kindo from "./Kindo"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; +import LlamaStack from "./LlamaStack"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; import MockLLM from "./Mock"; @@ -62,7 +63,6 @@ import Vllm from "./Vllm"; import Voyage from "./Voyage"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; - export const LLMClasses = [ Anthropic, Cohere, @@ -116,6 +116,7 @@ export const LLMClasses = [ Relace, Inception, Voyage, + LlamaStack, ]; export async function llmFromDescription( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ce706126c..199c669c7 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.47", + "version": "1.1.48", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.47", + "version": "1.1.48", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From 94af0ee986eb54cba4bd43728df00daf7bed28cd Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Wed, 18 Jun 2025 10:41:10 -0700 Subject: [PATCH 007/169] add llama-stack doc --- .../model-providers/more/llamastack.mdx | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 docs/docs/customize/model-providers/more/llamastack.mdx diff --git a/docs/docs/customize/model-providers/more/llamastack.mdx b/docs/docs/customize/model-providers/more/llamastack.mdx new file mode 100644 index 000000000..4f21e9911 --- /dev/null +++ b/docs/docs/customize/model-providers/more/llamastack.mdx @@ -0,0 +1,113 @@ +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +# Llama Stack + +[Llama Stack](https://llama-stack.readthedocs.io/en/latest/index.html) is an open-source library that standardizes the core building blocks that simplify AI application development. It codifies best practices across the Llama ecosystem. More specifically, it provides + +- **Unified API layer** for Inference, RAG, Agents, Tools, Safety, Evals, and Telemetry. +- **Plugin architecture** to support the rich ecosystem of different API implementations in various environments, including local development, on-premises, cloud, and mobile. +- **Prepackaged verified distributions** which offer a one-stop solution for developers to get started quickly and reliably in any environment. +- **Multiple developer interfaces** like CLI and SDKs for Python, Typescript, iOS, and Android. +- **Standalone applications** as examples for how to build production-grade AI applications with Llama Stack. + +To try Llama Stack locally, run: + +```shell +curl -LsSf https://github.com/meta-llama/llama-stack/raw/main/install.sh | bash +``` + +Learn more about how to get started with llama stack in this [guide](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html) + +## Chat model + +We recommend configuring **Llama 4 Maverick** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Llama4 Maverick + provider: llamastack + model: meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8 + apiBase: http:///v1/openai/v1/ + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama4 Maverick", + "provider": "llamastack", + "model": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", + "apiBase": "http:///v1/openai/v1/" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **CodeLlama 7B** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - name: CodeLlama 7B + provider: llamastack + model: codellama:7b + apiBase: http:///v1/openai/v1/ + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "CodeLlama 7B", + "provider": "llamastack", + "model": "codellama:7b", + "apiBase": "http:///v1/openai/v1/" + } + } + ``` + + + +## Embeddings model + +By default, Llama Stack uses **all-MiniLM-L6-v2** as the embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: all-MiniLM-L6-v2 + provider: llamastack + model: all-MiniLM-L6-v2 + apiBase: http:///v1/openai/v1/ + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "llamastack", + "model": "all-MiniLM-L6-v2", + "apiBase": "http:///v1/openai/v1/" + } + } + ``` + + + +## Reranking model + +Llama Stack currently did not support Reranking API yet. \ No newline at end of file From 3dbcce4793bf6a785db96ca4ff84eb65be84c11d Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Wed, 18 Jun 2025 11:01:28 -0700 Subject: [PATCH 008/169] fix core bug --- core/llm/llms/LlamaStack.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/llms/LlamaStack.ts b/core/llm/llms/LlamaStack.ts index c4d83c248..b0e0d4669 100644 --- a/core/llm/llms/LlamaStack.ts +++ b/core/llm/llms/LlamaStack.ts @@ -54,4 +54,4 @@ class LlamaStack extends OpenAI { } } -export default Deepseek; \ No newline at end of file +export default LlamaStack; \ No newline at end of file From 7254442f7e4ac3b249db86796367cf8b87eedc5c Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Wed, 18 Jun 2025 11:03:36 -0700 Subject: [PATCH 009/169] add llamastack to type.ts --- packages/openai-adapters/src/types.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index 3c79db7bf..f878a5e90 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -37,6 +37,7 @@ export const OpenAIConfigSchema = BasePlusConfig.extend({ z.literal("deepinfra"), z.literal("groq"), z.literal("nvidia"), + z.literal("llamastack"), z.literal("ovhcloud"), z.literal("fireworks"), z.literal("together"), From ad90ac44f857b56c43540d80b2fe47a7766e9d3e Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Wed, 18 Jun 2025 11:10:13 -0700 Subject: [PATCH 010/169] fix style --- core/llm/llms/LlamaStack.ts | 2 +- packages/openai-adapters/src/apis/LlamaStack.ts | 4 ++-- packages/openai-adapters/src/index.ts | 3 +-- packages/openai-adapters/src/test/main.test.ts | 2 +- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/core/llm/llms/LlamaStack.ts b/core/llm/llms/LlamaStack.ts index b0e0d4669..c246bdbdf 100644 --- a/core/llm/llms/LlamaStack.ts +++ b/core/llm/llms/LlamaStack.ts @@ -54,4 +54,4 @@ class LlamaStack extends OpenAI { } } -export default LlamaStack; \ No newline at end of file +export default LlamaStack; diff --git a/packages/openai-adapters/src/apis/LlamaStack.ts b/packages/openai-adapters/src/apis/LlamaStack.ts index fe0ee5daf..ba279e045 100644 --- a/packages/openai-adapters/src/apis/LlamaStack.ts +++ b/packages/openai-adapters/src/apis/LlamaStack.ts @@ -12,7 +12,7 @@ export class LlamastackApi extends OpenAIApi { ...config, provider: "openai", apiBase: config.apiBase ?? Llamastack_API_BASE, - apiKey: config.apiKey ?? 'dummy', + apiKey: config.apiKey ?? "dummy", }); } @@ -51,5 +51,5 @@ export class LlamastackApi extends OpenAIApi { model: body.model, }); } + } } -} \ No newline at end of file diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 70b9265b7..b4254046e 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -120,10 +120,9 @@ export { type Completion, type CompletionCreateParams, type CompletionCreateParamsNonStreaming, - type CompletionCreateParamsStreaming + type CompletionCreateParamsStreaming, } from "openai/resources/index"; // export export type { BaseLlmApi } from "./apis/base.js"; export type { LLMConfig } from "./types.js"; - diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index 9b3885b14..1d68a7782 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -173,4 +173,4 @@ describe("Configuration", () => { "https://api.example.com", ); }); -}); \ No newline at end of file +}); From de7283720b37552fe8846d6c5b2267ddca4b11e0 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 17:10:50 -0700 Subject: [PATCH 011/169] feat: continue init prompt --- core/promptFiles/v2/getPromptFiles.ts | 84 +++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index 069fe1114..db11b0885 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -4,6 +4,81 @@ import { readAllGlobalPromptFiles } from "../../util/paths"; import { joinPathsToUri } from "../../util/uri"; import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1"; +// The hardcoded init prompt content +const INIT_PROMPT_CONTENT = `name: Init +description: Initialize Codebase +--- +You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project. + +## Step 1: Check Required Tools +First, verify that you have access to the necessary tools: +- builtin_file_glob_search: To discover project files +- builtin_read_file: To analyze file contents +- builtin_ls: To explore directory structure +- builtin_create_new_file: To generate the CONTINUE.md file + +If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. + +## Step 2: Project Analysis +Analyze the project structure and key files to understand: +- The programming languages and frameworks used +- The overall architecture and organization +- Key components and their responsibilities +- Important configuration files +- Build/deployment system + +## Step 3: Generate CONTINUE.md +Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections: + +1. **Project Overview** + - Brief description of the project's purpose + - Key technologies used + - High-level architecture + +2. **Getting Started** + - Prerequisites (required software, dependencies) + - Installation instructions + - Basic usage examples + - Running tests + +3. **Project Structure** + - Overview of main directories and their purpose + - Key files and their roles + - Important configuration files + +4. **Development Workflow** + - Coding standards or conventions + - Testing approach + - Build and deployment process + - Contribution guidelines + +5. **Key Concepts** + - Domain-specific terminology + - Core abstractions + - Design patterns used + +6. **Common Tasks** + - Step-by-step guides for frequent development tasks + - Examples of common operations + +7. **Troubleshooting** + - Common issues and their solutions + - Debugging tips + +8. **References** + - Links to relevant documentation + - Important resources + +Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. + +## Step 4: Finalize +After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to: +1. Review and edit the file as needed +2. Commit it to their repository to share with their team +3. Explain that Continue will automatically load this file into context when working with the project + +Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`; + export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; export async function getPromptFilesFromDir( ide: IDE, @@ -58,8 +133,17 @@ export async function getAllPromptFiles( // Also read from ~/.continue/.prompts promptFiles.push(...readAllGlobalPromptFiles()); + // Add hardcoded init prompt + promptFiles.push({ + path: "builtin:/init.prompt", + content: INIT_PROMPT_CONTENT, + }); + return await Promise.all( promptFiles.map(async (file) => { + if (file.path.startsWith("builtin:")) { + return file; + } const content = await ide.readFile(file.path); return { path: file.path, content }; }), 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 012/169] =?UTF-8?q?add=20tool=20support=20for=20deepseek-c?= =?UTF-8?q?hat=E3=80=81deepseek-reasoner(Only=20for=20deepseek=20official?= =?UTF-8?q?=20API=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 013/169] 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 16d3145702c2222851867e467b84070f46a4594f Mon Sep 17 00:00:00 2001 From: Hayden Cardwell <26019242+hayden-cardwell@users.noreply.github.com> Date: Wed, 18 Jun 2025 21:56:24 -0500 Subject: [PATCH 014/169] fix(autocomplete): trim trailing <|file_separator|> for Gemini/Gemma models Google Gemini/Gemma models sometimes append "<|file_separator|>" at the end of autocomplete completions, forcing users to remove it manually. Update postprocessCompletion to detect when llm.model includes "gemini" or "gemma" and the completion ends with "<|file_separator|>", then slice off the trailing 18 characters. See #6067 --- core/autocomplete/postprocessing/index.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index bf0284cb2..3504a069d 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -132,6 +132,14 @@ export function postprocessCompletion({ completion = "\n" + completion; } + if ( + (llm.model.includes("gemini") || llm.model.includes("gemma")) && + completion.endsWith("<|file_separator|>") + ) { + // "<|file_separator|>" is 18 characters long + completion = completion.slice(0, -18); + } + // If prefix ends with space and so does completion, then remove the space from completion if (prefix.endsWith(" ") && completion.startsWith(" ")) { 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 015/169] 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 016/169] 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 017/169] 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 018/169] 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 019/169] 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 631a5b148159918ee0909c615095b69589d0e7d2 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 25 Jun 2025 22:07:00 -0700 Subject: [PATCH 020/169] Update jetbrains-release.yaml --- .github/workflows/jetbrains-release.yaml | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 8ea3d2ebb..920ed808b 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -167,20 +167,8 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Build and check config-yaml - run: | - cd ../../packages/config-yaml - npm i - npx tsc --noEmit - # Tests are currently failing, commenting out for now - # npm test - npm run build + - name: Build packages (Unix) + run: ./scripts/build-packages.sh # npm install core - name: Install core node_modules From ba37b5706a715570d84ec9c654fc9af4c72c67ba Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 26 Jun 2025 17:16:01 +0200 Subject: [PATCH 021/169] 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 022/169] 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 023/169] 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 39e4546436d05c300b44c6ab7244671adba71a15 Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Thu, 26 Jun 2025 14:06:33 -0700 Subject: [PATCH 024/169] remove llamastack from OpenAIConfigSchema --- packages/openai-adapters/src/index.ts | 2 +- packages/openai-adapters/src/types.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index b4254046e..7544d2ef3 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -120,7 +120,7 @@ export { type Completion, type CompletionCreateParams, type CompletionCreateParamsNonStreaming, - type CompletionCreateParamsStreaming, + type CompletionCreateParamsStreaming } from "openai/resources/index"; // export diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index f878a5e90..3c79db7bf 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -37,7 +37,6 @@ export const OpenAIConfigSchema = BasePlusConfig.extend({ z.literal("deepinfra"), z.literal("groq"), z.literal("nvidia"), - z.literal("llamastack"), z.literal("ovhcloud"), z.literal("fireworks"), z.literal("together"), From 7485bbab776e6c0eeb7b8189a8822af64b2d24ff Mon Sep 17 00:00:00 2001 From: Kai Wu Date: Thu, 26 Jun 2025 14:09:43 -0700 Subject: [PATCH 025/169] fix style --- packages/openai-adapters/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 7544d2ef3..b4254046e 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -120,7 +120,7 @@ export { type Completion, type CompletionCreateParams, type CompletionCreateParamsNonStreaming, - type CompletionCreateParamsStreaming + type CompletionCreateParamsStreaming, } from "openai/resources/index"; // export From 155525db20877fdc1ec99cbc5dfd07a91f96e2e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 26 Jun 2025 14:52:40 -0700 Subject: [PATCH 026/169] 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 f637e1d5d4a3ccce111daf7af5043d2cc2b52b71 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 21:20:51 -0700 Subject: [PATCH 027/169] remove dead code Footer --- gui/src/components/Footer.tsx | 21 --------------------- gui/src/components/Layout.tsx | 2 -- 2 files changed, 23 deletions(-) delete mode 100644 gui/src/components/Footer.tsx diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx deleted file mode 100644 index 35fe7fa56..000000000 --- a/gui/src/components/Footer.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { useAppSelector } from "../redux/hooks"; -import { selectSelectedChatModel } from "../redux/slices/configSlice"; - -function Footer() { - const defaultModel = useAppSelector(selectSelectedChatModel); - - // TODO hook hub up to free trial - // if (defaultModel?.provider === "free-trial") { - // return ( - //
- // - //
- // ); - // } - return null; -} - -export default Footer; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 1e2134e7a..cb0738314 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -17,7 +17,6 @@ import { incrementFreeTrialCount } from "../util/freeTrial"; import { ROUTES } from "../util/navigation"; import { FatalErrorIndicator } from "./config/FatalErrorNotice"; import TextDialog from "./dialogs"; -import Footer from "./Footer"; import { LumpProvider } from "./mainInput/Lump/LumpContext"; import { useMainEditor } from "./mainInput/TipTapEditor"; import { @@ -252,7 +251,6 @@ const Layout = () => { -
From b026445acadb0cae221716295e6d95c7bed7634b Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 21:40:40 -0700 Subject: [PATCH 028/169] convert styled components to tailwind (with prompt) --- .../migrate-styled-components-to-tailwind.md | 5 +++ .../StepContainerPreToolbar/index.tsx | 42 ++++--------------- gui/tailwind.config.cjs | 3 ++ 3 files changed, 16 insertions(+), 34 deletions(-) create mode 100644 .continue/rules/migrate-styled-components-to-tailwind.md diff --git a/.continue/rules/migrate-styled-components-to-tailwind.md b/.continue/rules/migrate-styled-components-to-tailwind.md new file mode 100644 index 000000000..bccb56d32 --- /dev/null +++ b/.continue/rules/migrate-styled-components-to-tailwind.md @@ -0,0 +1,5 @@ +--- +alwaysApply: false +--- + +Convert all of the styled components in this file into tailwind CSS. If a variable is used that is not already in @theme.ts and @tailwind.config.cjs, then you should figure out where it comes from and try adding that so it can be used. Wherever a function is called to interpolate a value, you can just use inline `styles={{ ... }}` diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index f5737c78e..8ece216bb 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -1,12 +1,6 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; import { useContext, useEffect, useMemo, useState } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - vscCommandCenterInactiveBorder, - vscEditorBackground, -} from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; @@ -25,29 +19,6 @@ import { FileInfo } from "./FileInfo"; import { InsertButton } from "./InsertButton"; import { RunInTerminalButton } from "./RunInTerminalButton"; -const TopDiv = styled.div` - display: flex; - flex-direction: column; - outline: 1px solid ${vscCommandCenterInactiveBorder}; - outline-offset: -0.5px; - border-radius: ${defaultBorderRadius}; - margin-bottom: 8px !important; - margin-top: 8px !important; - background-color: ${vscEditorBackground}; - min-width: 0; -`; - -const ToolbarDiv = styled.div<{ isExpanded: boolean }>` - display: flex; - justify-content: space-between; - align-items: center; - font-size: ${getFontSize() - 2}px; - padding: 4px 6px; - margin: 0; - border-bottom: ${({ isExpanded }) => - isExpanded ? `1px solid ${vscCommandCenterInactiveBorder}` : "inherit"}; -`; - export interface StepContainerPreToolbarProps { codeBlockContent: string; language: string | null; @@ -290,9 +261,12 @@ export function StepContainerPreToolbar({ } return ( - - -
+
+
+
setIsExpanded(!isExpanded)} @@ -323,11 +297,11 @@ export function StepContainerPreToolbar({ {renderActionButtons()}
- +
{isExpanded && (
{children}
)} - +
); } diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index ed91cee11..1e70345f2 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -29,6 +29,9 @@ module.exports = { borderRadius: { default: "5px", }, + outlineOffset: { + 0.5: "0.5px", + }, colors: { background: varWithFallback("background"), foreground: varWithFallback("foreground"), From b7b5b0e20307fec54a5745a856fd44e64cbad0e1 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 21:50:55 -0700 Subject: [PATCH 029/169] ToolbarButonWithTooltip --- .../ToolbarButtonWithTooltip.tsx | 28 ++++--------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx index 6950ee415..58f05ef0c 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx @@ -1,25 +1,7 @@ import { ReactNode, useMemo } from "react"; import { Tooltip } from "react-tooltip"; -import styled from "styled-components"; -import { lightGray, vscForeground } from "../.."; import { getFontSize } from "../../../util"; -export const ToolbarButton = styled.button` - display: flex; - align-items: center; - border: none; - outline: none; - background: transparent; - - color: ${vscForeground}; - font-size: ${getFontSize() - 2}px; - - &:hover { - cursor: pointer; - filter: brightness(1.25); - } -`; - interface ToolbarButtonWithTooltipProps { onClick: () => void; children: ReactNode; @@ -40,15 +22,17 @@ export function ToolbarButtonWithTooltip({ return ( <> - {children} - + {tooltipContent} From 3765e92be080064b8727c0459c4f4f4f3fc792a7 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 21:56:53 -0700 Subject: [PATCH 030/169] docstring --- gui/src/util/cn.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/gui/src/util/cn.ts b/gui/src/util/cn.ts index a5ef19350..ed267ad72 100644 --- a/gui/src/util/cn.ts +++ b/gui/src/util/cn.ts @@ -1,6 +1,20 @@ import { clsx, type ClassValue } from "clsx"; import { twMerge } from "tailwind-merge"; +/** + * Combines multiple class values and merges Tailwind CSS classes. + * + * This utility function combines the functionality of clsx (for conditional class names) + * and tailwind-merge (for intelligently merging Tailwind CSS classes, removing duplicates + * and conflicts). + * + * @param inputs - Class values that can be strings, objects, arrays, or conditional expressions + * @returns A merged string of class names with Tailwind conflicts resolved + * + * @example + * cn('px-2 py-1', 'px-4') // Returns 'py-1 px-4' (px-2 is overridden by px-4) + * cn('text-red-500', { 'text-blue-500': isActive }) // Conditionally applies classes + */ export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } From c24bcda9127c9de83a32fc52de61c9d158844820 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 21:56:59 -0700 Subject: [PATCH 031/169] update prompt to use cn.ts --- .continue/rules/migrate-styled-components-to-tailwind.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.continue/rules/migrate-styled-components-to-tailwind.md b/.continue/rules/migrate-styled-components-to-tailwind.md index bccb56d32..0432f9a8d 100644 --- a/.continue/rules/migrate-styled-components-to-tailwind.md +++ b/.continue/rules/migrate-styled-components-to-tailwind.md @@ -2,4 +2,4 @@ alwaysApply: false --- -Convert all of the styled components in this file into tailwind CSS. If a variable is used that is not already in @theme.ts and @tailwind.config.cjs, then you should figure out where it comes from and try adding that so it can be used. Wherever a function is called to interpolate a value, you can just use inline `styles={{ ... }}` +Convert all of the styled components in this file into tailwind CSS. If a variable is used that is not already in @theme.ts and @tailwind.config.cjs, then you should figure out where it comes from and try adding that so it can be used. Wherever a function is called to interpolate a value, you can just use inline `styles={{ ... }}`. For ternaries, you could use @cn.ts. From dd6284d63444923933eda03fb967502c11e40fbb Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 21:58:28 -0700 Subject: [PATCH 032/169] shared.tsx --- .../AssistantAndOrgListbox/shared.tsx | 105 +++++++++++++----- 1 file changed, 75 insertions(+), 30 deletions(-) diff --git a/gui/src/components/AssistantAndOrgListbox/shared.tsx b/gui/src/components/AssistantAndOrgListbox/shared.tsx index 1f57a4309..0cd897b5e 100644 --- a/gui/src/components/AssistantAndOrgListbox/shared.tsx +++ b/gui/src/components/AssistantAndOrgListbox/shared.tsx @@ -6,11 +6,8 @@ import { } from "@heroicons/react/24/outline"; import { useState } from "react"; import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscCommandCenterInactiveBorder, -} from ".."; +import { lightGray } from ".."; +import { cn } from "../../util/cn"; import { ToolTip } from "../gui/Tooltip"; export const OptionDiv = styled.div<{ @@ -47,11 +44,6 @@ export const OptionDiv = styled.div<{ export const MAX_HEIGHT_PX = 300; -export const Divider = styled.div` - height: 0.5px; - background-color: ${vscCommandCenterInactiveBorder}; -`; - interface ModelOptionProps { children: React.ReactNode; idx: number; @@ -64,28 +56,81 @@ interface ModelOptionProps { onClickError?: (e: any) => void; } -const IconBase = styled.div<{ $hovered: boolean }>` - width: 1.2em; - height: 1.2em; - cursor: pointer; - padding: 4px; - border-radius: ${defaultBorderRadius}; - opacity: ${(props) => (props.$hovered ? 0.75 : 0)}; - visibility: ${(props) => (props.$hovered ? "visible" : "hidden")}; +interface IconBaseProps { + $hovered: boolean; + onClick?: (e: any) => void; + className?: string; + children?: React.ReactNode; + [key: string]: any; +} - &:hover { - opacity: 1; - background-color: ${lightGray}33; - } -`; +function IconBase({ + $hovered, + onClick, + className, + children, + ...props +}: IconBaseProps) { + return ( +
+ {children} +
+ ); +} -const StyledCog6ToothIcon = styled(IconBase).attrs({ as: Cog6ToothIcon })``; -const StyledArrowTopRightOnSquareIcon = styled(IconBase).attrs({ - as: ArrowTopRightOnSquareIcon, -})``; -const StyledExclamationTriangleIcon = styled(IconBase).attrs({ - as: ExclamationTriangleIcon, -})``; +const StyledCog6ToothIcon = ({ + $hovered, + onClick, +}: { + $hovered: boolean; + onClick?: (e: any) => void; +}) => ( + + + +); + +const StyledArrowTopRightOnSquareIcon = ({ + $hovered, + onClick, +}: { + $hovered: boolean; + onClick?: (e: any) => void; +}) => ( + + + +); + +const StyledExclamationTriangleIcon = ({ + $hovered, + onClick, + className, + ...props +}: { + $hovered: boolean; + onClick?: (e: any) => void; + className?: string; + [key: string]: any; +}) => ( + + + +); export function Option({ children, From 0db42801ecd96934b7007fc54b284eb975a94c68 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 22:52:31 -0700 Subject: [PATCH 033/169] enable diff syntax highlighting on diff tool output file --- core/tools/implementations/viewDiff.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts index fd1dfdb8a..330172dff 100644 --- a/core/tools/implementations/viewDiff.ts +++ b/core/tools/implementations/viewDiff.ts @@ -7,7 +7,7 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => { return [ { - name: "Diff", + name: ".diff", description: "The current git diff", content: diffs.join("\n"), }, From cbae30ad53f60aac966b4d66bd747180c514a976 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 23:38:16 -0700 Subject: [PATCH 034/169] refactor gradient border to its own file --- .../components/mainInput/ContinueInputBox.tsx | 40 +------------------ .../components/mainInput/GradientBorder.tsx | 38 ++++++++++++++++++ 2 files changed, 40 insertions(+), 38 deletions(-) create mode 100644 gui/src/components/mainInput/GradientBorder.tsx diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index b50edfdbb..af7521666 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,12 +1,12 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers, RuleWithSource } from "core"; import { useMemo } from "react"; -import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; import { useAppSelector } from "../../redux/hooks"; import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; import { RulesPeek } from "./belowMainInput/RulesPeek"; +import { GradientBorder } from "./GradientBorder"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; @@ -38,43 +38,6 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ "repo-map", ]; -const gradient = keyframes` - 0% { - background-position: 0px 0; - } - 100% { - background-position: 100em 0; - } -`; - -const GradientBorder = styled.div<{ - borderRadius?: string; - borderColor?: string; - loading: 0 | 1; -}>` - border-radius: ${(props) => props.borderRadius || "0"}; - padding: 1px; - background: ${(props) => - props.borderColor - ? props.borderColor - : `repeating-linear-gradient( - 101.79deg, - #1BBE84 0%, - #331BBE 16%, - #BE1B55 33%, - #A6BE1B 55%, - #BE1B55 67%, - #331BBE 85%, - #1BBE84 99% - )`}; - animation: ${(props) => (props.loading ? gradient : "")} 6s linear infinite; - background-size: 200% 200%; - width: 100%; - display: flex; - flex-direction: row; - align-items: center; -`; - function ContinueInputBox(props: ContinueInputBoxProps) { const isStreaming = useAppSelector((state) => state.session.isStreaming); const availableSlashCommands = useAppSelector( @@ -146,6 +109,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { />
+ {(appliedRules.length > 0 || contextItems.length > 0) && (
diff --git a/gui/src/components/mainInput/GradientBorder.tsx b/gui/src/components/mainInput/GradientBorder.tsx new file mode 100644 index 000000000..6cbf263d5 --- /dev/null +++ b/gui/src/components/mainInput/GradientBorder.tsx @@ -0,0 +1,38 @@ +import styled, { keyframes } from "styled-components"; + +const gradient = keyframes` + 0% { + background-position: 0px 0; + } + 100% { + background-position: 100em 0; + } +`; + +export const GradientBorder = styled.div<{ + borderRadius?: string; + borderColor?: string; + loading: 0 | 1; +}>` + border-radius: ${(props) => props.borderRadius || "0"}; + padding: 1px; + background: ${(props) => + props.borderColor + ? props.borderColor + : `repeating-linear-gradient( + 101.79deg, + #1BBE84 0%, + #331BBE 16%, + #BE1B55 33%, + #A6BE1B 55%, + #BE1B55 67%, + #331BBE 85%, + #1BBE84 99% + )`}; + animation: ${(props) => (props.loading ? gradient : "")} 6s linear infinite; + background-size: 200% 200%; + width: 100%; + display: flex; + flex-direction: row; + align-items: center; +`; From 7addf2c9eab47d6d3ad4a31592bdc4f83e359c24 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 26 Jun 2025 23:47:45 -0700 Subject: [PATCH 035/169] nicer hover effects on input boxes --- gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 8e659f1e8..a5f9dbc56 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -179,7 +179,11 @@ export function TipTapEditor(props: TipTapEditorProps) { onBlur={handleBlur} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} - className={shouldHideToolbar ? "cursor-default" : "cursor-text"} + className={ + !props.isMainInput && shouldHideToolbar + ? "cursor-pointer hover:brightness-105" + : "cursor-text" + } onClick={() => { editor?.commands.focus(); }} From 4604369fb4cfe33756f33aa6b8f7a56fee106efa Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 27 Jun 2025 00:01:46 -0700 Subject: [PATCH 036/169] improve styling for links --- gui/src/components/StyledMarkdownPreview/index.tsx | 3 +-- gui/src/components/index.ts | 3 +++ gui/src/styles/theme.ts | 4 ++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index f648dd61b..98ca83881 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -77,14 +77,13 @@ const StyledMarkdown = styled.div<{ } word-wrap: break-word; border-radius: ${defaultBorderRadius}; - background-color: ${vscEditorBackground}; + background-color: var(--vscode-textCodeBlock-background); font-size: ${getFontSize() - 2}px; font-family: var(--vscode-editor-font-family); } code:not(pre > code) { font-family: var(--vscode-editor-font-family); - color: var(--vscode-input-placeholderForeground); } background-color: ${(props) => props.bgColor}; diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 71fd4ae0c..a1d2ed387 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -12,6 +12,9 @@ export const vscForeground = varWithFallback("foreground"); export const vscButtonBackground = varWithFallback("primary-background"); export const vscButtonForeground = varWithFallback("primary-foreground"); export const vscEditorBackground = varWithFallback("editor-background"); +export const vscTextCodeBlockBackground = varWithFallback( + "textCodeBlockBackground", +); export const vscListActiveBackground = varWithFallback("list-active"); export const vscFocusBorder = varWithFallback("border-focus"); export const vscListActiveForeground = varWithFallback( diff --git a/gui/src/styles/theme.ts b/gui/src/styles/theme.ts index ad0ee0bd7..144a9d8d6 100644 --- a/gui/src/styles/theme.ts +++ b/gui/src/styles/theme.ts @@ -140,6 +140,10 @@ export const THEME_COLORS = { vars: ["--vscode-textLink-foreground"], default: "#5c9ce6", // medium blue }, + textCodeBlockBackground: { + vars: ["--vscode-textCodeBlock-background"], + default: "#1e1e1e", // same as editor-background + }, accent: { vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"], default: "#4d8bf0", // bright blue From 1ce30606ae3e639a4b98f0235753e8a8b372165e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 27 Jun 2025 00:26:05 -0700 Subject: [PATCH 037/169] update defaultBorderRadius and use rem instead of px --- .continue/rules/css-units.md | 5 +++++ gui/src/components/Layout.tsx | 3 +-- gui/src/components/StyledMarkdownPreview/index.tsx | 2 +- gui/src/components/index.ts | 2 +- gui/src/components/mainInput/InputToolbar/EnterButton.tsx | 3 +-- .../mainInput/TipTapEditor/components/StyledComponents.ts | 3 +-- gui/tailwind.config.cjs | 2 +- 7 files changed, 11 insertions(+), 9 deletions(-) create mode 100644 .continue/rules/css-units.md diff --git a/.continue/rules/css-units.md b/.continue/rules/css-units.md new file mode 100644 index 000000000..a270a383d --- /dev/null +++ b/.continue/rules/css-units.md @@ -0,0 +1,5 @@ +--- +globs: "gui/**/*.tsx" +--- + +You should try to use the `rem` CSS unit whenever possible for scalability instead of `px`. diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 1e2134e7a..20d750d42 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -2,7 +2,7 @@ import { OnboardingModes } from "core/protocol/core"; import { useContext, useEffect } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { CustomScrollbarDiv, defaultBorderRadius } from "."; +import { CustomScrollbarDiv } from "."; import { AuthProvider } from "../context/Auth"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { LocalStorageProvider } from "../context/LocalStorage"; @@ -30,7 +30,6 @@ import PostHogPageView from "./PosthogPageView"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; - border-radius: ${defaultBorderRadius}; position: relative; overflow-x: hidden; `; diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index 98ca83881..45dd743fb 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -76,7 +76,7 @@ const StyledMarkdown = styled.div<{ display: none; } word-wrap: break-word; - border-radius: ${defaultBorderRadius}; + border-radius: 0.3125rem; background-color: var(--vscode-textCodeBlock-background); font-size: ${getFontSize() - 2}px; font-family: var(--vscode-editor-font-family); diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index a1d2ed387..ee20d7365 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -1,7 +1,7 @@ import styled from "styled-components"; import { varWithFallback } from "../styles/theme"; -export const defaultBorderRadius = "5px"; +export const defaultBorderRadius = "0.5rem"; export const lightGray = "#999998"; export const greenButtonColor = "#189e72"; diff --git a/gui/src/components/mainInput/InputToolbar/EnterButton.tsx b/gui/src/components/mainInput/InputToolbar/EnterButton.tsx index 21dae2642..6d26ca690 100644 --- a/gui/src/components/mainInput/InputToolbar/EnterButton.tsx +++ b/gui/src/components/mainInput/InputToolbar/EnterButton.tsx @@ -1,6 +1,5 @@ import styled from "styled-components"; import { - defaultBorderRadius, lightGray, vscButtonBackground, vscButtonForeground, @@ -18,7 +17,7 @@ export const EnterButton = styled.button<{ isPrimary?: boolean }>` !props.disabled && props.isPrimary ? vscButtonBackground : lightGray + "33"}; - border-radius: ${defaultBorderRadius}; + border-radius: 0.3125rem; color: ${(props) => !props.disabled && props.isPrimary ? vscButtonForeground : vscForeground}; cursor: pointer; diff --git a/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts index f994b53d6..3889a7ef9 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts +++ b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts @@ -1,6 +1,5 @@ import styled from "styled-components"; import { - defaultBorderRadius, lightGray, vscBadgeBackground, vscCommandCenterActiveBorder, @@ -14,7 +13,7 @@ import { getFontSize } from "../../../../util"; export const InputBoxDiv = styled.div<{}>` resize: none; font-family: inherit; - border-radius: ${defaultBorderRadius}; + border-radius: 0.5rem; padding-bottom: 1px; margin: 0; height: auto; diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index ed91cee11..d5871cc80 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -27,7 +27,7 @@ module.exports = { "spin-slow": "spin 6s linear infinite", }, borderRadius: { - default: "5px", + default: "0.5rem", }, colors: { background: varWithFallback("background"), From 5df9aa2a2bb514a211ff79006a6ebf0eef7dc1e7 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 27 Jun 2025 00:30:31 -0700 Subject: [PATCH 038/169] increase lump x margin --- gui/src/components/mainInput/Lump/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index f6ff453ce..993ed64cc 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -10,8 +10,8 @@ import { SelectedSection } from "./sections/SelectedSection"; const LumpDiv = styled.div` background-color: ${vscInputBackground}; - margin-left: 4px; - margin-right: 4px; + margin-left: 6px; + margin-right: 6px; border-radius: ${defaultBorderRadius} ${defaultBorderRadius} 0 0; border-top: 1px solid ${vscCommandCenterInactiveBorder}; border-left: 1px solid ${vscCommandCenterInactiveBorder}; From 0d26551ae0e8779cfcec408915b7052fb2af15b6 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 27 Jun 2025 00:35:59 -0700 Subject: [PATCH 039/169] fix code bg --- gui/src/components/StyledMarkdownPreview/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index 45dd743fb..0f2d1af0d 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -77,7 +77,7 @@ const StyledMarkdown = styled.div<{ } word-wrap: break-word; border-radius: 0.3125rem; - background-color: var(--vscode-textCodeBlock-background); + background-color: ${vscEditorBackground}; font-size: ${getFontSize() - 2}px; font-family: var(--vscode-editor-font-family); } From ec7c497faf0ab75c31a7620d9307076b38d35bfb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 19:18:09 -0700 Subject: [PATCH 040/169] 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 041/169] 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 042/169] 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 043/169] 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 044/169] 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 045/169] 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 046/169] 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 047/169] 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 4d20c8ad50c86bb98306a7e76deacc24da1d3abb Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 30 Jun 2025 14:07:08 -0700 Subject: [PATCH 048/169] add textCodeBlcokBackground to GetTheme.kt --- .../continueintellijextension/continue/GetTheme.kt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt index 0ee4c2bd0..3a01f05fc 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -166,6 +166,9 @@ class GetTheme { val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?: editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor + // Use editor background with slight tint for code blocks + val textCodeBlockBackground = slightChange(editorBackground, 3) ?: editorBackground + // These should match the keys in GUI's theme.ts val theme = mapOf( "background" to background, @@ -197,6 +200,7 @@ class GetTheme { "warning" to warningColor, "error" to errorColor, "link" to link, + "textCodeBlockBackground" to textCodeBlockBackground, "accent" to accentColor, "find-match" to findMatchBackground, "find-match-selected" to findMatchSelectedBackground, From 9266c2a812c87efc93c6da7361e33a48714d5575 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 30 Jun 2025 15:10:19 -0700 Subject: [PATCH 049/169] chore: conditional tooltip on reasoning btn --- gui/src/components/mainInput/InputToolbar.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 0dfbcd493..12fece723 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -167,7 +167,9 @@ function InputToolbar(props: InputToolbarProps) { /> - Use Model Reasoning + {hasReasoningEnabled + ? "Disable model reasoning" + : "Enable model reasoning"} )} From 089808f1630038aa0d0b994b6b2600d4970f347d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:05:55 -0700 Subject: [PATCH 050/169] 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 051/169] 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 052/169] 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 053/169] 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 054/169] 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 055/169] 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 a2adf2fe982813edd23cd259e21ba154754df525 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 30 Jun 2025 18:11:36 -0700 Subject: [PATCH 056/169] feat: generate rule button + dialog scaffolding --- .../GenerateRuleDialog/RuleTemplateChip.tsx | 26 ++++++ .../components/GenerateRuleDialog/index.tsx | 84 +++++++++++++++++++ .../GenerateRuleDialog/ruleTemplates.ts | 15 ++++ .../StepContainer/ResponseActions.tsx | 28 ++++++- gui/src/components/ui/Button.tsx | 4 +- 5 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 gui/src/components/GenerateRuleDialog/RuleTemplateChip.tsx create mode 100644 gui/src/components/GenerateRuleDialog/index.tsx create mode 100644 gui/src/components/GenerateRuleDialog/ruleTemplates.ts diff --git a/gui/src/components/GenerateRuleDialog/RuleTemplateChip.tsx b/gui/src/components/GenerateRuleDialog/RuleTemplateChip.tsx new file mode 100644 index 000000000..dc102cb50 --- /dev/null +++ b/gui/src/components/GenerateRuleDialog/RuleTemplateChip.tsx @@ -0,0 +1,26 @@ +import React from "react"; +import { Button } from "../ui"; + +interface RuleTemplateChipProps { + icon: React.ComponentType<{ className?: string }>; + text: string; + onClick: () => void; +} + +export function RuleTemplateChip({ + icon: Icon, + text, + onClick, +}: RuleTemplateChipProps) { + return ( + + ); +} diff --git a/gui/src/components/GenerateRuleDialog/index.tsx b/gui/src/components/GenerateRuleDialog/index.tsx new file mode 100644 index 000000000..04802c7b6 --- /dev/null +++ b/gui/src/components/GenerateRuleDialog/index.tsx @@ -0,0 +1,84 @@ +import { useContext, useState } from "react"; +import { useDispatch } from "react-redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { Button } from "../ui"; +import { RuleTemplateChip } from "./RuleTemplateChip"; +import { RuleTemplate, ruleTemplates } from "./ruleTemplates"; + +function GenerateRuleDialog() { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const [textareaValue, setTextareaValue] = useState(""); + + const lastChatMessage = useAppSelector( + (state) => state.session.history[state.session.history.length - 1], + ); + + const closeDialog = () => { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + }; + + function onSubmit(e: any) { + e.preventDefault(); + // Logic to generate rule will go here + closeDialog(); + } + + function handleRuleTemplateClick(ruleTemplate: RuleTemplate) { + setTextareaValue(ruleTemplate.template); + } + + return ( +
+
+
+

Generate Rule

+

+ This will generate a new rule using the content of your chat history +

+
+
+
+
+