From 8d8cf3644e41d8b4d095cc4a4197112f65c0cbec Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 29 May 2025 13:48:47 -0700 Subject: [PATCH 01/95] fix apply cancellation and make slash commands cancelable --- core/commands/index.ts | 3 ++- core/commands/slash/commit.ts | 4 ++-- core/commands/slash/draftIssue.ts | 4 ++-- core/commands/slash/mcp.ts | 2 +- core/commands/slash/onboard.ts | 4 ++-- core/commands/slash/review.ts | 4 ++-- core/edit/lazy/applyCodeBlock.ts | 9 ++++++++- core/edit/lazy/replace.ts | 12 ++++++++---- core/edit/lazy/streamLazyApply.ts | 7 +++---- core/index.d.ts | 3 ++- core/llm/streamChat.ts | 1 + core/promptFiles/v1/slashCommandFromPromptFile.ts | 2 +- extensions/vscode/src/apply/ApplyManager.ts | 8 +++++++- 13 files changed, 41 insertions(+), 22 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index 3037d7ef7..d87a3536f 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -25,6 +25,7 @@ export function slashFromCustomCommand( config, selectedCode, fetch, + abortController, }) { // Render prompt template let renderedPrompt: string; @@ -63,7 +64,7 @@ export function slashFromCustomCommand( for await (const chunk of llm.streamChat( messages, - new AbortController().signal, + abortController.signal, completionOptions, )) { yield renderChatMessage(chunk); diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 8fc1ae27b..55499b583 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -4,7 +4,7 @@ import { renderChatMessage } from "../../util/messageContent.js"; const CommitMessageCommand: SlashCommand = { name: "commit", description: "Generate a commit message for current changes", - run: async function* ({ ide, llm, params }) { + run: async function* ({ ide, llm, params, abortController }) { const includeUnstaged = params?.includeUnstaged ?? false; const diff = await ide.getDiff(includeUnstaged); @@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = { const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; for await (const chunk of llm.streamChat( [{ role: "user", content: prompt }], - new AbortController().signal, + abortController.signal, )) { yield renderChatMessage(chunk); } diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 637013476..fba5d4cd3 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -24,7 +24,7 @@ Body:\n\n`; const DraftIssueCommand: SlashCommand = { name: "issue", description: "Draft a GitHub issue", - run: async function* ({ input, llm, history, params }) { + run: async function* ({ input, llm, history, params, abortController }) { if (params?.repositoryUrl === undefined) { yield "This command requires a repository URL to be set in the config file."; return; @@ -46,7 +46,7 @@ const DraftIssueCommand: SlashCommand = { for await (const chunk of llm.streamChat( messages, - new AbortController().signal, + abortController.signal, )) { body += chunk.content; yield renderChatMessage(chunk); diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts index 84df38989..89af5c5c2 100644 --- a/core/commands/slash/mcp.ts +++ b/core/commands/slash/mcp.ts @@ -60,7 +60,7 @@ export function constructMcpSlashCommand( for await (const chunk of context.llm.streamChat( messages, - new AbortController().signal, + context.abortController.signal, context.completionOptions, )) { yield renderChatMessage(chunk); diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index b53c8d3a9..545b75cc2 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -41,7 +41,7 @@ const MAX_EXPLORE_DEPTH = 2; const OnboardSlashCommand: SlashCommand = { name: "onboard", description: "Familiarize yourself with the codebase", - run: async function* ({ llm, ide }) { + run: async function* ({ llm, ide, abortController }) { const [workspaceDir] = await ide.getWorkspaceDirs(); const context = await gatherProjectContext(workspaceDir, ide); @@ -49,7 +49,7 @@ const OnboardSlashCommand: SlashCommand = { for await (const chunk of llm.streamChat( [{ role: "user", content: prompt }], - new AbortController().signal, + abortController.signal, )) { yield renderChatMessage(chunk); } diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index a3a2be6a7..6190f5499 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -38,14 +38,14 @@ function getLastUserHistory(history: ChatMessage[]): string { const ReviewMessageCommand: SlashCommand = { name: "review", description: "Review code and give feedback", - run: async function* ({ llm, history }) { + run: async function* ({ llm, history, abortController }) { const reviewText = getLastUserHistory(history).replace("\\review", ""); const content = `${prompt} \r\n ${reviewText}`; for await (const chunk of llm.streamChat( [{ role: "user", content: content }], - new AbortController().signal, + abortController.signal, )) { yield renderChatMessage(chunk); } diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 8ca9a8154..b58b9d4ec 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -16,6 +16,7 @@ export async function applyCodeBlock( newLazyFile: string, filename: string, llm: ILLM, + abortController: AbortController, ): Promise<{ isInstantApply: boolean; diffLinesGenerator: AsyncGenerator; @@ -51,6 +52,12 @@ export async function applyCodeBlock( return { isInstantApply: false, - diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm), + diffLinesGenerator: streamLazyApply( + oldFile, + filename, + newLazyFile, + llm, + abortController, + ), }; } diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index 26e174c17..1a5ba704d 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -59,6 +59,7 @@ export async function* getReplacementWithLlm( linesBefore: string[], linesAfter: string[], llm: ILLM, + abortController: AbortController, ): AsyncGenerator { const userPrompt = dedent` ORIGINAL CODE: @@ -83,10 +84,13 @@ export async function* getReplacementWithLlm( \`\`\` `; - const completion = await llm.streamChat([ - { role: "user", content: userPrompt }, - { role: "assistant", content: assistantPrompt }, - ], new AbortController().signal); + const completion = await llm.streamChat( + [ + { role: "user", content: userPrompt }, + { role: "assistant", content: assistantPrompt }, + ], + abortController.signal, + ); let lines = streamLines(completion); lines = filterLeadingNewline(lines); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index ce7af0ef7..f8ec0905c 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -16,6 +16,7 @@ export async function* streamLazyApply( filename: string, newCode: string, llm: ILLM, + abortController: AbortController, ): AsyncGenerator { const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName); if (!promptFactory) { @@ -23,10 +24,7 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat( - promptMessages, - new AbortController().signal, - ); + const lazyCompletion = llm.streamChat(promptMessages, abortController.signal); // Do find and replace over the lazy edit response async function* replacementFunction( @@ -39,6 +37,7 @@ export async function* streamLazyApply( linesBefore, linesAfter, llm, + abortController, )) { yield line; } diff --git a/core/index.d.ts b/core/index.d.ts index 794c03ce0..ffbd84d1b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -836,6 +836,7 @@ export interface ContinueSDK { config: ContinueConfig; fetch: FetchFunction; completionOptions?: LLMFullCompletionOptions; + abortController: AbortController; } export interface SlashCommand { @@ -1141,7 +1142,7 @@ export interface StreamableHTTPOptions { requestOptions?: RequestOptions; } -export type TransportOptions = +export type TransportOptions = | StdioOptions | WebSocketOptions | SSEOptions diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index c899e437f..99e1dad94 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -84,6 +84,7 @@ export async function* llmStreamChat( config.requestOptions, ), completionOptions, + abortController, }); let next = await gen.next(); while (!next.done) { diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 7f478e623..9b5cf0c34 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -98,7 +98,7 @@ export function slashCommandFromPromptFileV1( for await (const chunk of context.llm.streamChat( messages, - new AbortController().signal, + context.abortController.signal, context.completionOptions, )) { yield renderChatMessage(chunk); diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index df5791335..d16bc433c 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -3,6 +3,7 @@ import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { StreamAbortManager } from "core/util/abortManager"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -116,11 +117,16 @@ export class ApplyManager { return; } + const fileUri = editor.document.uri.toString(); + const abortManager = StreamAbortManager.getInstance(); + const abortController = abortManager.get(fileUri); + const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( editor.document.getText(), text, - getUriPathBasename(editor.document.uri.toString()), + getUriPathBasename(fileUri), llm, + abortController, ); if (isInstantApply) { From a1dc1f8aa249a1678d0f2b611a3f6f87ad2f695d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 29 May 2025 16:04:35 -0700 Subject: [PATCH 02/95] change to reject diffs approach rather than cancel apply approach --- core/core.ts | 13 ++-- .../applyAbortManager.ts} | 12 ++-- core/edit/recursiveStream.ts | 1 + core/edit/streamDiffLines.ts | 7 +- core/index.d.ts | 2 +- core/llm/utils/extractPathsFromCodeBlocks.ts | 2 - .../continueintellijextension/types.kt | 2 +- extensions/vscode/package-lock.json | 6 +- extensions/vscode/src/apply/ApplyManager.ts | 4 +- extensions/vscode/src/commands.ts | 67 +++---------------- extensions/vscode/src/diff/processDiff.ts | 52 ++++++++++++++ .../vscode/src/diff/vertical/manager.ts | 10 ++- .../Lump/LumpToolbar/IsApplyingToolbar.tsx | 8 ++- gui/src/pages/gui/Chat.tsx | 2 +- .../thunks/streamResponseAfterToolCall.ts | 12 ++-- 15 files changed, 111 insertions(+), 89 deletions(-) rename core/{util/abortManager.ts => edit/applyAbortManager.ts} (70%) create mode 100644 extensions/vscode/src/diff/processDiff.ts diff --git a/core/core.ts b/core/core.ts index 6b5f9814e..bd4d8b48b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -53,6 +53,7 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; +import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; @@ -61,7 +62,6 @@ import { LLMLogger } from "./llm/logger"; import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; -import { StreamAbortManager } from "./util/abortManager"; export class Core { configHandler: ConfigHandler; @@ -509,6 +509,11 @@ export class Core { throw new Error("No model selected"); } + const abortManager = ApplyAbortManager.getInstance(); + const abortController = abortManager.get( + data.fileUri ?? "current-file-stream", + ); // not super important since currently cancelling apply will cancel all streams it's one file at a time + return streamDiffLines({ highlighted: data.highlighted, prefix: data.prefix, @@ -522,13 +527,13 @@ export class Core { language: data.language, onlyOneInsertion: false, overridePrompt: undefined, - abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time + abortController, }); }); on("cancelApply", async (msg) => { - const abortManager = StreamAbortManager.getInstance(); - abortManager.clear(); + const abortManager = ApplyAbortManager.getInstance(); + abortManager.clear(); // for now abort all streams }); on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); diff --git a/core/util/abortManager.ts b/core/edit/applyAbortManager.ts similarity index 70% rename from core/util/abortManager.ts rename to core/edit/applyAbortManager.ts index e7de53bca..e811b5d4b 100644 --- a/core/util/abortManager.ts +++ b/core/edit/applyAbortManager.ts @@ -1,16 +1,16 @@ -export class StreamAbortManager { - private static instance: StreamAbortManager; +export class ApplyAbortManager { + private static instance: ApplyAbortManager; private controllers: Map; private constructor() { this.controllers = new Map(); } - public static getInstance(): StreamAbortManager { - if (!StreamAbortManager.instance) { - StreamAbortManager.instance = new StreamAbortManager(); + public static getInstance(): ApplyAbortManager { + if (!ApplyAbortManager.instance) { + ApplyAbortManager.instance = new ApplyAbortManager(); } - return StreamAbortManager.instance; + return ApplyAbortManager.instance; } public get(id: string): AbortController { diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index 004563cdb..5a6d4b39b 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -68,6 +68,7 @@ export async function* recursiveStream( }); for await (const chunk of generator) { + console.log(chunk); yield chunk; const rendered = renderChatMessage(chunk); buffer += rendered; diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 096b31d7d..f64448f36 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -20,7 +20,6 @@ import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; -import { StreamAbortManager } from "../util/abortManager"; import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; import { recursiveStream } from "./recursiveStream"; @@ -64,7 +63,7 @@ export async function* streamDiffLines({ highlighted, suffix, llm, - abortControllerId, + abortController, input, language, onlyOneInsertion, @@ -75,15 +74,13 @@ export async function* streamDiffLines({ highlighted: string; suffix: string; llm: ILLM; - abortControllerId: string; + abortController: AbortController; input: string; language: string | undefined; onlyOneInsertion: boolean; overridePrompt: ChatMessage[] | undefined; rulesToInclude: RuleWithSource[] | undefined; }): AsyncGenerator { - const abortManager = StreamAbortManager.getInstance(); - const abortController = abortManager.get(abortControllerId); void Telemetry.capture( "inlineEdit", { diff --git a/core/index.d.ts b/core/index.d.ts index ffbd84d1b..bbd4e385c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1263,7 +1263,7 @@ export interface HighlightedCodePayload { } export interface AcceptOrRejectDiffPayload { - filepath: string; + filepath?: string; streamId?: string; } diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts index 00f723c7a..99f2764b2 100644 --- a/core/llm/utils/extractPathsFromCodeBlocks.ts +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -2,8 +2,6 @@ * Extracts file paths from markdown code blocks */ export function extractPathsFromCodeBlocks(content: string): string[] { - console.log("CONTENT", content); - const paths: string[] = []; // Match code block opening patterns: diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 86862a096..56fe76777 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -249,7 +249,7 @@ data class StreamDiffLinesPayload( ) data class AcceptOrRejectDiffPayload( - val filepath: String, + val filepath: String? = null, val streamId: String? = null ) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 5634027da..f2db4b382 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.39", + "version": "1.1.40", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.39", + "version": "1.1.40", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -110,7 +110,7 @@ "@continuedev/fetch": "^1.0.10", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.25", - "@modelcontextprotocol/sdk": "^1.5.0", + "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index d16bc433c..fb446e174 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -3,7 +3,7 @@ import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; -import { StreamAbortManager } from "core/util/abortManager"; +import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -118,7 +118,7 @@ export class ApplyManager { } const fileUri = editor.document.uri.toString(); - const abortManager = StreamAbortManager.getInstance(); + const abortManager = ApplyAbortManager.getInstance(); const abortController = abortManager.get(fileUri); const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 84885f757..88c25bc07 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -35,6 +35,7 @@ import { } from "./autocomplete/statusBar"; import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; +import { processDiff } from "./diff/processDiff"; import { VerticalDiffManager } from "./diff/vertical/manager"; import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; @@ -93,56 +94,6 @@ function hideGUI() { } } -async function processDiff( - action: "accept" | "reject", - sidebar: ContinueGUIWebviewViewProvider, - ide: VsCodeIde, - core: Core, - verticalDiffManager: VerticalDiffManager, - newFileUri?: string, - streamId?: string, - toolCallId?: string, -) { - captureCommandTelemetry(`${action}Diff`); - - const currentFile = await ide.getCurrentFile(); - - let newOrCurrentUri = newFileUri; - if (!newOrCurrentUri) { - newOrCurrentUri = currentFile?.path; - } - if (!newOrCurrentUri) { - console.warn( - `No file provided or current file open while attempting to resolve diff`, - ); - return; - } - - await ide.openFile(newOrCurrentUri); - - // Clear vertical diffs depending on action - verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); - if (action === "reject") { - core.invoke("cancelApply", undefined); - } - - if (streamId) { - const fileContent = await ide.readFile(newOrCurrentUri); - - await sidebar.webviewProtocol.request("updateApplyState", { - fileContent, - filepath: newOrCurrentUri, - streamId, - status: "closed", - numDiffs: 0, - toolCallId, - }); - } - - // Save the file - await ide.saveFile(newOrCurrentUri); -} - function waitForSidebarReady( sidebar: ContinueGUIWebviewViewProvider, timeout: number, @@ -235,8 +186,9 @@ const getCommandsMap: ( } return { - "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => - processDiff( + "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => { + captureCommandTelemetry("acceptDiff"); + void processDiff( "accept", sidebar, ide, @@ -244,10 +196,12 @@ const getCommandsMap: ( verticalDiffManager, newFileUri, streamId, - ), + ); + }, - "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => - processDiff( + "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => { + captureCommandTelemetry("rejectDiff"); + void processDiff( "reject", sidebar, ide, @@ -255,7 +209,8 @@ const getCommandsMap: ( verticalDiffManager, newFileUri, streamId, - ), + ); + }, "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => { captureCommandTelemetry("acceptVerticalDiffBlock"); verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index); diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts new file mode 100644 index 000000000..b78ea966c --- /dev/null +++ b/extensions/vscode/src/diff/processDiff.ts @@ -0,0 +1,52 @@ +import { Core } from "core/core"; +import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; +import { VsCodeIde } from "../VsCodeIde"; +import { VerticalDiffManager } from "./vertical/manager"; + +export async function processDiff( + action: "accept" | "reject", + sidebar: ContinueGUIWebviewViewProvider, + ide: VsCodeIde, + core: Core, + verticalDiffManager: VerticalDiffManager, + newFileUri?: string, + streamId?: string, + toolCallId?: string, +) { + let newOrCurrentUri = newFileUri; + if (!newOrCurrentUri) { + const currentFile = await ide.getCurrentFile(); + newOrCurrentUri = currentFile?.path; + } + if (!newOrCurrentUri) { + console.warn( + `No file provided or current file open while attempting to resolve diff`, + ); + return; + } + + await ide.openFile(newOrCurrentUri); + + // Clear vertical diffs depending on action + verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); + if (action === "reject") { + // this is so that IDE reject diff command can also cancel apply + core.invoke("cancelApply", undefined); + } + + if (streamId) { + const fileContent = await ide.readFile(newOrCurrentUri); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: newOrCurrentUri, + streamId, + status: "closed", + numDiffs: 0, + toolCallId, + }); + } + + // Save the file + await ide.saveFile(newOrCurrentUri); +} diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 104db10c6..aca644c3a 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -10,6 +10,7 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -437,6 +438,9 @@ export class VerticalDiffManager { this.editDecorationManager.clear(); + const abortManager = ApplyAbortManager.getInstance(); + const abortController = abortManager.get(fileUri); + try { const streamedLines: string[] = []; @@ -451,7 +455,7 @@ export class VerticalDiffManager { language: getMarkdownLanguageTagForFile(fileUri), onlyOneInsertion: !!onlyOneInsertion, overridePrompt, - abortControllerId: fileUri, + abortController, }); for await (const line of stream) { @@ -467,6 +471,10 @@ export class VerticalDiffManager { // enable a listener for user edits to file while diff is open this.enableDocumentChangeListener(); + if (abortController.signal.aborted) { + vscode.commands.executeCommand("continue.rejectDiff"); + } + return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx index 0faf43e0e..f4840088d 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx @@ -1,12 +1,14 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../../redux/hooks"; +import { cancelStream } from "../../../../redux/thunks"; import { getAltKeyLabel, getMetaKeyLabel } from "../../../../util"; import { Container, StopButton } from "./components"; import { GeneratingIndicator } from "./GeneratingIndicator"; export const IsApplyingToolbar = () => { const ideMessenger = useContext(IdeMessengerContext); - + const dispatch = useAppDispatch(); const jetbrains = window.location.protocol === "jb-api:"; return ( @@ -18,7 +20,9 @@ export const IsApplyingToolbar = () => { // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option // Apply is prioritized because it can be more catastrophic // Intentional to be more WYSIWYG for now - ideMessenger.post("cancelApply", undefined); + // Keyboard shortcut is handled in chat + dispatch(cancelStream()); + ideMessenger.post("rejectDiff", {}); }} > {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index c3e8ac512..30088ab53 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -139,7 +139,7 @@ export function Chat() { !e.shiftKey ) { dispatch(cancelStream()); - ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter + ideMessenger.post("rejectDiff", {}); // just always cancel, if not in applying won't matter } }; window.addEventListener("keydown", listener); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 990723f7a..21d151562 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -35,7 +35,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< const toolCallState = findToolCall(state.session.history, toolCallId); if (!toolCallState) { - throw new Error("Tool call not found"); + return; // in cases where edit tool is cancelled mid apply, this will be triggered } const toolOutput = toolCallState.output ?? []; @@ -65,12 +65,14 @@ export const streamResponseAfterToolCall = createAsyncThunk< dispatch(setActive()); - const updatedHistory = getState().session.history; - const messageMode = getState().session.mode + const messageMode = getState().session.mode; + + const baseChatOrAgentSystemMessage = getBaseSystemMessage( + selectedChatModel, + messageMode, + ); - const baseChatOrAgentSystemMessage = getBaseSystemMessage(selectedChatModel, messageMode) - const messages = constructMessages( messageMode, [...updatedHistory], From 6d6f89fe55e7301d3c84473162d2e4da8bf0dc31 Mon Sep 17 00:00:00 2001 From: Jacob Date: Mon, 9 Jun 2025 11:04:23 +0800 Subject: [PATCH 03/95] fix: Fix the issue where the chunk index might be duplicated --- core/indexing/chunk/chunk.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index d51f368a2..c918ddac8 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -62,12 +62,11 @@ export async function* chunkDocument({ resolve({ ...chunkWithoutId, digest, - index, + index: index++, filepath, }); }), ); - index++; } for await (const chunk of chunkPromises) { if (!chunk) { From c69270959cb6b30c72e75d0d0dceae348bd490be Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 10 Jun 2025 13:23:46 -0700 Subject: [PATCH 04/95] improved error logging --- .../pipelines/NoRerankerRetrievalPipeline.ts | 10 +++++++++- .../pipelines/RerankerRetrievalPipeline.ts | 7 ++++++- core/util/posthog.ts | 19 +++++++++++++++++++ extensions/vscode/package-lock.json | 4 ++-- 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index f35809fed..ca88c479e 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -1,4 +1,5 @@ import { Chunk } from "../../../"; +import { Telemetry } from "../../../util/posthog"; import { findUriInDirs } from "../../../util/uri"; import { requestFilesFromRepoMap } from "../repoMapRequest"; import { deduplicateChunks } from "../util"; @@ -23,7 +24,8 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { try { ftsChunks = await this.retrieveFts(args, ftsNFinal); } catch (error) { - console.error("Error retrieving FTS chunks:", error); + await Telemetry.captureError("no_reranker_fts_retrieval", error); + // console.error("Error retrieving FTS chunks:", error); } let embeddingsChunks: Chunk[] = []; @@ -32,6 +34,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { ? await this.retrieveEmbeddings(input, embeddingsNFinal) : []; } catch (error) { + await Telemetry.captureError("no_reranker_embeddings_retrieval", error); console.error("Error retrieving embeddings:", error); } @@ -40,6 +43,10 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); } catch (error) { + await Telemetry.captureError( + "no_reranker_recently_edited_retrieval", + error, + ); console.error("Error retrieving recently edited files:", error); } @@ -53,6 +60,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { filterDirectory, ); } catch (error) { + await Telemetry.captureError("no_reranker_repo_map_retrieval", error); console.error("Error retrieving repo map chunks:", error); } diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index e73edf118..28de3d096 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -1,5 +1,6 @@ import { Chunk } from "../../.."; import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { Telemetry } from "../../../util/posthog"; import { findUriInDirs } from "../../../util/uri"; import { requestFilesFromRepoMap } from "../repoMapRequest"; import { deduplicateChunks } from "../util"; @@ -20,7 +21,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { try { ftsChunks = await this.retrieveFts(args, nRetrieve); } catch (error) { - console.error("Error retrieving FTS chunks:", error); + await Telemetry.captureError("reranker_fts_retrieval", error); + // console.error("Error retrieving FTS chunks:", error); } let embeddingsChunks: Chunk[] = []; @@ -29,6 +31,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { ? await this.retrieveEmbeddings(input, nRetrieve) : []; } catch (error) { + await Telemetry.captureError("reranker_embeddings_retrieval", error); console.error("Error retrieving embeddings chunks:", error); } @@ -37,6 +40,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); } catch (error) { + await Telemetry.captureError("reranker_recently_edited_retrieval", error); console.error("Error retrieving recently edited files chunks:", error); } @@ -50,6 +54,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { filterDirectory, ); } catch (error) { + await Telemetry.captureError("reranker_repo_map_retrieval", error); console.error("Error retrieving repo map chunks:", error); } diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 25b3ab600..dfde657fb 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -4,6 +4,7 @@ import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; import type { PostHog as PostHogType } from "posthog-node"; +import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js"; export enum PosthogFeatureFlag { AutocompleteTimeout = "autocomplete-timeout", @@ -37,6 +38,24 @@ export class Telemetry { static os: string | undefined = undefined; static ideInfo: IdeInfo | undefined = undefined; + /** + * Convenience method for capturing errors in a single event + */ + static async captureError(errorName: string, error: unknown) { + if (!(error instanceof Error)) { + return; + } + await Telemetry.capture( + "extension_error_caught", + { + errorName, + message: error.message, + stack: extractMinimalStackTraceInfo(error.stack), + }, + false, + ); + } + static async capture( event: string, properties: { [key: string]: any }, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8d4221fa2..f66fd08f3 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.45", + "version": "1.1.46", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.45", + "version": "1.1.46", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From 498e90778831d3b5bf517c81ab92aa5639c9fe84 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 12 Jun 2025 17:52:13 +0530 Subject: [PATCH 05/95] chore: migrate core (commands) tests to vitest --- core/commands/util.test.ts | 3 ++- core/jest.config.js | 1 + core/vitest.config.ts | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/core/commands/util.test.ts b/core/commands/util.test.ts index 447ec0e60..656903aa5 100644 --- a/core/commands/util.test.ts +++ b/core/commands/util.test.ts @@ -1,5 +1,6 @@ -import { ctxItemToRifWithContents } from "./util"; +import { describe, expect, it } from "vitest"; import { ContextItemWithId, RangeInFileWithContents } from "../index"; +import { ctxItemToRifWithContents } from "./util"; describe("ctxItemToRifWithContents", () => { it("should parse start and end lines from the item name when format is valid", () => { diff --git a/core/jest.config.js b/core/jest.config.js index 75bb11e9a..7bc65548e 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -35,5 +35,6 @@ export default { testPathIgnorePatterns: [ "/config/yaml/LocalPlatformClient.test.ts", "/autocomplete/", + "/commands/", ], }; diff --git a/core/vitest.config.ts b/core/vitest.config.ts index d781d152d..0bad68f69 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -13,6 +13,7 @@ export default defineConfig({ "**/*.vitest.ts", "config/yaml/LocalPlatformClient.test.ts", "autocomplete/**/*.test.ts", + "commands/**/*.test.ts", ], }, }); From 27c19aa6ceaf9ad0ca0789628fe2aab80d9b693d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 13 Jun 2025 19:27:03 +0530 Subject: [PATCH 06/95] migrate `control-plane` to vitest --- core/control-plane/mdm/mdm.test.ts | 1 + core/jest.config.js | 1 + core/vitest.config.ts | 1 + 3 files changed, 3 insertions(+) diff --git a/core/control-plane/mdm/mdm.test.ts b/core/control-plane/mdm/mdm.test.ts index ca4f5f0ec..193960e27 100644 --- a/core/control-plane/mdm/mdm.test.ts +++ b/core/control-plane/mdm/mdm.test.ts @@ -1,4 +1,5 @@ import * as crypto from "crypto"; +import { expect, test } from "vitest"; import { LicenseKeyData, validateLicenseKey } from "./mdm"; // We'll create a real key pair once for all tests diff --git a/core/jest.config.js b/core/jest.config.js index 7bc65548e..b00bd7099 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -36,5 +36,6 @@ export default { "/config/yaml/LocalPlatformClient.test.ts", "/autocomplete/", "/commands/", + "/control-plane/", ], }; diff --git a/core/vitest.config.ts b/core/vitest.config.ts index 0bad68f69..dc7d7dc91 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -14,6 +14,7 @@ export default defineConfig({ "config/yaml/LocalPlatformClient.test.ts", "autocomplete/**/*.test.ts", "commands/**/*.test.ts", + "control-plane/**/*.test.ts", ], }, }); From 4eb5b777a5a50b1f083fe260891fd5c1d5e74846 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 13 Jun 2025 19:28:17 +0530 Subject: [PATCH 07/95] migrate `data` to vitest --- core/data/log.test.ts | 24 ++++++++++++++++-------- core/jest.config.js | 1 + core/vitest.config.ts | 1 + 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/core/data/log.test.ts b/core/data/log.test.ts index 1b7b42b2e..f79e05130 100644 --- a/core/data/log.test.ts +++ b/core/data/log.test.ts @@ -1,13 +1,22 @@ import { DevDataLogEvent } from "@continuedev/config-yaml"; import fs from "fs"; import path from "path"; +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; import { IdeInfo, IdeSettings } from ".."; import { Core } from "../core"; import { getDevDataFilePath } from "../util/paths"; import { DataLogger } from "./log"; // Only mock fetch, not fs -jest.mock("@continuedev/fetch"); +vi.mock("@continuedev/fetch"); const TEST_EVENT: DevDataLogEvent = { name: "tokensGenerated", @@ -54,7 +63,7 @@ describe("DataLogger", () => { beforeEach(() => { // Reset mocks - jest.clearAllMocks(); + vi.clearAllMocks(); // Remove test file if it exists if (fs.existsSync(testFilePath)) { @@ -67,7 +76,7 @@ describe("DataLogger", () => { // Mock core and required promises dataLogger.core = { configHandler: { - loadConfig: jest.fn().mockResolvedValue({ + loadConfig: vi.fn().mockResolvedValue({ config: { data: [], }, @@ -78,7 +87,7 @@ describe("DataLogger", () => { }, }, controlPlaneClient: { - getAccessToken: jest.fn().mockResolvedValue("test-access-token"), + getAccessToken: vi.fn().mockResolvedValue("test-access-token"), }, }, } as unknown as Core; @@ -184,7 +193,6 @@ describe("DataLogger", () => { // Read file contents and verify const fileContent = fs.readFileSync(filepath, "utf8"); - console.log("debug1 filecontent", fileContent); expect(fileContent).toContain('"eventName":"chatInteraction"'); expect(fileContent).toContain('"prompt":"Hello, world!"'); expect(fileContent).toContain('"completion":"Hello, world!"'); @@ -195,10 +203,10 @@ describe("DataLogger", () => { describe("logDevData", () => { it("should log data locally and to configured destinations", async () => { // Spy on logLocalData and logToOneDestination - const logLocalDataSpy = jest + const logLocalDataSpy = vi .spyOn(dataLogger, "logLocalData") .mockResolvedValue(); - const logToOneDestinationSpy = jest + const logToOneDestinationSpy = vi .spyOn(dataLogger, "logToOneDestination") .mockResolvedValue(); @@ -212,7 +220,7 @@ describe("DataLogger", () => { }, }; - dataLogger.core!.configHandler.loadConfig = jest + dataLogger.core!.configHandler.loadConfig = vi .fn() .mockResolvedValue(mockConfig); diff --git a/core/jest.config.js b/core/jest.config.js index b00bd7099..da0bb3a79 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -37,5 +37,6 @@ export default { "/autocomplete/", "/commands/", "/control-plane/", + "/data/", ], }; diff --git a/core/vitest.config.ts b/core/vitest.config.ts index dc7d7dc91..129c71a03 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -15,6 +15,7 @@ export default defineConfig({ "autocomplete/**/*.test.ts", "commands/**/*.test.ts", "control-plane/**/*.test.ts", + "data/**/*.test.ts", ], }, }); From c86fb9cfcbd4c02d2976cee59d11402e62d3a726 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 13 Jun 2025 19:29:41 +0530 Subject: [PATCH 08/95] migrate `diff` folder --- core/diff/myers.test.ts | 2 ++ core/diff/streamDiff.test.ts | 9 +++------ core/diff/util.test.ts | 8 ++++---- core/jest.config.js | 1 + core/vitest.config.ts | 1 + 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/core/diff/myers.test.ts b/core/diff/myers.test.ts index 0683e5a96..a5902142a 100644 --- a/core/diff/myers.test.ts +++ b/core/diff/myers.test.ts @@ -1,3 +1,5 @@ +import { describe, expect, test } from "vitest"; + import { dedent } from "../util"; import { myersDiff } from "./myers"; diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.test.ts index 560d2e13d..57c6e77f1 100644 --- a/core/diff/streamDiff.test.ts +++ b/core/diff/streamDiff.test.ts @@ -1,6 +1,8 @@ import fs from "node:fs"; import path from "node:path"; +import { describe, expect, test } from "vitest"; + // @ts-ignore no typings available import { changed, diff as myersDiff } from "myers-diff"; import { streamDiff } from "../diff/streamDiff.js"; @@ -54,12 +56,7 @@ function displayDiff(diff: DiffLine[]) { } async function expectDiff(file: string) { - const testFilePath = path.join( - __dirname, - "diff", - "test-examples", - file + ".diff", - ); + const testFilePath = path.join(__dirname, "test-examples", file + ".diff"); const testFileContents = fs.readFileSync(testFilePath, "utf-8"); const [oldText, newText, expectedDiff] = testFileContents .split("\n---\n") diff --git a/core/diff/util.test.ts b/core/diff/util.test.ts index fca80ba6a..b94ab6317 100644 --- a/core/diff/util.test.ts +++ b/core/diff/util.test.ts @@ -1,8 +1,8 @@ // Generated by continue -import { matchLine, streamLines, generateLines } from "./util"; +import { describe, expect, it, vi } from "vitest"; import { ChatMessage } from "../index"; -import { jest } from "@jest/globals"; +import { generateLines, matchLine, streamLines } from "./util"; describe.skip("matchLine", () => { it("should match empty lines if the first old line is also empty", () => { @@ -146,7 +146,7 @@ describe("streamLines", () => { content: "line4", }; - // const spy = jest.spyOn(messageContentModule, "renderChatMessage"); + // const spy = vi.spyOn(messageContentModule, "renderChatMessage"); async function* streamCompletion(): AsyncGenerator { yield messageChunk1; @@ -164,7 +164,7 @@ describe("streamLines", () => { }); it("should log lines if log parameter is true", async () => { - const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {}); + const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {}); async function* streamCompletion(): AsyncGenerator { yield "line1\nline2\n"; diff --git a/core/jest.config.js b/core/jest.config.js index da0bb3a79..6c8a12faf 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -38,5 +38,6 @@ export default { "/commands/", "/control-plane/", "/data/", + "/diff/", ], }; diff --git a/core/vitest.config.ts b/core/vitest.config.ts index 129c71a03..b3c387fdb 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -16,6 +16,7 @@ export default defineConfig({ "commands/**/*.test.ts", "control-plane/**/*.test.ts", "data/**/*.test.ts", + "diff/**/*.test.ts", ], }, }); From 6226ed63dfb6adcb705af775ae6b86ae6634797d Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 16 Jun 2025 09:47:02 -0700 Subject: [PATCH 09/95] change icon for grep search tool --- gui/src/pages/gui/ToolCallDiv/index.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index d3f2edb09..9f867356e 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -2,7 +2,6 @@ import { ArrowRightIcon, CheckIcon, CodeBracketIcon, - CommandLineIcon, DocumentIcon, DocumentTextIcon, FolderIcon, @@ -37,7 +36,7 @@ interface ToolCallDivProps { const toolCallIcons: Record = { [BuiltInToolNames.FileGlobSearch]: MagnifyingGlassIcon, - [BuiltInToolNames.GrepSearch]: CommandLineIcon, + [BuiltInToolNames.GrepSearch]: MagnifyingGlassIcon, [BuiltInToolNames.LSTool]: FolderIcon, [BuiltInToolNames.ReadCurrentlyOpenFile]: DocumentTextIcon, [BuiltInToolNames.ReadFile]: DocumentIcon, From 5c94ec06dbf89f8d6e3f811cda629c62c169fe26 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 12:15:54 -0700 Subject: [PATCH 10/95] test: alwaysApply --- core/llm/rules/alwaysApply.vitest.ts | 186 +++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 core/llm/rules/alwaysApply.vitest.ts diff --git a/core/llm/rules/alwaysApply.vitest.ts b/core/llm/rules/alwaysApply.vitest.ts new file mode 100644 index 000000000..f8d6e1160 --- /dev/null +++ b/core/llm/rules/alwaysApply.vitest.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from "vitest"; +import { + ContextItemId, + ContextItemWithId, + RuleWithSource, + UserChatMessage, +} from "../.."; +import { getApplicableRules } from "./getSystemMessageWithRules"; + +describe("alwaysApply Behavior", () => { + // Common test fixtures + const testFile = "src/app.ts"; + const matchingFile = "src/components/Button.tsx"; + const nonMatchingFile = "src/utils/helper.js"; // Not matching *.tsx glob + + // File context items + const matchingFileContext: ContextItemWithId = { + id: { providerTitle: "file", itemId: "match1" } as ContextItemId, + uri: { type: "file", value: matchingFile }, + content: "export const Button = () => {...}", + name: "Button.tsx", + description: "Component file", + }; + + const nonMatchingFileContext: ContextItemWithId = { + id: { providerTitle: "file", itemId: "nonmatch1" } as ContextItemId, + uri: { type: "file", value: nonMatchingFile }, + content: "export const helper = () => {...}", + name: "helper.js", + description: "Helper file", + }; + + // Message with no file references + const messageWithoutFile: UserChatMessage = { + role: "user", + content: "Can you help me understand how this works?", + }; + + it("alwaysApply: true - Always include the rule, regardless of file context", () => { + // Rule with alwaysApply: true + const alwaysApplyRule: RuleWithSource = { + name: "Always Apply Rule", + rule: "This rule should always be applied", + alwaysApply: true, + globs: "**/*.tsx", // Should be ignored since alwaysApply is true + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Test with no file context + let applicableRules = getApplicableRules( + messageWithoutFile, + [alwaysApplyRule], + [], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Always Apply Rule"); + + // Test with matching file + applicableRules = getApplicableRules( + undefined, + [alwaysApplyRule], + [matchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Always Apply Rule"); + + // Test with non-matching file + applicableRules = getApplicableRules( + undefined, + [alwaysApplyRule], + [nonMatchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Always Apply Rule"); + }); + + it("alwaysApply: false - Only include if globs exist AND match file context", () => { + // Rule with alwaysApply: false and globs + const conditionalRule: RuleWithSource = { + name: "Conditional Rule", + rule: "Apply only to matching files", + alwaysApply: false, + globs: "**/*.tsx", + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Rule with alwaysApply: false and no globs + const neverApplyRule: RuleWithSource = { + name: "Never Apply Rule", + rule: "This rule should never apply", + alwaysApply: false, + // No globs + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Test with no file context + let applicableRules = getApplicableRules( + messageWithoutFile, + [conditionalRule, neverApplyRule], + [], + ); + expect(applicableRules).toHaveLength(0); // No rules should apply + + // Test with matching file + applicableRules = getApplicableRules( + undefined, + [conditionalRule, neverApplyRule], + [matchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Conditional Rule"); + expect(applicableRules.map((r) => r.name)).not.toContain( + "Never Apply Rule", + ); + + // Test with non-matching file + applicableRules = getApplicableRules( + undefined, + [conditionalRule, neverApplyRule], + [nonMatchingFileContext], + ); + expect(applicableRules).toHaveLength(0); // No rules should apply + }); + + it("alwaysApply: undefined - Default behavior: include if no globs exist OR globs exist and match", () => { + // Rule with undefined alwaysApply and no globs (should behave like a global rule) + const defaultNoGlobsRule: RuleWithSource = { + name: "Default No Globs Rule", + rule: "Default rule with no globs", + source: "rules-block", + ruleFile: ".continue/rules.md", + // No alwaysApply, no globs + }; + + // Rule with undefined alwaysApply and globs + const defaultWithGlobsRule: RuleWithSource = { + name: "Default With Globs Rule", + rule: "Default rule with globs", + globs: "**/*.tsx", + source: "rules-block", + ruleFile: ".continue/rules.md", + // No alwaysApply, with globs + }; + + // Test with no file context + let applicableRules = getApplicableRules( + messageWithoutFile, + [defaultNoGlobsRule, defaultWithGlobsRule], + [], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Default No Globs Rule"); + expect(applicableRules.map((r) => r.name)).not.toContain( + "Default With Globs Rule", + ); + + // Test with matching file + applicableRules = getApplicableRules( + undefined, + [defaultNoGlobsRule, defaultWithGlobsRule], + [matchingFileContext], + ); + expect(applicableRules).toHaveLength(2); + expect(applicableRules.map((r) => r.name)).toContain( + "Default No Globs Rule", + ); + expect(applicableRules.map((r) => r.name)).toContain( + "Default With Globs Rule", + ); + + // Test with non-matching file + applicableRules = getApplicableRules( + undefined, + [defaultNoGlobsRule, defaultWithGlobsRule], + [nonMatchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Default No Globs Rule"); + expect(applicableRules.map((r) => r.name)).not.toContain( + "Default With Globs Rule", + ); + }); +}); From a1e1ecf0939dc53cae56e58ec3ee9b67ca4dd55f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 13:03:36 -0700 Subject: [PATCH 11/95] Update uiSlice.ts --- gui/src/redux/slices/uiSlice.ts | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index dcdddafb1..4a0bcae32 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -1,5 +1,5 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { Tool } from "core"; +import { RuleWithSource, Tool } from "core"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn"; import { defaultOnboardingCardState, @@ -12,9 +12,12 @@ export type ToolPolicy = | "allowedWithoutPermission" | "disabled"; +export type RulePolicy = "always" | "auto" | "never"; + export type ToolGroupPolicy = "include" | "exclude"; export type ToolPolicies = { [toolName: string]: ToolPolicy }; +export type RulePolicies = { [ruleName: string]: RulePolicy }; export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy }; type UIState = { @@ -27,10 +30,12 @@ type UIState = { shouldAddFileForEditing: boolean; toolSettings: ToolPolicies; toolGroupSettings: ToolGroupPolicies; + ruleSettings: RulePolicies; ttsActive: boolean; }; export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission"; +export const DEFAULT_RULE_SETTING: RulePolicy = "auto"; export const uiSlice = createSlice({ name: "ui", @@ -62,6 +67,7 @@ export const uiSlice = createSlice({ toolGroupSettings: { [BUILT_IN_GROUP_NAME]: "include", }, + ruleSettings: {}, } as UIState, reducers: { setOnboardingCard: ( @@ -126,6 +132,28 @@ export const uiSlice = createSlice({ state.toolGroupSettings[action.payload] = "include"; } }, + // Rules + addRule: (state, action: PayloadAction) => { + state.ruleSettings[action.payload.name] = DEFAULT_RULE_SETTING; + }, + toggleRuleSetting: (state, action: PayloadAction) => { + const setting = state.ruleSettings[action.payload]; + + switch (setting) { + case "auto": + state.ruleSettings[action.payload] = "always"; + break; + case "always": + state.ruleSettings[action.payload] = "never"; + break; + case "never": + state.ruleSettings[action.payload] = "auto"; + break; + default: + state.ruleSettings[action.payload] = DEFAULT_RULE_SETTING; + break; + } + }, setTTSActive: (state, { payload }: PayloadAction) => { state.ttsActive = payload; }, @@ -142,6 +170,8 @@ export const { toggleToolSetting, toggleToolGroupSetting, addTool, + addRule, + toggleRuleSetting, setTTSActive, } = uiSlice.actions; From 8a2ffb3a859d4fbec3299500a0d860c0f725573d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 13:08:10 -0700 Subject: [PATCH 12/95] feat: rules policies --- core/llm/rules/getSystemMessageWithRules.ts | 34 +++-- .../Lump/sections/rules/RulePolicyItem.tsx | 118 ++++++++++++++++++ .../sections/rules/RulesSectionTooltip.tsx | 21 ++++ 3 files changed, 162 insertions(+), 11 deletions(-) create mode 100644 gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx create mode 100644 gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index e83a2cbfc..cbb89817c 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -120,7 +120,20 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { export const shouldApplyRule = ( rule: RuleWithSource, filePaths: string[], + rulePolicies: RulePolicies = {}, ): boolean => { + const policy = rulePolicies[rule.name]; + + // Always apply if policy is "always" + if (policy === "always") { + return true; + } + + // Never apply if policy is "never" + if (policy === "never") { + return false; + } + // If it's a global rule, always apply it regardless of file paths if (isGlobalRule(rule)) { return true; @@ -196,6 +209,7 @@ export const getApplicableRules = ( userMessage: UserChatMessage | ToolResultChatMessage | undefined, rules: RuleWithSource[], contextItems: ContextItemWithId[], + rulePolicies: RulePolicies = {}, ): RuleWithSource[] => { // First, extract any global rules that should always apply const globalRules = rules.filter((rule) => isGlobalRule(rule)); @@ -221,33 +235,31 @@ export const getApplicableRules = ( // Get rules that match file paths const matchingRules = rules .filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them - .filter((rule) => shouldApplyRule(rule, allFilePaths)); + .filter((rule) => shouldApplyRule(rule, allFilePaths, rulePolicies)); // Combine global rules with matching rules, ensuring no duplicates return [...globalRules, ...matchingRules]; }; -/** - * Creates a system message string with applicable rules appended - * - * @param baseSystemMessage - The base system message to start with - * @param userMessage - The user message to check for file paths - * @param rules - The list of rules to filter - * @param contextItems - Context items to check for file paths - * @returns System message with applicable rules appended - */ export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, rules, contextItems, + rulePolicies = {}, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; rules: RuleWithSource[]; contextItems: ContextItemWithId[]; + rulePolicies?: RulePolicies; }) => { - const applicableRules = getApplicableRules(userMessage, rules, contextItems); + const applicableRules = getApplicableRules( + userMessage, + rules, + contextItems, + rulePolicies, + ); let systemMessage = baseSystemMessage ?? ""; for (const rule of applicableRules) { diff --git a/gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx new file mode 100644 index 000000000..0639a9d2a --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx @@ -0,0 +1,118 @@ +// gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx +import { ChevronRightIcon } from "@heroicons/react/24/outline"; +import { RuleWithSource } from "core"; +import { useEffect, useState } from "react"; +import { useDispatch } from "react-redux"; +import { useAppSelector } from "../../../../../redux/hooks"; +import { + addRule, + toggleRuleSetting, +} from "../../../../../redux/slices/uiSlice"; +import { useFontSize } from "../../../../ui/font"; + +interface RulePolicyItemProps { + rule: RuleWithSource; +} + +export function RulePolicyItem(props: RulePolicyItemProps) { + const dispatch = useDispatch(); + const policy = useAppSelector( + (state) => state.ui.ruleSettings[props.rule.name], + ); + const [isExpanded, setIsExpanded] = useState(false); + + useEffect(() => { + if (!policy) { + dispatch(addRule(props.rule)); + } + }, [props.rule.name, policy]); + + const fontSize = useFontSize(-2); + + if (!policy) { + return null; + } + + return ( +
+
+
setIsExpanded((val) => !val)} + > +
+
{ + dispatch(toggleRuleSetting(props.rule.name)); + e.stopPropagation(); + e.preventDefault(); + }} + > + {policy === "never" ? ( + <> + Off + + Never + + + ) : policy === "auto" ? ( + <> + Auto + Auto + + ) : ( + // always + <> + On + + Always + + + )} +
+
+
+ Rule: + {props.rule.rule} + {props.rule.globs && ( + <> + Applies to: + + {typeof props.rule.globs === "string" + ? props.rule.globs + : props.rule.globs.join(", ")} + + + )} + {props.rule.ruleFile && ( + <> + Source: + {props.rule.ruleFile} + + )} +
+
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx b/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx new file mode 100644 index 000000000..2505147af --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx @@ -0,0 +1,21 @@ +// gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx +export const RulesSectionTooltip = () => ( +
+

+ Rules allow you to control how coding + standards and preferences are applied. +

+
    +
  • + Always: Rule will always be applied, regardless of + context +
  • +
  • + Auto: Rule will be applied based on file matching +
  • +
  • + Never: Rule will never be applied +
  • +
+
+); From 9c8bbd99e904040685c916d1cb0881e2079f140f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 13:19:51 -0700 Subject: [PATCH 13/95] Update RulesSection.tsx --- .../mainInput/Lump/sections/RulesSection.tsx | 50 +++++++++++++++++-- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 3617ae632..2972ef4e8 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -2,6 +2,7 @@ import { parseConfigYaml } from "@continuedev/config-yaml"; import { ArrowsPointingOutIcon, EyeIcon, + InformationCircleIcon, PencilIcon, } from "@heroicons/react/24/outline"; import { RuleWithSource } from "core"; @@ -11,7 +12,7 @@ import { DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, } from "core/llm/constructMessages"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; @@ -22,6 +23,8 @@ import { import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; +import { RulePolicyItem } from "./rules/RulePolicyItem"; +import { RulesSectionTooltip } from "./rules/RulesSectionTooltip"; interface RuleCardProps { rule: RuleWithSource; @@ -146,6 +149,7 @@ const RuleCard: React.FC = ({ rule }) => { export function RulesSection() { const { selectedProfile } = useAuth(); + const [showPolicies, setShowPolicies] = useState(false); const config = useAppSelector((store) => store.config.config); const mode = useAppSelector((store) => store.session.mode); @@ -213,12 +217,48 @@ export function RulesSection() { return rules; }, [config, selectedProfile, mode]); + const namedRules = useMemo(() => { + return sortedRules.filter((rule) => rule.name); + }, [sortedRules]); + return (
- {sortedRules.map((rule, index) => ( - - ))} - +
+ + +
+ +
+ +
+
+
+
+ + {showPolicies ? ( +
+ {namedRules.map((rule, index) => ( + + ))} + {namedRules.length === 0 && ( +
+ No rules with names available to configure policies. +
+ )} +
+ ) : ( + <> + {sortedRules.map((rule, index) => ( + + ))} + + + )}
); } From f976e54dc3b2b8072aef3ecadf259ee1e5299956 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 13:27:36 -0700 Subject: [PATCH 14/95] fix: type errors --- core/llm/rules/getSystemMessageWithRules.ts | 1 + core/llm/rules/types.ts | 2 ++ 2 files changed, 3 insertions(+) create mode 100644 core/llm/rules/types.ts diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index cbb89817c..3b22212d8 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -8,6 +8,7 @@ import { import { renderChatMessage } from "../../util/messageContent"; import { getCleanUriPath } from "../../util/uri"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; +import { RulePolicies } from "./types"; /** * Checks if a path matches any of the provided globs diff --git a/core/llm/rules/types.ts b/core/llm/rules/types.ts new file mode 100644 index 000000000..91154f9c3 --- /dev/null +++ b/core/llm/rules/types.ts @@ -0,0 +1,2 @@ +export type RulePolicy = "always" | "auto" | "never"; +export type RulePolicies = { [ruleName: string]: RulePolicy }; From 765141f0e494d5980e3bcbec563cfbf0c613301e Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 13:28:26 -0700 Subject: [PATCH 15/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 3b22212d8..25c8b11c6 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -123,7 +123,7 @@ export const shouldApplyRule = ( filePaths: string[], rulePolicies: RulePolicies = {}, ): boolean => { - const policy = rulePolicies[rule.name]; + const policy = rulePolicies[rule.name || ""]; // Always apply if policy is "always" if (policy === "always") { From e6cd458b5af5d64df9bed541a61cf3052c9207f1 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 13:59:18 -0700 Subject: [PATCH 16/95] Update RulesSection.tsx --- .../mainInput/Lump/sections/RulesSection.tsx | 101 ++++++++++-------- 1 file changed, 55 insertions(+), 46 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 2972ef4e8..9e29392a2 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -12,18 +12,19 @@ import { DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, } from "core/llm/constructMessages"; -import { useContext, useMemo, useState } from "react"; +import { useContext, useEffect, useMemo } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { + addRule, setDialogMessage, setShowDialog, + toggleRuleSetting, } from "../../../../redux/slices/uiSlice"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; -import { RulePolicyItem } from "./rules/RulePolicyItem"; import { RulesSectionTooltip } from "./rules/RulesSectionTooltip"; interface RuleCardProps { @@ -34,6 +35,14 @@ const RuleCard: React.FC = ({ rule }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const mode = useAppSelector((store) => store.session.mode); + const policy = useAppSelector((state) => state.ui.ruleSettings[rule.name]); + + // Ensure the rule is added to settings + useEffect(() => { + if (rule.name && !policy) { + dispatch(addRule(rule)); + } + }, [rule.name, policy, dispatch, rule]); const handleOpen = async () => { if (rule.slug) { @@ -56,6 +65,14 @@ const RuleCard: React.FC = ({ rule }) => { } }; + const handleTogglePolicy = (e) => { + if (rule.name) { + dispatch(toggleRuleSetting(rule.name)); + e.stopPropagation(); + e.preventDefault(); + } + }; + const title = useMemo(() => { if (rule.name) { return rule.name; @@ -104,20 +121,36 @@ const RuleCard: React.FC = ({ rule }) => { > {title} -
- - - {" "} - {rule.source === "default-chat" || - rule.source === "default-agent" ? ( - - - - ) : ( - - - +
+ {rule.name && policy && ( +
+ {policy === "never" ? ( + Never + ) : policy === "auto" ? ( + Auto + ) : ( + Always + )} +
)} +
+ + + {" "} + {rule.source === "default-chat" || + rule.source === "default-agent" ? ( + + + + ) : ( + + + + )} +
@@ -149,8 +182,6 @@ const RuleCard: React.FC = ({ rule }) => { export function RulesSection() { const { selectedProfile } = useAuth(); - const [showPolicies, setShowPolicies] = useState(false); - const config = useAppSelector((store) => store.config.config); const mode = useAppSelector((store) => store.session.mode); const sortedRules: RuleWithSource[] = useMemo(() => { @@ -217,19 +248,12 @@ export function RulesSection() { return rules; }, [config, selectedProfile, mode]); - const namedRules = useMemo(() => { - return sortedRules.filter((rule) => rule.name); - }, [sortedRules]); - return (
- +
+ Available Rules +
@@ -240,25 +264,10 @@ export function RulesSection() {
- {showPolicies ? ( -
- {namedRules.map((rule, index) => ( - - ))} - {namedRules.length === 0 && ( -
- No rules with names available to configure policies. -
- )} -
- ) : ( - <> - {sortedRules.map((rule, index) => ( - - ))} - - - )} + {sortedRules.map((rule, index) => ( + + ))} +
); } From cdedddd660c6a74da6c21951e36310411cae534d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:03:07 -0700 Subject: [PATCH 17/95] improv: ui --- .../Lump/sections/rules/RulePolicyItem.tsx | 118 ------------------ .../sections/rules/RulesSectionTooltip.tsx | 1 - 2 files changed, 119 deletions(-) delete mode 100644 gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx diff --git a/gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx deleted file mode 100644 index 0639a9d2a..000000000 --- a/gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx +++ /dev/null @@ -1,118 +0,0 @@ -// gui/src/components/mainInput/Lump/sections/rules/RulePolicyItem.tsx -import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { RuleWithSource } from "core"; -import { useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; -import { useAppSelector } from "../../../../../redux/hooks"; -import { - addRule, - toggleRuleSetting, -} from "../../../../../redux/slices/uiSlice"; -import { useFontSize } from "../../../../ui/font"; - -interface RulePolicyItemProps { - rule: RuleWithSource; -} - -export function RulePolicyItem(props: RulePolicyItemProps) { - const dispatch = useDispatch(); - const policy = useAppSelector( - (state) => state.ui.ruleSettings[props.rule.name], - ); - const [isExpanded, setIsExpanded] = useState(false); - - useEffect(() => { - if (!policy) { - dispatch(addRule(props.rule)); - } - }, [props.rule.name, policy]); - - const fontSize = useFontSize(-2); - - if (!policy) { - return null; - } - - return ( -
-
-
setIsExpanded((val) => !val)} - > -
-
{ - dispatch(toggleRuleSetting(props.rule.name)); - e.stopPropagation(); - e.preventDefault(); - }} - > - {policy === "never" ? ( - <> - Off - - Never - - - ) : policy === "auto" ? ( - <> - Auto - Auto - - ) : ( - // always - <> - On - - Always - - - )} -
-
-
- Rule: - {props.rule.rule} - {props.rule.globs && ( - <> - Applies to: - - {typeof props.rule.globs === "string" - ? props.rule.globs - : props.rule.globs.join(", ")} - - - )} - {props.rule.ruleFile && ( - <> - Source: - {props.rule.ruleFile} - - )} -
-
-
- ); -} diff --git a/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx b/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx index 2505147af..f5da60c54 100644 --- a/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx +++ b/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx @@ -1,4 +1,3 @@ -// gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx export const RulesSectionTooltip = () => (

From 8786f587f53f56b2de1558a07089bd507050ed91 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:05:31 -0700 Subject: [PATCH 18/95] Update RulesSection.tsx --- .../mainInput/Lump/sections/RulesSection.tsx | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 9e29392a2..8430cb78f 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -2,7 +2,6 @@ import { parseConfigYaml } from "@continuedev/config-yaml"; import { ArrowsPointingOutIcon, EyeIcon, - InformationCircleIcon, PencilIcon, } from "@heroicons/react/24/outline"; import { RuleWithSource } from "core"; @@ -25,7 +24,6 @@ import { import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; -import { RulesSectionTooltip } from "./rules/RulesSectionTooltip"; interface RuleCardProps { rule: RuleWithSource; @@ -250,20 +248,6 @@ export function RulesSection() { return (

-
-
- Available Rules -
- -
- -
- -
-
-
-
- {sortedRules.map((rule, index) => ( ))} From 11a10f852424cf16dcda5a1eb1f40dd2a6de65e8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:07:30 -0700 Subject: [PATCH 19/95] improv: clean up code --- .../mainInput/Lump/sections/RulesSection.tsx | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 8430cb78f..5c479accc 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -11,12 +11,11 @@ import { DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, } from "core/llm/constructMessages"; -import { useContext, useEffect, useMemo } from "react"; +import { useContext, useMemo } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { - addRule, setDialogMessage, setShowDialog, toggleRuleSetting, @@ -35,13 +34,6 @@ const RuleCard: React.FC = ({ rule }) => { const mode = useAppSelector((store) => store.session.mode); const policy = useAppSelector((state) => state.ui.ruleSettings[rule.name]); - // Ensure the rule is added to settings - useEffect(() => { - if (rule.name && !policy) { - dispatch(addRule(rule)); - } - }, [rule.name, policy, dispatch, rule]); - const handleOpen = async () => { if (rule.slug) { void ideMessenger.request("controlPlane/openUrl", { From 270d2a8a796a40109a86b2038391a517c769ce91 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:08:36 -0700 Subject: [PATCH 20/95] Update RulesSection.tsx --- gui/src/components/mainInput/Lump/sections/RulesSection.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 5c479accc..b4efd9e1f 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -32,7 +32,9 @@ const RuleCard: React.FC = ({ rule }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const mode = useAppSelector((store) => store.session.mode); - const policy = useAppSelector((state) => state.ui.ruleSettings[rule.name]); + const policy = useAppSelector( + (state) => state.ui.ruleSettings[rule.name || ""], + ); const handleOpen = async () => { if (rule.slug) { From bcae5b3cf210f1a8ced3b2c913961ed16aaf2ea9 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:16:09 -0700 Subject: [PATCH 21/95] fix: rules --- .../components/mainInput/Lump/sections/RulesSection.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index b4efd9e1f..f64850595 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -16,6 +16,7 @@ import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { + DEFAULT_RULE_SETTING, setDialogMessage, setShowDialog, toggleRuleSetting, @@ -32,8 +33,10 @@ const RuleCard: React.FC = ({ rule }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const mode = useAppSelector((store) => store.session.mode); - const policy = useAppSelector( - (state) => state.ui.ruleSettings[rule.name || ""], + const policy = useAppSelector((state) => + rule.name + ? state.ui.ruleSettings[rule.name] || DEFAULT_RULE_SETTING + : undefined, ); const handleOpen = async () => { From 56f38038b35cedc2aa1bca1b09780b21c811bd83 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:21:08 -0700 Subject: [PATCH 22/95] fix: settings persistance --- gui/src/redux/slices/uiSlice.ts | 2 +- gui/src/redux/store.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 4a0bcae32..ae4e205f4 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -134,7 +134,7 @@ export const uiSlice = createSlice({ }, // Rules addRule: (state, action: PayloadAction) => { - state.ruleSettings[action.payload.name] = DEFAULT_RULE_SETTING; + state.ruleSettings[action.payload.name!] = DEFAULT_RULE_SETTING; }, toggleRuleSetting: (state, action: PayloadAction) => { const setting = state.ruleSettings[action.payload]; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 1e0d098f3..806387691 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -58,7 +58,7 @@ const saveSubsetFilters = [ "codeToEdit", ]), createFilter("config", ["defaultModelTitle"]), - createFilter("ui", ["toolSettings", "toolGroupSettings"]), + createFilter("ui", ["toolSettings", "toolGroupSettings", "ruleSettings"]), createFilter("indexing", []), createFilter("tabs", ["tabs"]), createFilter("profiles", [ From 7b9c5cc4f062e2882706919b1effe34a460f45b8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:22:01 -0700 Subject: [PATCH 23/95] fix: types --- gui/src/components/mainInput/Lump/sections/RulesSection.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index f64850595..f23e8688c 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -11,7 +11,7 @@ import { DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, } from "core/llm/constructMessages"; -import { useContext, useMemo } from "react"; +import { MouseEventHandler, useContext, useMemo } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; @@ -60,7 +60,7 @@ const RuleCard: React.FC = ({ rule }) => { } }; - const handleTogglePolicy = (e) => { + const handleTogglePolicy: MouseEventHandler = (e) => { if (rule.name) { dispatch(toggleRuleSetting(rule.name)); e.stopPropagation(); From 3b44bc9564b359a24db5f84e10a5a68b8f087943 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 14:31:36 -0700 Subject: [PATCH 24/95] Update getSystemMessageWithRules.vitest.ts --- .../rules/getSystemMessageWithRules.vitest.ts | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 0e7bd39fe..2ea49494c 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { RuleWithSource } from "../.."; import { shouldApplyRule } from "./getSystemMessageWithRules"; +import { RulePolicies } from "./types"; describe("Rule colocation glob matching", () => { // This test file demonstrates the expected behavior after our fix @@ -132,3 +133,135 @@ describe("Rule colocation glob matching", () => { ); }); }); + +describe("Rule policies", () => { + const componentRule: RuleWithSource = { + name: "Components Rule", + rule: "Use functional components with hooks", + source: "rules-block", + ruleFile: "src/components/rules.md", + }; + + const testFiles = ["src/components/Button.tsx"]; + const nonMatchingFiles = ["src/utils/helpers.ts"]; + + it("should always apply rules with 'always' policy regardless of file paths", () => { + const rulePolicies: RulePolicies = { + "Components Rule": "always", + }; + + // Should apply even to non-matching files + expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe( + true, + ); + + // Should apply to empty file list + expect(shouldApplyRule(componentRule, [], rulePolicies)).toBe(true); + }); + + it("should never apply rules with 'never' policy regardless of file paths", () => { + const rulePolicies: RulePolicies = { + "Components Rule": "never", + }; + + // Should not apply even to matching files + expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false); + + // Rule with alwaysApply: true should still be overridden by 'never' policy + const alwaysApplyRule: RuleWithSource = { + name: "Always Apply Rule", + rule: "This rule would normally always apply", + alwaysApply: true, + source: "rules-block", + ruleFile: "src/components/rules.md", + }; + + const alwaysNeverPolicies: RulePolicies = { + "Always Apply Rule": "never", + }; + + expect( + shouldApplyRule(alwaysApplyRule, testFiles, alwaysNeverPolicies), + ).toBe(false); + }); + + it("should apply 'auto' policy rules based on normal matching logic", () => { + const rulePolicies: RulePolicies = { + "Components Rule": "auto", + }; + + // Should apply to matching files + expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true); + + // Should not apply to non-matching files + expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe( + false, + ); + }); + + it("should use default behavior when no policy is specified", () => { + // Empty policies object should use default behavior + const rulePolicies: RulePolicies = {}; + + // Should apply to matching files + expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true); + + // Should not apply to non-matching files + expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe( + false, + ); + }); + + it("should handle policy interaction with global rules", () => { + // Root level rule which would normally apply globally + const rootRule: RuleWithSource = { + name: "Root Rule", + rule: "Follow project standards", + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Never policy should override even global rules + const neverPolicies: RulePolicies = { + "Root Rule": "never", + }; + + expect(shouldApplyRule(rootRule, testFiles, neverPolicies)).toBe(false); + + // Auto policy should maintain global rule behavior + const autoPolicies: RulePolicies = { + "Root Rule": "auto", + }; + + expect(shouldApplyRule(rootRule, testFiles, autoPolicies)).toBe(true); + }); + + it("should prioritize policies over alwaysApply and directory restrictions", () => { + // Create rule with multiple matching criteria + const complexRule: RuleWithSource = { + name: "Complex Rule", + rule: "This rule has complex matching logic", + alwaysApply: true, + globs: "**/*.ts", + source: "rules-block", + ruleFile: "src/utils/rules.md", + }; + + // Always policy should win over everything + const alwaysPolicies: RulePolicies = { + "Complex Rule": "always", + }; + + expect(shouldApplyRule(complexRule, [], alwaysPolicies)).toBe(true); + + // Never policy should also win over everything + const neverPolicies: RulePolicies = { + "Complex Rule": "never", + }; + + // Even with matching files and alwaysApply: true, never policy wins + expect( + shouldApplyRule(complexRule, ["src/utils/test.ts"], neverPolicies), + ).toBe(false); + }); +}); From 91170460fd53947aad5fce84fb860d588738219c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 15:02:48 -0700 Subject: [PATCH 25/95] Update streamResponse.ts --- gui/src/redux/thunks/streamResponse.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 8f11fc7f5..caeded723 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -92,6 +92,7 @@ export const streamResponseThunk = createAsyncThunk< // 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 @@ -101,6 +102,7 @@ export const streamResponseThunk = createAsyncThunk< : undefined, rules, selectedContextItems, + rulePolicies, ); // Store in history for UI display @@ -122,6 +124,7 @@ export const streamResponseThunk = createAsyncThunk< [...updatedHistory], baseChatOrAgentSystemMessage, applicableRules, + rulePolicies, ); posthog.capture("step run", { From 4842cf54740f47b69c265a05f90b302ce563b6d7 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 15:04:47 -0700 Subject: [PATCH 26/95] Update constructMessages.ts --- core/llm/constructMessages.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 5358deee5..49115cb6f 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -11,6 +11,7 @@ import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; +import { RulePolicies } from "./rules/types"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; @@ -108,6 +109,7 @@ export function constructMessages( history: ChatHistoryItem[], baseChatOrAgentSystemMessage: string | undefined, rules: RuleWithSource[], + rulePolicies?: RulePolicies, ): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", @@ -164,6 +166,7 @@ export function constructMessages( rules, userMessage: lastUserMsg, contextItems: lastUserContextItems, + rulePolicies, }); if (systemMessage.trim()) { From e1a0da69fcc7ce413b7ce420468c88ab5e5ca78e Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 16:15:29 -0700 Subject: [PATCH 27/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 29 +++++++++------------ 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 25c8b11c6..1323b7e23 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -123,7 +123,10 @@ export const shouldApplyRule = ( filePaths: string[], rulePolicies: RulePolicies = {}, ): boolean => { + console.log("POLICIES", rulePolicies); + console.log("RULE ZZZ", rule); const policy = rulePolicies[rule.name || ""]; + console.log("POLICY", policy); // Always apply if policy is "always" if (policy === "always") { @@ -140,7 +143,7 @@ export const shouldApplyRule = ( return true; } - // If there are no file paths to check: + // If there are no file paths to check and we've made it here: // - We've already handled global rules above // - Don't apply other rules since we have no files to match against if (filePaths.length === 0) { @@ -212,10 +215,8 @@ export const getApplicableRules = ( contextItems: ContextItemWithId[], rulePolicies: RulePolicies = {}, ): RuleWithSource[] => { - // First, extract any global rules that should always apply - const globalRules = rules.filter((rule) => isGlobalRule(rule)); - - // Get file paths from message and context for regular rule matching + console.log("GET APPLICABLE"); + // Get file paths from message and context for rule matching const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) : []; @@ -228,18 +229,13 @@ export const getApplicableRules = ( // Combine file paths from both sources const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems]; - // If we have no file paths, just return the global rules - if (allFilePaths.length === 0) { - return globalRules; - } + // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, + // and path matching in a consistent way + const applicableRules = rules.filter((rule) => + shouldApplyRule(rule, allFilePaths, rulePolicies), + ); - // Get rules that match file paths - const matchingRules = rules - .filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them - .filter((rule) => shouldApplyRule(rule, allFilePaths, rulePolicies)); - - // Combine global rules with matching rules, ensuring no duplicates - return [...globalRules, ...matchingRules]; + return applicableRules; }; export const getSystemMessageWithRules = ({ @@ -255,6 +251,7 @@ export const getSystemMessageWithRules = ({ contextItems: ContextItemWithId[]; rulePolicies?: RulePolicies; }) => { + console.log("HERE ZZZZ"); const applicableRules = getApplicableRules( userMessage, rules, From de6a0ae36c43753e768bf0164dfbe1b938da790d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 16:22:08 -0700 Subject: [PATCH 28/95] fix: policy precedence --- core/llm/rules/alwaysApplyRules.vitest.ts | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts index 0508a1e38..44f82793a 100644 --- a/core/llm/rules/alwaysApplyRules.vitest.ts +++ b/core/llm/rules/alwaysApplyRules.vitest.ts @@ -6,6 +6,7 @@ import { UserChatMessage, } from "../.."; import { getApplicableRules } from "./getSystemMessageWithRules"; +import { RulePolicies } from "./types"; describe("Rule application with alwaysApply", () => { // Create an always-apply rule @@ -136,4 +137,38 @@ describe("Rule application with alwaysApply", () => { expect(applicableRules).toHaveLength(1); expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule"); }); + + it("should respect rulePolicies over alwaysApply when there are no file paths", () => { + // Rule with alwaysApply: true + const globalRule: RuleWithSource = { + name: "Global Rule", + rule: "This rule has alwaysApply: true but is blocked by rulePolicies", + alwaysApply: true, + source: "rules-block", + ruleFile: "src/some/path.md", + }; + + // Message with no code blocks or file references + const simpleMessage: UserChatMessage = { + role: "user", + content: "Can you help me with something?", + }; + + // Create a rule policy that blocks the rule + const rulePolicies: RulePolicies = { + "Global Rule": "never", + }; + + // The rule should NOT be applied due to the "never" policy, + // even though it has alwaysApply: true and there are no file paths + const applicableRules = getApplicableRules( + simpleMessage, + [globalRule], + [], + rulePolicies, + ); + + expect(applicableRules).toHaveLength(0); + expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule"); + }); }); From f5a8edfc916814c2932da0092948af1a9154701f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 17 Jun 2025 16:25:47 -0700 Subject: [PATCH 29/95] improv: clean up --- core/llm/rules/getSystemMessageWithRules.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 1323b7e23..9eaa3e12c 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -123,10 +123,7 @@ export const shouldApplyRule = ( filePaths: string[], rulePolicies: RulePolicies = {}, ): boolean => { - console.log("POLICIES", rulePolicies); - console.log("RULE ZZZ", rule); const policy = rulePolicies[rule.name || ""]; - console.log("POLICY", policy); // Always apply if policy is "always" if (policy === "always") { @@ -215,7 +212,6 @@ export const getApplicableRules = ( contextItems: ContextItemWithId[], rulePolicies: RulePolicies = {}, ): RuleWithSource[] => { - console.log("GET APPLICABLE"); // Get file paths from message and context for rule matching const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) @@ -251,7 +247,6 @@ export const getSystemMessageWithRules = ({ contextItems: ContextItemWithId[]; rulePolicies?: RulePolicies; }) => { - console.log("HERE ZZZZ"); const applicableRules = getApplicableRules( userMessage, rules, From ae97f1d6eb1469ac4805fa61134f0fb8556e7585 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 18 Jun 2025 10:50:14 -0700 Subject: [PATCH 30/95] add apply cancellation test --- core/edit/recursiveStream.ts | 1 - .../Lump/LumpToolbar/GeneratingIndicator.tsx | 4 +- .../Lump/LumpToolbar/IsApplyingToolbar.tsx | 5 +- gui/src/pages/gui/Chat.test.tsx | 52 +++++++++++++++++++ 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index 5a6d4b39b..004563cdb 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -68,7 +68,6 @@ export async function* recursiveStream( }); for await (const chunk of generator) { - console.log(chunk); yield chunk; const rendered = renderChatMessage(chunk); buffer += rendered; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx index 48c1571b4..1446d2720 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx @@ -2,11 +2,13 @@ import { AnimatedEllipsis } from "../../.."; export function GeneratingIndicator({ text = "Generating", + testId, }: { text?: string; + testId?: string; }) { return ( -
+
{text}
diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx index f4840088d..57ee2740a 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx @@ -13,15 +13,16 @@ export const IsApplyingToolbar = () => { return ( - + { // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option // Apply is prioritized because it can be more catastrophic // Intentional to be more WYSIWYG for now // Keyboard shortcut is handled in chat - dispatch(cancelStream()); + void dispatch(cancelStream()); ideMessenger.post("rejectDiff", {}); }} > diff --git a/gui/src/pages/gui/Chat.test.tsx b/gui/src/pages/gui/Chat.test.tsx index 626438350..1bf5dc09d 100644 --- a/gui/src/pages/gui/Chat.test.tsx +++ b/gui/src/pages/gui/Chat.test.tsx @@ -106,4 +106,56 @@ describe("Chat page test", () => { ).not.toBeInTheDocument(); }); }); + + it("should show apply cancellation", async () => { + const { ideMessenger } = await renderWithProviders(); + + // Spy on the request method of ideMessenger + const messengerPostSpy = vi.spyOn(ideMessenger, "post"); + + for (let i = 0; i < 5; i++) { + ideMessenger.mockMessageToWebview("updateApplyState", { + status: "streaming", + streamId: `12345`, + }); + } + + // Wait for applying toolbar to appear + await waitFor(() => { + const cancelApplyButton = screen.getByTestId( + "notch-applying-cancel-button", + ); + const applyingText = screen.getByTestId("notch-applying-text"); + + expect(cancelApplyButton).toBeInTheDocument(); + expect(applyingText).toBeInTheDocument(); + }); + + const cancelApplyButton = screen.getByTestId( + "notch-applying-cancel-button", + ); + cancelApplyButton.click(); + + // Verify that rejectDiff message has been posted to ideMessenger + expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {}); + + // Now simulate the IDE sending back a message that the apply state is closed + ideMessenger.mockMessageToWebview("updateApplyState", { + status: "closed", + streamId: "12345", + }); + + await waitFor(() => { + const cancelApplyButton = screen.queryByTestId( + "notch-applying-cancel-button", + ); + const applyingText = screen.queryByTestId("notch-applying-text"); + + expect(cancelApplyButton).not.toBeInTheDocument(); + expect(applyingText).not.toBeInTheDocument(); + }); + + // Cleanup spy + messengerPostSpy.mockRestore(); + }); }); From a6f030420f436050db089044eff536db2adb2f13 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 18 Jun 2025 13:48:17 -0700 Subject: [PATCH 31/95] programming principles rule --- .continue/rules/programming-principles.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .continue/rules/programming-principles.md diff --git a/.continue/rules/programming-principles.md b/.continue/rules/programming-principles.md new file mode 100644 index 000000000..0485f4f68 --- /dev/null +++ b/.continue/rules/programming-principles.md @@ -0,0 +1,6 @@ +--- +name: Programming principles +description: Guidelines for coding fundamentals in this project +--- + +Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions. From c3081d9d25649919013178aa0ce4b5821e0ff97a Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 14:54:53 -0700 Subject: [PATCH 32/95] improv: use on / off for rules --- core/llm/rules/alwaysApplyRules.vitest.ts | 6 +- core/llm/rules/getSystemMessageWithRules.ts | 9 +-- .../rules/getSystemMessageWithRules.vitest.ts | 69 +++++++------------ core/llm/rules/types.ts | 2 +- .../mainInput/Lump/sections/RulesSection.tsx | 39 ++++++----- gui/src/redux/slices/uiSlice.ts | 15 ++-- 6 files changed, 56 insertions(+), 84 deletions(-) diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts index 44f82793a..538ab03cf 100644 --- a/core/llm/rules/alwaysApplyRules.vitest.ts +++ b/core/llm/rules/alwaysApplyRules.vitest.ts @@ -138,7 +138,7 @@ describe("Rule application with alwaysApply", () => { expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule"); }); - it("should respect rulePolicies over alwaysApply when there are no file paths", () => { + it("should respect 'off' rulePolicies over alwaysApply when there are no file paths", () => { // Rule with alwaysApply: true const globalRule: RuleWithSource = { name: "Global Rule", @@ -156,10 +156,10 @@ describe("Rule application with alwaysApply", () => { // Create a rule policy that blocks the rule const rulePolicies: RulePolicies = { - "Global Rule": "never", + "Global Rule": "off", }; - // The rule should NOT be applied due to the "never" policy, + // The rule should NOT be applied due to the "off" policy, // even though it has alwaysApply: true and there are no file paths const applicableRules = getApplicableRules( simpleMessage, diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 9eaa3e12c..a0f3cf64f 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -125,13 +125,8 @@ export const shouldApplyRule = ( ): boolean => { const policy = rulePolicies[rule.name || ""]; - // Always apply if policy is "always" - if (policy === "always") { - return true; - } - - // Never apply if policy is "never" - if (policy === "never") { + // Never apply if policy is "off" + if (policy === "off") { return false; } diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 2ea49494c..f652d3a77 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -145,29 +145,15 @@ describe("Rule policies", () => { const testFiles = ["src/components/Button.tsx"]; const nonMatchingFiles = ["src/utils/helpers.ts"]; - it("should always apply rules with 'always' policy regardless of file paths", () => { + it("should never apply rules with 'off' policy regardless of file paths", () => { const rulePolicies: RulePolicies = { - "Components Rule": "always", - }; - - // Should apply even to non-matching files - expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe( - true, - ); - - // Should apply to empty file list - expect(shouldApplyRule(componentRule, [], rulePolicies)).toBe(true); - }); - - it("should never apply rules with 'never' policy regardless of file paths", () => { - const rulePolicies: RulePolicies = { - "Components Rule": "never", + "Components Rule": "off", }; // Should not apply even to matching files expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false); - // Rule with alwaysApply: true should still be overridden by 'never' policy + // Rule with alwaysApply: true should still be overridden by 'off' policy const alwaysApplyRule: RuleWithSource = { name: "Always Apply Rule", rule: "This rule would normally always apply", @@ -176,18 +162,18 @@ describe("Rule policies", () => { ruleFile: "src/components/rules.md", }; - const alwaysNeverPolicies: RulePolicies = { - "Always Apply Rule": "never", + const offPolicies: RulePolicies = { + "Always Apply Rule": "off", }; - expect( - shouldApplyRule(alwaysApplyRule, testFiles, alwaysNeverPolicies), - ).toBe(false); + expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe( + false, + ); }); - it("should apply 'auto' policy rules based on normal matching logic", () => { + it("should apply 'on' policy rules based on normal matching logic", () => { const rulePolicies: RulePolicies = { - "Components Rule": "auto", + "Components Rule": "on", }; // Should apply to matching files @@ -221,22 +207,22 @@ describe("Rule policies", () => { ruleFile: ".continue/rules.md", }; - // Never policy should override even global rules - const neverPolicies: RulePolicies = { - "Root Rule": "never", + // Off policy should override even global rules + const offPolicies: RulePolicies = { + "Root Rule": "off", }; - expect(shouldApplyRule(rootRule, testFiles, neverPolicies)).toBe(false); + expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false); - // Auto policy should maintain global rule behavior - const autoPolicies: RulePolicies = { - "Root Rule": "auto", + // On policy should maintain global rule behavior + const onPolicies: RulePolicies = { + "Root Rule": "on", }; - expect(shouldApplyRule(rootRule, testFiles, autoPolicies)).toBe(true); + expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true); }); - it("should prioritize policies over alwaysApply and directory restrictions", () => { + it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => { // Create rule with multiple matching criteria const complexRule: RuleWithSource = { name: "Complex Rule", @@ -247,21 +233,14 @@ describe("Rule policies", () => { ruleFile: "src/utils/rules.md", }; - // Always policy should win over everything - const alwaysPolicies: RulePolicies = { - "Complex Rule": "always", + // Off policy should win over everything + const offPolicies: RulePolicies = { + "Complex Rule": "off", }; - expect(shouldApplyRule(complexRule, [], alwaysPolicies)).toBe(true); - - // Never policy should also win over everything - const neverPolicies: RulePolicies = { - "Complex Rule": "never", - }; - - // Even with matching files and alwaysApply: true, never policy wins + // Even with matching files and alwaysApply: true, off policy wins expect( - shouldApplyRule(complexRule, ["src/utils/test.ts"], neverPolicies), + shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies), ).toBe(false); }); }); diff --git a/core/llm/rules/types.ts b/core/llm/rules/types.ts index 91154f9c3..f973d8260 100644 --- a/core/llm/rules/types.ts +++ b/core/llm/rules/types.ts @@ -1,2 +1,2 @@ -export type RulePolicy = "always" | "auto" | "never"; +export type RulePolicy = "on" | "off"; export type RulePolicies = { [ruleName: string]: RulePolicy }; diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index f23e8688c..1097805d2 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -11,7 +11,7 @@ import { DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, } from "core/llm/constructMessages"; -import { MouseEventHandler, useContext, useMemo } from "react"; +import { useContext, useMemo } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; @@ -22,6 +22,7 @@ import { toggleRuleSetting, } from "../../../../redux/slices/uiSlice"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; +import Switch from "../../../gui/Switch"; import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; @@ -39,6 +40,8 @@ const RuleCard: React.FC = ({ rule }) => { : undefined, ); + const isDisabled = policy === "off"; + const handleOpen = async () => { if (rule.slug) { void ideMessenger.request("controlPlane/openUrl", { @@ -60,11 +63,9 @@ const RuleCard: React.FC = ({ rule }) => { } }; - const handleTogglePolicy: MouseEventHandler = (e) => { + const handleTogglePolicy = () => { if (rule.name) { dispatch(toggleRuleSetting(rule.name)); - e.stopPropagation(); - e.preventDefault(); } }; @@ -105,11 +106,13 @@ const RuleCard: React.FC = ({ rule }) => { const smallFont = useFontSize(-2); const tinyFont = useFontSize(-3); return ( -
+
= ({ rule }) => {
{rule.name && policy && ( -
- {policy === "never" ? ( - Never - ) : policy === "auto" ? ( - Auto - ) : ( - Always - )} +
+ handleTogglePolicy()} + size={10} + text="" + />
)}
@@ -153,7 +152,7 @@ const RuleCard: React.FC = ({ rule }) => { style={{ fontSize: tinyFont, }} - className="mt-1 line-clamp-3 text-gray-400" + className={`mt-1 line-clamp-3 ${isDisabled ? "text-gray-500" : "text-gray-400"}`} > {rule.rule} @@ -165,7 +164,9 @@ const RuleCard: React.FC = ({ rule }) => { className="mt-1.5 flex flex-col gap-1" > Applies to files - + {rule.globs}
diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index ae4e205f4..15d6216a4 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -12,7 +12,7 @@ export type ToolPolicy = | "allowedWithoutPermission" | "disabled"; -export type RulePolicy = "always" | "auto" | "never"; +export type RulePolicy = "on" | "off"; export type ToolGroupPolicy = "include" | "exclude"; @@ -35,7 +35,7 @@ type UIState = { }; export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission"; -export const DEFAULT_RULE_SETTING: RulePolicy = "auto"; +export const DEFAULT_RULE_SETTING: RulePolicy = "on"; export const uiSlice = createSlice({ name: "ui", @@ -140,14 +140,11 @@ export const uiSlice = createSlice({ const setting = state.ruleSettings[action.payload]; switch (setting) { - case "auto": - state.ruleSettings[action.payload] = "always"; + case "on": + state.ruleSettings[action.payload] = "off"; break; - case "always": - state.ruleSettings[action.payload] = "never"; - break; - case "never": - state.ruleSettings[action.payload] = "auto"; + case "off": + state.ruleSettings[action.payload] = "on"; break; default: state.ruleSettings[action.payload] = DEFAULT_RULE_SETTING; From 07dc2c46cef00663900f0ef84d34d2bfa9437ac3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 15:31:29 -0700 Subject: [PATCH 33/95] feat: patterns --- core/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/index.d.ts b/core/index.d.ts index ce78a8d82..1c7f336f2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1576,12 +1576,12 @@ export interface RuleWithSource { slug?: string; source: RuleSource; globs?: string | string[]; + patterns?: string | string[]; rule: string; description?: string; ruleFile?: string; alwaysApply?: boolean; } - export interface CompleteOnboardingPayload { mode: OnboardingModes; provider?: string; From 3a33dc788711f739d79d0eff4f84320b27f08633 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 15:36:22 -0700 Subject: [PATCH 34/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index a0f3cf64f..00532bbed 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -52,6 +52,44 @@ const matchesGlobs = ( return false; }; +/** + * Checks if a path matches any of the provided regex patterns + */ +const matchesPatterns = ( + filePath: string, + patterns: string | string[] | undefined, +): boolean => { + if (!patterns) return true; + + // Handle single string pattern + if (typeof patterns === "string") { + try { + const regex = new RegExp(patterns); + return regex.test(filePath); + } catch (e) { + console.error(`Invalid regex pattern: ${patterns}`, e); + return false; + } + } + // Handle array of patterns + if (Array.isArray(patterns)) { + if (patterns.length === 0) return true; + + // File must match at least one pattern + return patterns.some((pattern) => { + try { + const regex = new RegExp(pattern); + return regex.test(filePath); + } catch (e) { + console.error(`Invalid regex pattern: ${pattern}`, e); + return false; + } + }); + } + + return false; +}; + /** * Determines if a file path is within a specific directory or its subdirectories * From 1703fce6507aad8fa1d283f7735c1399a48dbb14 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 15:40:38 -0700 Subject: [PATCH 35/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 89 ++++++++++++++++++--- 1 file changed, 79 insertions(+), 10 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 00532bbed..1c4f0f814 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -149,6 +149,13 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { return false; }; +/** + * Determines if a rule should be applied based on its alwaysApply property and file path matching + * + * @param rule - The rule to check + * @param filePaths - Array of file paths to check against the rule's globs + * @returns true if the rule should be applied, false otherwise + */ /** * Determines if a rule should be applied based on its alwaysApply property and file path matching * @@ -200,31 +207,93 @@ export const shouldApplyRule = ( return false; } - // If we have globs, check if any files in this directory match them - if (rule.globs) { + // Check both globs and patterns + const hasGlobs = rule.globs !== undefined; + const hasPatterns = rule.patterns !== undefined; + + // If we have both globs and patterns, check if any files match both + if (hasGlobs && hasPatterns) { + return filesInRuleDirectory.some( + (filePath) => + matchesGlobs(filePath, rule.globs) && + matchesPatterns(filePath, rule.patterns), + ); + } + + // If we only have globs, check those + if (hasGlobs) { return filesInRuleDirectory.some((filePath) => matchesGlobs(filePath, rule.globs), ); } - // No globs but files are in this directory, so apply the rule + // If we only have patterns, check those + if (hasPatterns) { + return filesInRuleDirectory.some((filePath) => + matchesPatterns(filePath, rule.patterns), + ); + } + + // No globs or patterns but files are in this directory, so apply the rule return true; } // For root-level rules: - // If alwaysApply is explicitly false, only apply if there are globs AND they match + // If alwaysApply is explicitly false, only apply if there are globs AND/OR patterns AND they match if (rule.alwaysApply === false) { - if (!rule.globs) { + const hasGlobs = rule.globs !== undefined; + const hasPatterns = rule.patterns !== undefined; + + if (!hasGlobs && !hasPatterns) { return false; } - return filePaths.some((path) => matchesGlobs(path, rule.globs)); + + // If we have both globs and patterns, check if any files match both + if (hasGlobs && hasPatterns) { + return filePaths.some( + (filePath) => + matchesGlobs(filePath, rule.globs) && + matchesPatterns(filePath, rule.patterns), + ); + } + + // If we only have globs, check those + if (hasGlobs) { + return filePaths.some((filePath) => matchesGlobs(filePath, rule.globs)); + } + + // If we only have patterns, check those + if (hasPatterns) { + return filePaths.some((filePath) => + matchesPatterns(filePath, rule.patterns), + ); + } } - // Default behavior for root rules with globs: - // - Only apply if they match the globs - if (rule.globs) { - return filePaths.some((path) => matchesGlobs(path, rule.globs)); + // Default behavior for root rules with globs and/or patterns: + const hasGlobs = rule.globs !== undefined; + const hasPatterns = rule.patterns !== undefined; + + // If we have both globs and patterns, check if any files match both + if (hasGlobs && hasPatterns) { + return filePaths.some( + (filePath) => + matchesGlobs(filePath, rule.globs) && + matchesPatterns(filePath, rule.patterns), + ); + } + + // If we only have globs, check those + if (hasGlobs) { + return filePaths.some((filePath) => matchesGlobs(filePath, rule.globs)); + } + + // If we only have patterns, check those + if (hasPatterns) { + return filePaths.some((filePath) => + matchesPatterns(filePath, rule.patterns), + ); } // This point should not be reached as we've handled all cases above From 3422fff6077ac75196bf5ff034a219586819a0b8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 17:08:02 -0700 Subject: [PATCH 36/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 164 +++++++++++--------- 1 file changed, 90 insertions(+), 74 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 1c4f0f814..73942d4d0 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -53,10 +53,14 @@ const matchesGlobs = ( }; /** - * Checks if a path matches any of the provided regex patterns + * Checks if file content matches any of the provided regex patterns + * + * @param fileContent - The content of the file to check + * @param patterns - A single regex pattern string or array of regex pattern strings + * @returns true if the content matches any pattern (or if no patterns are provided), false otherwise */ -const matchesPatterns = ( - filePath: string, +const contentMatchesPatterns = ( + fileContent: string, patterns: string | string[] | undefined, ): boolean => { if (!patterns) return true; @@ -65,21 +69,22 @@ const matchesPatterns = ( if (typeof patterns === "string") { try { const regex = new RegExp(patterns); - return regex.test(filePath); + return regex.test(fileContent); } catch (e) { console.error(`Invalid regex pattern: ${patterns}`, e); return false; } } + // Handle array of patterns if (Array.isArray(patterns)) { if (patterns.length === 0) return true; - // File must match at least one pattern + // Content must match at least one pattern return patterns.some((pattern) => { try { const regex = new RegExp(pattern); - return regex.test(filePath); + return regex.test(fileContent); } catch (e) { console.error(`Invalid regex pattern: ${pattern}`, e); return false; @@ -150,22 +155,18 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { }; /** - * Determines if a rule should be applied based on its alwaysApply property and file path matching - * - * @param rule - The rule to check - * @param filePaths - Array of file paths to check against the rule's globs - * @returns true if the rule should be applied, false otherwise - */ -/** - * Determines if a rule should be applied based on its alwaysApply property and file path matching + * Determines if a rule should be applied based on its properties and file matching * * @param rule - The rule to check * @param filePaths - Array of file paths to check against the rule's globs + * @param fileContents - Map of file paths to their contents for pattern matching + * @param rulePolicies - Optional policies that can override normal rule behavior * @returns true if the rule should be applied, false otherwise */ export const shouldApplyRule = ( rule: RuleWithSource, filePaths: string[], + fileContents: Record = {}, rulePolicies: RulePolicies = {}, ): boolean => { const policy = rulePolicies[rule.name || ""]; @@ -207,40 +208,40 @@ export const shouldApplyRule = ( return false; } - // Check both globs and patterns + // First check if the files match the globs const hasGlobs = rule.globs !== undefined; - const hasPatterns = rule.patterns !== undefined; - // If we have both globs and patterns, check if any files match both - if (hasGlobs && hasPatterns) { - return filesInRuleDirectory.some( - (filePath) => - matchesGlobs(filePath, rule.globs) && - matchesPatterns(filePath, rule.patterns), - ); + // Filter to files that match the globs (or all files if no globs) + const matchingFiles = hasGlobs + ? filesInRuleDirectory.filter((filePath) => + matchesGlobs(filePath, rule.globs), + ) + : filesInRuleDirectory; + + // If no files match the globs, don't apply the rule + if (matchingFiles.length === 0) { + return false; } - // If we only have globs, check those - if (hasGlobs) { - return filesInRuleDirectory.some((filePath) => - matchesGlobs(filePath, rule.globs), - ); + // Now check for pattern matches in file contents if patterns are specified + if (rule.patterns) { + // Check if any of the matching files also match the content patterns + return matchingFiles.some((filePath) => { + const content = fileContents[filePath]; + // If we don't have the content, we can't check patterns + if (!content) return false; + return contentMatchesPatterns(content, rule.patterns); + }); } - // If we only have patterns, check those - if (hasPatterns) { - return filesInRuleDirectory.some((filePath) => - matchesPatterns(filePath, rule.patterns), - ); - } - - // No globs or patterns but files are in this directory, so apply the rule - return true; + // If we have no patterns or if we couldn't check patterns (no content), + // just go with the glob matches + return matchingFiles.length > 0; } // For root-level rules: - // If alwaysApply is explicitly false, only apply if there are globs AND/OR patterns AND they match + // If alwaysApply is explicitly false, we need to check globs and/or patterns if (rule.alwaysApply === false) { const hasGlobs = rule.globs !== undefined; const hasPatterns = rule.patterns !== undefined; @@ -249,55 +250,60 @@ export const shouldApplyRule = ( return false; } - // If we have both globs and patterns, check if any files match both - if (hasGlobs && hasPatterns) { - return filePaths.some( - (filePath) => - matchesGlobs(filePath, rule.globs) && - matchesPatterns(filePath, rule.patterns), - ); + // Filter to files that match the globs (or all files if no globs) + const matchingFiles = hasGlobs + ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) + : filePaths; + + // If no files match the globs, don't apply the rule + if (matchingFiles.length === 0) { + return false; } - // If we only have globs, check those - if (hasGlobs) { - return filePaths.some((filePath) => matchesGlobs(filePath, rule.globs)); - } - - // If we only have patterns, check those + // Now check for pattern matches in file contents if patterns are specified if (hasPatterns) { - return filePaths.some((filePath) => - matchesPatterns(filePath, rule.patterns), - ); + // Check if any of the matching files also match the content patterns + return matchingFiles.some((filePath) => { + const content = fileContents[filePath]; + // If we don't have the content, we can't check patterns + if (!content) return false; + return contentMatchesPatterns(content, rule.patterns); + }); } + + // If we have no patterns or if we couldn't check patterns (no content), + // just go with the glob matches + return matchingFiles.length > 0; } - // Default behavior for root rules with globs and/or patterns: + // Default behavior for root rules with globs: const hasGlobs = rule.globs !== undefined; const hasPatterns = rule.patterns !== undefined; - // If we have both globs and patterns, check if any files match both - if (hasGlobs && hasPatterns) { - return filePaths.some( - (filePath) => - matchesGlobs(filePath, rule.globs) && - matchesPatterns(filePath, rule.patterns), - ); + // Filter to files that match the globs (or all files if no globs) + const matchingFiles = hasGlobs + ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) + : filePaths; + + // If no files match the globs, don't apply the rule + if (matchingFiles.length === 0) { + return false; } - // If we only have globs, check those - if (hasGlobs) { - return filePaths.some((filePath) => matchesGlobs(filePath, rule.globs)); - } - - // If we only have patterns, check those + // Now check for pattern matches in file contents if patterns are specified if (hasPatterns) { - return filePaths.some((filePath) => - matchesPatterns(filePath, rule.patterns), - ); + // Check if any of the matching files also match the content patterns + return matchingFiles.some((filePath) => { + const content = fileContents[filePath]; + // If we don't have the content, we can't check patterns + if (!content) return false; + return contentMatchesPatterns(content, rule.patterns); + }); } - // This point should not be reached as we've handled all cases above - return false; + // If we have no patterns or if we couldn't check patterns (no content), + // just go with the glob matches + return matchingFiles.length > 0; }; /** @@ -327,10 +333,20 @@ export const getApplicableRules = ( // Combine file paths from both sources const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems]; + // Create a map of file paths to their contents for pattern matching + const fileContents: Record = {}; + + // Extract contents from context items with file URIs + contextItems.forEach((item) => { + if (item.uri?.type === "file" && item.uri?.value) { + fileContents[item.uri.value] = item.content; + } + }); + // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, // and path matching in a consistent way const applicableRules = rules.filter((rule) => - shouldApplyRule(rule, allFilePaths, rulePolicies), + shouldApplyRule(rule, allFilePaths, fileContents, rulePolicies), ); return applicableRules; From ff80ffeb3f2bcb8381dc73a624e41ac96cd0eeee Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 17:33:12 -0700 Subject: [PATCH 37/95] fix: missing patterns --- core/tools/definitions/createRuleBlock.ts | 8 +++++--- core/tools/implementations/createRuleBlock.ts | 3 ++- packages/config-yaml/src/markdown/createMarkdownRule.ts | 8 ++++++++ packages/config-yaml/src/markdown/markdownToRule.ts | 2 ++ packages/config-yaml/src/schemas/index.ts | 1 + 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index ace3bc6b2..23c0185b5 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -1,6 +1,3 @@ -import { Tool } from "../.."; -import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; - export const createRuleBlock: Tool = { type: "function", displayTitle: "Create Rule Block", @@ -37,6 +34,11 @@ export const createRuleBlock: Tool = { description: "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])", }, + patterns: { + type: "string", + description: + "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)", + }, }, }, }, diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index a38e06056..5ecb756fa 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -7,7 +7,7 @@ export type CreateRuleBlockArgs = Pick< Required, "rule" | "description" | "alwaysApply" | "name" > & - Pick; + Pick; export const createRuleBlockImpl: ToolImpl = async ( args: CreateRuleBlockArgs, @@ -16,6 +16,7 @@ export const createRuleBlockImpl: ToolImpl = async ( const fileContent = createRuleMarkdown(args.name, args.rule, { description: args.description, globs: args.globs, + patterns: args.patterns, }); const [localContinueDir] = await extras.ide.getWorkspaceDirs(); diff --git a/packages/config-yaml/src/markdown/createMarkdownRule.ts b/packages/config-yaml/src/markdown/createMarkdownRule.ts index 14843f14d..13cce86f4 100644 --- a/packages/config-yaml/src/markdown/createMarkdownRule.ts +++ b/packages/config-yaml/src/markdown/createMarkdownRule.ts @@ -34,6 +34,7 @@ export function createRuleMarkdown( options: { description?: string; globs?: string | string[]; + patterns?: string | string[]; alwaysApply?: boolean; } = {}, ): string { @@ -44,6 +45,13 @@ export function createRuleMarkdown( typeof options.globs === "string" ? options.globs.trim() : options.globs; } + if (options.patterns) { + frontmatter.patterns = + typeof options.patterns === "string" + ? options.patterns.trim() + : options.patterns; + } + if (options.description) { frontmatter.description = options.description.trim(); } diff --git a/packages/config-yaml/src/markdown/markdownToRule.ts b/packages/config-yaml/src/markdown/markdownToRule.ts index a48f8176a..5bed93ac8 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.ts @@ -7,6 +7,7 @@ import { RuleObject } from "../schemas/index.js"; export interface RuleFrontmatter { globs?: RuleObject["globs"]; + patterns?: RuleObject["patterns"]; name?: RuleObject["name"]; description?: RuleObject["description"]; alwaysApply?: RuleObject["alwaysApply"]; @@ -56,6 +57,7 @@ export function markdownToRule( name: frontmatter.name ?? packageIdentifierToDisplayName(id), rule: markdown, globs: frontmatter.globs, + patterns: frontmatter.patterns, description: frontmatter.description, alwaysApply: frontmatter.alwaysApply, }; diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 224278cd7..14d4a7486 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -45,6 +45,7 @@ const ruleObjectSchema = z.object({ rule: z.string(), description: z.string().optional(), globs: z.union([z.string(), z.array(z.string())]).optional(), + patterns: z.union([z.string(), z.array(z.string())]).optional(), alwaysApply: z.boolean().optional(), }); const ruleSchema = z.union([z.string(), ruleObjectSchema]); From c1467f5eca45f7d3260bf1ad78473bf92a1f9fea Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 17:34:58 -0700 Subject: [PATCH 38/95] fix: types --- core/tools/definitions/createRuleBlock.ts | 3 +++ core/tools/implementations/createRuleBlock.ts | 13 ++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 23c0185b5..2afb19d70 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -1,3 +1,6 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + export const createRuleBlock: Tool = { type: "function", displayTitle: "Create Rule Block", diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index 5ecb756fa..cfa60a5a3 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -13,11 +13,18 @@ export const createRuleBlockImpl: ToolImpl = async ( args: CreateRuleBlockArgs, extras, ) => { - const fileContent = createRuleMarkdown(args.name, args.rule, { + // Create options object with the fields that createRuleMarkdown expects + const options: any = { description: args.description, globs: args.globs, - patterns: args.patterns, - }); + }; + + // Add patterns if provided + if (args.patterns) { + options.patterns = args.patterns; + } + + const fileContent = createRuleMarkdown(args.name, args.rule, options); const [localContinueDir] = await extras.ide.getWorkspaceDirs(); const ruleFilePath = createRuleFilePath(localContinueDir, args.name); From 3786a04fc9140d20ab98bd2765917db099761698 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 18 Jun 2025 17:35:35 -0700 Subject: [PATCH 39/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 73942d4d0..3a662b1b6 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -146,11 +146,19 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { return true; } - // Root-level rules with no globs are implicitly global - if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) { + console.log("RULE", rule); + // Root-level rules with no globs or patterns are implicitly global + if ( + isRootLevelRule(rule) && + !rule.globs && + !rule.patterns && + rule.alwaysApply !== false + ) { + console.log("IS ROOT"); return true; } + console.log("NOT ROOT"); return false; }; From e222fba6aa123145b64f9f9223f94edc7ce4f53d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 13:42:43 -0700 Subject: [PATCH 40/95] remove all barrel extensions --- gui/.eslintrc.json | 5 ++-- gui/package-lock.json | 13 +++++++++- gui/package.json | 1 + gui/src/App.tsx | 2 +- .../ConversationStarterCards.tsx | 2 +- .../components/ConversationStarters/index.ts | 1 - gui/src/components/Layout.tsx | 10 +++----- gui/src/components/ModeSelect/ModeSelect.tsx | 2 +- gui/src/components/ModeSelect/index.ts | 1 - .../OnboardingCard/OnboardingCard.tsx | 14 +++++------ .../components/OnboardingCardLanding.tsx | 6 ++--- .../components/OnboardingLocalTab.tsx | 4 +-- .../components/OnboardingModelsAddOnTab.tsx | 2 +- .../components/OnboardingProvidersTab.tsx | 2 +- .../OnboardingCard/components/index.ts | 8 ------ .../components/OnboardingCard/hooks/index.ts | 2 -- .../OnboardingCard/hooks/useOnboardingCard.ts | 2 +- gui/src/components/OnboardingCard/index.ts | 3 --- .../StepContainerPreToolbar/index.tsx | 2 +- .../loaders/FreeTrialProgressBar.tsx | 2 +- .../components/mainInput/ContinueInputBox.tsx | 2 +- gui/src/components/mainInput/InputToolbar.tsx | 2 +- .../Lump/LumpToolbar/EditOutcomeToolbar.tsx | 2 +- .../Lump/LumpToolbar/EditToolbar.tsx | 2 +- .../Lump/LumpToolbar/LumpToolbar.tsx | 6 ++--- .../LumpToolbar/PendingToolCallToolbar.tsx | 6 ++--- .../Lump/LumpToolbar/StreamingToolbar.tsx | 2 +- .../mainInput/Lump/LumpToolbar/index.ts | 1 - gui/src/components/mainInput/Lump/index.tsx | 2 +- .../mainInput/Lump/sections/ModelsSection.tsx | 2 +- .../Lump/sections/PromptsSection.tsx | 2 +- .../mainInput/TipTapEditor/TipTapEditor.tsx | 5 ++-- .../TipTapEditor/components/index.ts | 3 --- .../extensions/CodeBlock/index.ts | 1 - .../TipTapEditor/extensions/Prompt/index.ts | 1 - .../TipTapEditor/extensions/index.ts | 4 --- .../mainInput/TipTapEditor/index.ts | 4 --- .../useMainEditorWebviewListeners.ts | 3 ++- .../TipTapEditor/utils/editorConfig.ts | 25 ++++++++++--------- .../TipTapEditor/utils/getSuggestion.ts | 2 +- .../mainInput/TipTapEditor/utils/index.ts | 5 ---- .../utils/insertCurrentFileContextMention.ts | 4 +-- .../utils/resolveEditorContent.ts | 4 ++- .../mainInput/util/handleMetaKeyIssues.ts | 2 +- gui/src/components/mainInput/util/index.ts | 2 -- .../components/modelSelection/ModelSelect.tsx | 11 +++++--- .../modelSelection/ModelSelectionListbox.tsx | 4 +-- .../platform/AssistantSelect.tsx | 8 +++--- .../platform/FreeTrialButton.tsx | 3 ++- gui/src/components/ui/index.tsx | 4 --- gui/src/context/Auth.tsx | 4 +-- gui/src/forms/AddModelForm.tsx | 2 +- gui/src/forms/index.ts | 1 - gui/src/hooks/ParallelListeners.tsx | 18 +++++++------ gui/src/hooks/index.ts | 1 - gui/src/hooks/useBookmarkedSlashCommands.ts | 5 ++-- gui/src/pages/config/AccountButton.tsx | 8 +++--- gui/src/pages/config/ConfigItemSelect.tsx | 4 +-- gui/src/pages/config/ModelRoleSelector.tsx | 4 +-- gui/src/pages/config/ScopeSelect.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 4 +-- gui/src/pages/gui/EmptyChatBody.tsx | 4 +-- gui/src/pages/gui/StreamError.tsx | 6 ++--- gui/src/redux/index.ts | 1 - gui/src/redux/slices/index.ts | 1 - gui/src/redux/slices/profiles/index.ts | 1 - .../{profiles/slice.ts => profilesSlice.ts} | 0 gui/src/redux/slices/uiSlice.ts | 6 ++--- gui/src/redux/store.ts | 2 +- gui/src/redux/thunks/edit.ts | 2 +- gui/src/redux/thunks/gatherContext.ts | 2 +- gui/src/redux/thunks/index.ts | 12 --------- gui/src/redux/thunks/selectFirstHubProfile.ts | 2 +- gui/src/redux/thunks/updateFileSymbols.ts | 2 +- gui/src/util/localStorage.ts | 2 +- gui/src/util/test/render.tsx | 2 +- 76 files changed, 133 insertions(+), 173 deletions(-) delete mode 100644 gui/src/components/ConversationStarters/index.ts delete mode 100644 gui/src/components/ModeSelect/index.ts delete mode 100644 gui/src/components/OnboardingCard/components/index.ts delete mode 100644 gui/src/components/OnboardingCard/hooks/index.ts delete mode 100644 gui/src/components/OnboardingCard/index.ts delete mode 100644 gui/src/components/mainInput/Lump/LumpToolbar/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/components/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/utils/index.ts delete mode 100644 gui/src/components/ui/index.tsx delete mode 100644 gui/src/forms/index.ts delete mode 100644 gui/src/hooks/index.ts delete mode 100644 gui/src/redux/index.ts delete mode 100644 gui/src/redux/slices/index.ts delete mode 100644 gui/src/redux/slices/profiles/index.ts rename gui/src/redux/slices/{profiles/slice.ts => profilesSlice.ts} (100%) delete mode 100644 gui/src/redux/thunks/index.ts diff --git a/gui/.eslintrc.json b/gui/.eslintrc.json index aebab49dd..afdd06ee9 100644 --- a/gui/.eslintrc.json +++ b/gui/.eslintrc.json @@ -1,7 +1,7 @@ { "root": true, "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint", "eslint-plugin-react"], + "plugins": ["@typescript-eslint", "eslint-plugin-react", "no-barrel-files"], "parserOptions": { "project": ["tsconfig.json", "tsconfig.node.json"] }, @@ -13,7 +13,8 @@ ], "rules": { "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/no-floating-promises": "warn" + "@typescript-eslint/no-floating-promises": "warn", + "no-barrel-files/no-barrel-files": "error" }, "overrides": [ { diff --git a/gui/package-lock.json b/gui/package-lock.json index 045ee07cb..0619e22e5 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -90,6 +90,7 @@ "@vitest/ui": "^2.1.3", "autoprefixer": "^10.4.13", "eslint": "^8", + "eslint-plugin-no-barrel-files": "^1.2.1", "eslint-plugin-react": "^7.37.2", "jsdom": "^25.0.1", "postcss": "^8.4.21", @@ -214,7 +215,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.92", + "version": "1.0.94", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -5281,6 +5282,16 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint-plugin-no-barrel-files": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-no-barrel-files/-/eslint-plugin-no-barrel-files-1.2.1.tgz", + "integrity": "sha512-WoZ48JXa99yptWwWWAKmuKNgvgA6tpSol6Cf0GzXs2Lg/JdBqe+CF58Bf8saEpYJRA+6+cTzP90nI7U7zoy5IQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@typescript-eslint/utils": "^8.13.0" + } + }, "node_modules/eslint-plugin-react": { "version": "7.37.2", "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.2.tgz", diff --git a/gui/package.json b/gui/package.json index 1f137f19b..eb4a5a4d0 100644 --- a/gui/package.json +++ b/gui/package.json @@ -99,6 +99,7 @@ "@vitest/ui": "^2.1.3", "autoprefixer": "^10.4.13", "eslint": "^8", + "eslint-plugin-no-barrel-files": "^1.2.1", "eslint-plugin-react": "^7.37.2", "jsdom": "^25.0.1", "postcss": "^8.4.21", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 6fc120707..e6f770eb3 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,6 +1,6 @@ import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; -import { MainEditorProvider } from "./components/mainInput/TipTapEditor"; +import { MainEditorProvider } from "./components/mainInput/TipTapEditor/MainEditorProvider"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import ParallelListeners from "./hooks/ParallelListeners"; diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 776c0721b..9ac9bcf91 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -2,7 +2,7 @@ import { SlashCommandDescription } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { useMainEditor } from "../mainInput/TipTapEditor"; +import { useMainEditor } from "../mainInput/TipTapEditor/MainEditorProvider"; import { ConversationStarterCard } from "./ConversationStarterCard"; const NUM_CARDS_TO_RENDER = 5; diff --git a/gui/src/components/ConversationStarters/index.ts b/gui/src/components/ConversationStarters/index.ts deleted file mode 100644 index 72b23e0b7..000000000 --- a/gui/src/components/ConversationStarters/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./ConversationStarterCards"; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 1e2134e7a..4dd3239e8 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -19,12 +19,10 @@ 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 { - isNewUserOnboarding, - OnboardingCard, - useOnboardingCard, -} from "./OnboardingCard"; +import { useMainEditor } from "./mainInput/TipTapEditor/MainEditorProvider"; +import { useOnboardingCard } from "./OnboardingCard/hooks/useOnboardingCard"; +import { OnboardingCard } from "./OnboardingCard/OnboardingCard"; +import { isNewUserOnboarding } from "./OnboardingCard/utils"; import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index dbd5cabfe..dec1b1e81 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -6,7 +6,7 @@ import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; import { getFontSize, getMetaKeyLabel } from "../../util"; -import { useMainEditor } from "../mainInput/TipTapEditor"; +import { useMainEditor } from "../mainInput/TipTapEditor/MainEditorProvider"; import { Listbox, ListboxButton, diff --git a/gui/src/components/ModeSelect/index.ts b/gui/src/components/ModeSelect/index.ts deleted file mode 100644 index 04cc20156..000000000 --- a/gui/src/components/ModeSelect/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./ModeSelect"; diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index 8b6264fe0..b5131916a 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -3,14 +3,12 @@ import { useAppSelector } from "../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import Alert from "../gui/Alert"; import { ReusableCard } from "../ReusableCard"; -import { - OnboardingCardLanding, - OnboardingCardTabs, - OnboardingLocalTab, - OnboardingModelsAddOnTab, - OnboardingProvidersTab, -} from "./components"; -import { useOnboardingCard } from "./hooks"; +import { OnboardingCardLanding } from "./components/OnboardingCardLanding"; +import { OnboardingCardTabs } from "./components/OnboardingCardTabs"; +import { OnboardingLocalTab } from "./components/OnboardingLocalTab"; +import { OnboardingModelsAddOnTab } from "./components/OnboardingModelsAddOnTab"; +import { OnboardingProvidersTab } from "./components/OnboardingProvidersTab"; +import { useOnboardingCard } from "./hooks/useOnboardingCard"; export interface OnboardingCardState { show?: boolean; diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index 5c3958d4b..d9eae491c 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -2,13 +2,13 @@ import { useContext } from "react"; import { Button, SecondaryButton } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { selectCurrentOrg } from "../../../redux"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectFirstHubProfile } from "../../../redux/thunks"; +import { selectCurrentOrg } from "../../../redux/slices/profilesSlice"; +import { selectFirstHubProfile } from "../../../redux/thunks/selectFirstHubProfile"; import { hasPassedFTL } from "../../../util/freeTrial"; import { ToolTip } from "../../gui/Tooltip"; import ContinueLogo from "../../svg/ContinueLogo"; -import { useOnboardingCard } from "../hooks"; +import { useOnboardingCard } from "../hooks/useOnboardingCard"; export function OnboardingCardLanding({ onSelectConfigure, diff --git a/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx index 797fcbff0..6db9cd0cc 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx @@ -12,8 +12,8 @@ import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; -import { updateSelectedModelByRole } from "../../../redux/thunks"; -import { useSubmitOnboarding } from "../hooks"; +import { updateSelectedModelByRole } from "../../../redux/thunks/updateSelectedModelByRole"; +import { useSubmitOnboarding } from "../hooks/useSubmitOnboarding"; import OllamaModelDownload from "./OllamaModelDownload"; import { OllamaStatus } from "./OllamaStatus"; diff --git a/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx index 888013072..3d512d508 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx @@ -3,7 +3,7 @@ import { useContext, useEffect, useState } from "react"; import { Button } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { getLocalStorage } from "../../../util/localStorage"; -import { useOnboardingCard } from "../hooks"; +import { useOnboardingCard } from "../hooks/useOnboardingCard"; /** * Models Add-On tab component displaying pricing and tier information diff --git a/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx index 1d99397c0..b3f473923 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx @@ -1,6 +1,6 @@ import { OnboardingModes } from "core/protocol/core"; import { FormProvider, useForm } from "react-hook-form"; -import { AddModelForm } from "../../../forms"; +import { AddModelForm } from "../../../forms/AddModelForm"; import { providers } from "../../../pages/AddNewModel/configs/providers"; import { useAppDispatch } from "../../../redux/hooks"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; diff --git a/gui/src/components/OnboardingCard/components/index.ts b/gui/src/components/OnboardingCard/components/index.ts deleted file mode 100644 index 4b31778b4..000000000 --- a/gui/src/components/OnboardingCard/components/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * from "./OllamaCompletedStep"; -export * from "./OllamaModelDownload"; -export * from "./OllamaStatus"; -export * from "./OnboardingCardLanding"; -export * from "./OnboardingCardTabs"; -export * from "./OnboardingLocalTab"; -export * from "./OnboardingModelsAddOnTab"; -export * from "./OnboardingProvidersTab"; diff --git a/gui/src/components/OnboardingCard/hooks/index.ts b/gui/src/components/OnboardingCard/hooks/index.ts deleted file mode 100644 index f2340f5f6..000000000 --- a/gui/src/components/OnboardingCard/hooks/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./useSubmitOnboarding"; -export * from "./useOnboardingCard"; diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index 94a7fb7a8..34b7f4225 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,6 +1,5 @@ import { OnboardingModes } from "core/protocol/core"; import { useNavigate } from "react-router-dom"; -import { OnboardingCardState } from ".."; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { setDialogMessage, @@ -8,6 +7,7 @@ import { setShowDialog, } from "../../../redux/slices/uiSlice"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; +import { OnboardingCardState } from "../OnboardingCard"; export interface UseOnboardingCard { show: OnboardingCardState["show"]; diff --git a/gui/src/components/OnboardingCard/index.ts b/gui/src/components/OnboardingCard/index.ts deleted file mode 100644 index 5a9a0c0d8..000000000 --- a/gui/src/components/OnboardingCard/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./OnboardingCard"; -export * from "./utils"; -export * from "./hooks/useOnboardingCard"; diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index e33c21df5..0dd4ec7e8 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -8,7 +8,7 @@ import { vscEditorBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useIdeMessengerRequest } from "../../../hooks"; +import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall"; diff --git a/gui/src/components/loaders/FreeTrialProgressBar.tsx b/gui/src/components/loaders/FreeTrialProgressBar.tsx index 1307ba900..f9c3b8b03 100644 --- a/gui/src/components/loaders/FreeTrialProgressBar.tsx +++ b/gui/src/components/loaders/FreeTrialProgressBar.tsx @@ -1,7 +1,7 @@ import { ExclamationCircleIcon } from "@heroicons/react/24/outline"; import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; -import { AddModelForm } from "../../forms"; +import { AddModelForm } from "../../forms/AddModelForm"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { ToolTip } from "../gui/Tooltip"; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index b50edfdbb..8ee50bc07 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -9,7 +9,7 @@ import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; import { RulesPeek } from "./belowMainInput/RulesPeek"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; -import { TipTapEditor } from "./TipTapEditor"; +import { TipTapEditor } from "./TipTapEditor/TipTapEditor"; interface ContinueInputBoxProps { isLastUserInput: boolean; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 23d242ae2..7cff5fc7c 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -14,7 +14,7 @@ import { exitEdit } from "../../redux/thunks/edit"; import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; -import { ModeSelect } from "../ModeSelect"; +import { ModeSelect } from "../ModeSelect/ModeSelect"; import { useFontSize } from "../ui/font"; import { EnterButton } from "./InputToolbar/EnterButton"; import HoverItem from "./InputToolbar/HoverItem"; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx index dc3779d22..832383f10 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx @@ -3,7 +3,7 @@ import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { exitEdit } from "../../../../redux/thunks/edit"; import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons"; -import { useMainEditor } from "../../TipTapEditor"; +import { useMainEditor } from "../../TipTapEditor/MainEditorProvider"; export function EditOutcomeToolbar() { const dispatch = useAppDispatch(); diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx index 10f441be4..b1424ffe4 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx @@ -2,7 +2,7 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; -import { exitEdit } from "../../../../redux/thunks"; +import { exitEdit } from "../../../../redux/thunks/edit"; import { getEditFilenameAndRangeText } from "../../util"; export function EditToolbar() { diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 6b4fdb5ba..02027865e 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -2,10 +2,8 @@ import { useEffect } from "react"; import { useSelector } from "react-redux"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; -import { - callCurrentTool, - cancelCurrentToolCall, -} from "../../../../redux/thunks"; +import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; +import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; import { isJetBrains } from "../../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx index 3a7da10d1..365898dce 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx @@ -1,9 +1,7 @@ import styled from "styled-components"; import { useAppDispatch } from "../../../../redux/hooks"; -import { - callCurrentTool, - cancelCurrentToolCall, -} from "../../../../redux/thunks"; +import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; +import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; import { getAltKeyLabel, getFontSize, diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx index aa3a6cdaf..60ad198b3 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx @@ -1,5 +1,5 @@ import { useAppDispatch } from "../../../../redux/hooks"; -import { cancelStream } from "../../../../redux/thunks"; +import { cancelStream } from "../../../../redux/thunks/cancelStream"; import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util"; import { Container, StopButton } from "./components"; import { GeneratingIndicator } from "./GeneratingIndicator"; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/index.ts b/gui/src/components/mainInput/Lump/LumpToolbar/index.ts deleted file mode 100644 index a62e11c02..000000000 --- a/gui/src/components/mainInput/Lump/LumpToolbar/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./LumpToolbar"; diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index bdd77fdf1..f6ff453ce 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -5,7 +5,7 @@ import { vscInputBackground, } from "../.."; import { useLump } from "./LumpContext"; -import { LumpToolbar } from "./LumpToolbar"; +import { LumpToolbar } from "./LumpToolbar/LumpToolbar"; import { SelectedSection } from "./sections/SelectedSection"; const LumpDiv = styled.div` diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx index 4d821980b..b8327d59e 100644 --- a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -3,7 +3,7 @@ import { ModelDescription } from "core"; import { useAuth } from "../../../../context/Auth"; import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; -import { updateSelectedModelByRole } from "../../../../redux/thunks"; +import { updateSelectedModelByRole } from "../../../../redux/thunks/updateSelectedModelByRole"; import { isJetBrains } from "../../../../util"; export function ModelsSection() { diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index d7fd74eee..b057d68e7 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -11,7 +11,7 @@ import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands"; import { useAppSelector } from "../../../../redux/hooks"; import { fontSize } from "../../../../util"; -import { useMainEditor } from "../../TipTapEditor"; +import { useMainEditor } from "../../TipTapEditor/MainEditorProvider"; import { useLump } from "../LumpContext"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 8948a7e46..8e659f1e8 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -9,11 +9,12 @@ import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; -import { DragOverlay, InputBoxDiv } from "./components"; +import { DragOverlay } from "./components/DragOverlay"; +import { InputBoxDiv } from "./components/StyledComponents"; import { useMainEditor } from "./MainEditorProvider"; import "./TipTapEditor.css"; -import { handleImageFile } from "./utils"; import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig"; +import { handleImageFile } from "./utils/imageUtils"; import { useEditorEventHandlers } from "./utils/keyHandlers"; export interface TipTapEditorProps { diff --git a/gui/src/components/mainInput/TipTapEditor/components/index.ts b/gui/src/components/mainInput/TipTapEditor/components/index.ts deleted file mode 100644 index ddcf5dd94..000000000 --- a/gui/src/components/mainInput/TipTapEditor/components/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./DragOverlay"; -export * from "./ExpandableToolbarPreview"; -export * from "./StyledComponents"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts deleted file mode 100644 index ca111193d..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./CodeBlock"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts deleted file mode 100644 index 3a72d7bd3..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./PromptBlock"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts deleted file mode 100644 index 717557fdc..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./CodeBlock"; -export * from "./Mention"; -export * from "./Prompt"; -export * from "./SlashCommand"; diff --git a/gui/src/components/mainInput/TipTapEditor/index.ts b/gui/src/components/mainInput/TipTapEditor/index.ts deleted file mode 100644 index b2d446398..000000000 --- a/gui/src/components/mainInput/TipTapEditor/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./extensions"; -export * from "./MainEditorProvider"; -export * from "./TipTapEditor"; -export * from "./utils"; diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 0fe79297c..b73d12e73 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -8,7 +8,8 @@ import { clearCodeToEdit } from "../../../redux/slices/editState"; import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { CodeBlock, PromptBlock } from "./extensions"; +import { CodeBlock } from "./extensions/CodeBlock/CodeBlock"; +import { PromptBlock } from "./extensions/Prompt/PromptBlock"; import { insertCurrentFileContextMention } from "./utils/insertCurrentFileContextMention"; /** diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 774a95446..3ae001058 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -11,10 +11,6 @@ import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { usePostHog } from "posthog-js/react"; import { useRef } from "react"; -import { - getContextProviderDropdownOptions, - getSlashCommandDropdownOptions, -} from "."; import { IIdeMessenger } from "../../../../context/IdeMessenger"; import { useSubmenuContextProviders } from "../../../../context/SubmenuContextProviders"; import { useInputHistory } from "../../../../hooks/useInputHistory"; @@ -25,8 +21,15 @@ import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; import { AppDispatch } from "../../../../redux/store"; import { exitEdit } from "../../../../redux/thunks/edit"; import { getFontSize, isJetBrains } from "../../../../util"; -import * as ContinueExtensions from "../extensions"; +import { CodeBlock } from "../extensions/CodeBlock/CodeBlock"; +import { Mention } from "../extensions/Mention"; +import { PromptBlock } from "../extensions/Prompt/PromptBlock"; +import { SlashCommand } from "../extensions/SlashCommand"; import { TipTapEditorProps } from "../TipTapEditor"; +import { + getContextProviderDropdownOptions, + getSlashCommandDropdownOptions, +} from "./getSuggestion"; import { handleImageFile } from "./imageUtils"; export function getPlaceholderText( @@ -52,9 +55,7 @@ export function getPlaceholderText( export function hasValidEditorContent(json: JSONContent): boolean { // Check for prompt or code blocks const hasPromptOrCodeBlock = json.content?.some( - (c) => - c.type === ContinueExtensions.PromptBlock.name || - c.type === ContinueExtensions.CodeBlock.name, + (c) => c.type === PromptBlock.name || c.type === CodeBlock.name, ); // Check for text content @@ -306,7 +307,7 @@ export function createEditorConfig(options: { }, }), Text, - ContinueExtensions.Mention.configure({ + Mention.configure({ suggestion: getContextProviderDropdownOptions( availableContextProvidersRef, getSubmenuContextItemsRef, @@ -317,7 +318,7 @@ export function createEditorConfig(options: { ideMessenger, ), }), - ContinueExtensions.SlashCommand.configure({ + SlashCommand.configure({ suggestion: getSlashCommandDropdownOptions( availableSlashCommandsRef, onClose, @@ -327,8 +328,8 @@ export function createEditorConfig(options: { props.inputId, ), }), - ContinueExtensions.PromptBlock, - ContinueExtensions.CodeBlock, + PromptBlock, + CodeBlock, ], editorProps: { attributes: { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index 8c0613a4a..87175f317 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -11,7 +11,7 @@ import { AppDispatch } from "../../../../redux/store"; import AtMentionDropdown from "../../AtMentionDropdown"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; import { TIPPY_DIV_ID } from "../TipTapEditor"; -import { SlashCommand } from "../extensions"; +import { SlashCommand } from "../extensions/SlashCommand"; function getSuggestion( items: (props: { query: string }) => Promise, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/index.ts b/gui/src/components/mainInput/TipTapEditor/utils/index.ts deleted file mode 100644 index 5ce05a866..000000000 --- a/gui/src/components/mainInput/TipTapEditor/utils/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./editorConfig"; -export * from "./getSuggestion"; -export * from "./imageUtils"; -export * from "./keyHandlers"; -export * from "./resolveEditorContent"; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts b/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts index 764ea9f9b..6f5398455 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts @@ -1,6 +1,6 @@ import { Editor } from "@tiptap/core"; import { ContextProviderDescription } from "core"; -import * as ContinueExtensions from "../extensions"; +import { Mention } from "../extensions/Mention"; /** * inserts the current file context as a removable mention in the editor area @@ -16,7 +16,7 @@ export function insertCurrentFileContextMention( ); if (foundCurrentFileProvider) { - const node = editor.schema.nodes[ContinueExtensions.Mention.name].create({ + const node = editor.schema.nodes[Mention.name].create({ name: foundCurrentFileProvider.displayTitle, description: foundCurrentFileProvider.description, id: foundCurrentFileProvider.title, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index 958ea2331..8d1b402eb 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -18,7 +18,9 @@ import { renderChatMessage, stripImages } from "core/util/messageContent"; import { getUriFileExtension } from "core/util/uri"; import { IIdeMessenger } from "../../../../context/IdeMessenger"; import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; -import { CodeBlock, Mention, PromptBlock } from "../extensions"; +import { CodeBlock } from "../extensions/CodeBlock/CodeBlock"; +import { Mention } from "../extensions/Mention"; +import { PromptBlock } from "../extensions/Prompt/PromptBlock"; interface MentionAttrs { label: string; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index bc45d19f1..2ca436425 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,7 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; -import { CodeBlock } from "../TipTapEditor"; +import { CodeBlock } from "../TipTapEditor/extensions/CodeBlock/CodeBlock"; const isWebEnv = isWebEnvironment(); diff --git a/gui/src/components/mainInput/util/index.ts b/gui/src/components/mainInput/util/index.ts index 5f8b4fd77..466a2618a 100644 --- a/gui/src/components/mainInput/util/index.ts +++ b/gui/src/components/mainInput/util/index.ts @@ -1,8 +1,6 @@ import { SetCodeToEditPayload } from "core"; import { getUriPathBasename } from "core/util/uri"; -export * from "./handleMetaKeyIssues"; - export function getEditFilenameAndRangeText(code: SetCodeToEditPayload) { const fileName = getUriPathBasename(code.filepath); let title = `${fileName}`; diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index c6f946b89..b6b270a4b 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -9,17 +9,22 @@ import { import { useContext, useEffect, useRef, useState } from "react"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { AddModelForm } from "../../forms"; +import { AddModelForm } from "../../forms/AddModelForm"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { EMPTY_CONFIG } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { updateSelectedModelByRole } from "../../redux/thunks"; +import { updateSelectedModelByRole } from "../../redux/thunks/updateSelectedModelByRole"; import { fontSize, getMetaKeyLabel, isMetaEquivalentKeyPressed, } from "../../util"; -import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; +import { + Listbox, + ListboxButton, + ListboxOption, + ListboxOptions, +} from "../ui/Listbox"; interface ModelOptionProps { option: Option; diff --git a/gui/src/components/modelSelection/ModelSelectionListbox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx index 04510b6bb..041d6c9a5 100644 --- a/gui/src/components/modelSelection/ModelSelectionListbox.tsx +++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx @@ -9,8 +9,8 @@ import { ListboxButton, ListboxOption, ListboxOptions, - Transition, -} from "../../components/ui"; +} from "../../components/ui/Listbox"; +import { Transition } from "../../components/ui/Transition"; import { DisplayInfo } from "../../pages/AddNewModel/configs/models"; interface ModelSelectionListboxProps { diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index aebae2aa6..21e62ed10 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -10,12 +10,12 @@ import { import { useContext, useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectCurrentOrg, setSelectedOrgId, setSelectedProfile, -} from "../../../redux"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +} from "../../../redux/slices/profilesSlice"; import { fontSize, getMetaKeyLabel, @@ -27,8 +27,8 @@ import { ListboxButton, ListboxOption, ListboxOptions, - Transition, -} from "../../ui"; +} from "../../ui/Listbox"; +import { Transition } from "../../ui/Transition"; import type { ProfileDescription } from "core/config/ConfigHandler"; import { useNavigate } from "react-router-dom"; diff --git a/gui/src/components/modelSelection/platform/FreeTrialButton.tsx b/gui/src/components/modelSelection/platform/FreeTrialButton.tsx index c34d0abce..0ff4fb1dc 100644 --- a/gui/src/components/modelSelection/platform/FreeTrialButton.tsx +++ b/gui/src/components/modelSelection/platform/FreeTrialButton.tsx @@ -4,7 +4,8 @@ import { useContext } from "react"; import { Button, SecondaryButton, vscButtonBackground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { fontSize } from "../../../util"; -import { Listbox, ListboxButton, ListboxOptions, Transition } from "../../ui"; +import { Listbox, ListboxButton, ListboxOptions } from "../../ui/Listbox"; +import { Transition } from "../../ui/Transition"; import { useFontSize } from "../../ui/font"; interface ProgressBarProps { diff --git a/gui/src/components/ui/index.tsx b/gui/src/components/ui/index.tsx deleted file mode 100644 index e8f087bb1..000000000 --- a/gui/src/components/ui/index.tsx +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./Combobox"; -export * from "./Listbox"; -export * from "./Popover"; -export * from "./Transition"; diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 8c928630d..99f0998da 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -12,13 +12,13 @@ import React, { } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { useWebviewListener } from "../hooks/useWebviewListener"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { selectCurrentOrg, selectSelectedProfile, setOrganizations, setSelectedOrgId, -} from "../redux/"; -import { useAppDispatch, useAppSelector } from "../redux/hooks"; +} from "../redux/slices/profilesSlice"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { IdeMessengerContext } from "./IdeMessenger"; diff --git a/gui/src/forms/AddModelForm.tsx b/gui/src/forms/AddModelForm.tsx index afc2055c2..5de78133c 100644 --- a/gui/src/forms/AddModelForm.tsx +++ b/gui/src/forms/AddModelForm.tsx @@ -13,7 +13,7 @@ import { providers, } from "../pages/AddNewModel/configs/providers"; import { useAppDispatch } from "../redux/hooks"; -import { updateSelectedModelByRole } from "../redux/thunks"; +import { updateSelectedModelByRole } from "../redux/thunks/updateSelectedModelByRole"; interface AddModelFormProps { onDone: () => void; diff --git a/gui/src/forms/index.ts b/gui/src/forms/index.ts deleted file mode 100644 index 410a55a37..000000000 --- a/gui/src/forms/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./AddModelForm"; diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 155b91e2c..2c37a90e2 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -3,13 +3,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { FromCoreProtocol } from "core/protocol"; -import { useMainEditor } from "../components/mainInput/TipTapEditor"; -import { - initializeProfilePreferences, - setOrganizations, - setSelectedOrgId, - setSelectedProfile, -} from "../redux"; +import { useMainEditor } from "../components/mainInput/TipTapEditor/MainEditorProvider"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; import { setConfigResult } from "../redux/slices/configSlice"; @@ -18,13 +12,21 @@ import { updateEditStateApplyState, } from "../redux/slices/editState"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; +import { + initializeProfilePreferences, + setOrganizations, + setSelectedOrgId, + setSelectedProfile, +} from "../redux/slices/profilesSlice"; import { acceptToolCall, addContextItemsAtIndex, updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; -import { exitEdit, streamResponseAfterToolCall } from "../redux/thunks"; +import { exitEdit } from "../redux/thunks/edit"; +import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall"; + import { cancelStream } from "../redux/thunks/cancelStream"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; diff --git a/gui/src/hooks/index.ts b/gui/src/hooks/index.ts deleted file mode 100644 index 8688c91e5..000000000 --- a/gui/src/hooks/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./useIdeMessengerRequest"; diff --git a/gui/src/hooks/useBookmarkedSlashCommands.ts b/gui/src/hooks/useBookmarkedSlashCommands.ts index d00c60934..dcd58f9f7 100644 --- a/gui/src/hooks/useBookmarkedSlashCommands.ts +++ b/gui/src/hooks/useBookmarkedSlashCommands.ts @@ -1,11 +1,12 @@ import { SlashCommandDescription } from "core"; import { usePostHog } from "posthog-js/react"; + +import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { bookmarkSlashCommand, selectBookmarkedSlashCommands, unbookmarkSlashCommand, -} from "../redux"; -import { useAppDispatch, useAppSelector } from "../redux/hooks"; +} from "../redux/slices/profilesSlice"; export function useBookmarkedSlashCommands() { const dispatch = useAppDispatch(); diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 06c6beba0..7c94827f7 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,15 +1,15 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; import { isOnPremSession } from "core/control-plane/AuthTypes"; +import { Button } from "../../components/ui/Button"; import { Popover, PopoverButton, PopoverPanel, - Transition, -} from "../../components/ui"; -import { Button } from "../../components/ui/Button"; +} from "../../components/ui/Popover"; +import { Transition } from "../../components/ui/Transition"; import { useAuth } from "../../context/Auth"; -import { selectCurrentOrg } from "../../redux"; import { useAppSelector } from "../../redux/hooks"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; import { ScopeSelect } from "./ScopeSelect"; export function AccountButton() { diff --git a/gui/src/pages/config/ConfigItemSelect.tsx b/gui/src/pages/config/ConfigItemSelect.tsx index 320ea8cf7..882477382 100644 --- a/gui/src/pages/config/ConfigItemSelect.tsx +++ b/gui/src/pages/config/ConfigItemSelect.tsx @@ -16,8 +16,8 @@ import { Popover, PopoverButton, PopoverPanel, - Transition, -} from "../../components/ui"; +} from "../../components/ui/Popover"; +import { Transition } from "../../components/ui/Transition"; import { fontSize } from "../../util"; export function ConfigItemSelect({ diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index 0065552a8..ea2b33f29 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -15,8 +15,8 @@ import { ListboxButton, ListboxOption, ListboxOptions, - Transition, -} from "../../components/ui"; +} from "../../components/ui/Listbox"; +import { Transition } from "../../components/ui/Transition"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { fontSize } from "../../util"; diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 07a177c7b..9e574f44a 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -16,7 +16,7 @@ import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectCurrentOrg, setSelectedOrgId, -} from "../../redux/slices/profiles/slice"; +} from "../../redux/slices/profilesSlice"; interface ScopeSelectProps { onSelect?: () => void; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6b2a6a364..aee592b96 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -23,7 +23,7 @@ import TimelineItem from "../../components/gui/TimelineItem"; import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import { useOnboardingCard } from "../../components/OnboardingCard"; +import { useOnboardingCard } from "../../components/OnboardingCard/hooks/useOnboardingCard"; import StepContainer from "../../components/StepContainer"; import { TabBar } from "../../components/TabBar/TabBar"; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -42,10 +42,10 @@ import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiSlice"; -import { streamResponseThunk } from "../../redux/thunks"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; +import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; diff --git a/gui/src/pages/gui/EmptyChatBody.tsx b/gui/src/pages/gui/EmptyChatBody.tsx index 54185f597..f094c42ef 100644 --- a/gui/src/pages/gui/EmptyChatBody.tsx +++ b/gui/src/pages/gui/EmptyChatBody.tsx @@ -1,6 +1,6 @@ -import { ConversationStarterCards } from "../../components/ConversationStarters"; +import { ConversationStarterCards } from "../../components/ConversationStarters/ConversationStarterCards"; import { ExploreHubCard } from "../../components/ExploreHubCard"; -import { OnboardingCard } from "../../components/OnboardingCard"; +import { OnboardingCard } from "../../components/OnboardingCard/OnboardingCard"; export interface EmptyChatBodyProps { showOnboardingCard?: boolean; diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 580cbd3c0..f3654993a 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -8,17 +8,17 @@ import { import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; import { useContext, useMemo } from "react"; import { GhostButton, SecondaryButton } from "../../components"; -import { useMainEditor } from "../../components/mainInput/TipTapEditor"; +import { useMainEditor } from "../../components/mainInput/TipTapEditor/MainEditorProvider"; import { DiscordIcon } from "../../components/svg/DiscordIcon"; import { GithubIcon } from "../../components/svg/GithubIcon"; import ToggleDiv from "../../components/ToggleDiv"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { selectSelectedProfile } from "../../redux/"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; +import { selectSelectedProfile } from "../../redux/slices/profilesSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { streamResponseThunk } from "../../redux/thunks"; +import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isLocalProfile } from "../../util"; import { providers } from "../AddNewModel/configs/providers"; import { ModelsAddOnLimitDialog } from "./ModelsAddOnLimitDialog"; diff --git a/gui/src/redux/index.ts b/gui/src/redux/index.ts deleted file mode 100644 index 0af19ed8d..000000000 --- a/gui/src/redux/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./slices"; diff --git a/gui/src/redux/slices/index.ts b/gui/src/redux/slices/index.ts deleted file mode 100644 index 09303f508..000000000 --- a/gui/src/redux/slices/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./profiles"; diff --git a/gui/src/redux/slices/profiles/index.ts b/gui/src/redux/slices/profiles/index.ts deleted file mode 100644 index 52fbee8e7..000000000 --- a/gui/src/redux/slices/profiles/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./slice"; diff --git a/gui/src/redux/slices/profiles/slice.ts b/gui/src/redux/slices/profilesSlice.ts similarity index 100% rename from gui/src/redux/slices/profiles/slice.ts rename to gui/src/redux/slices/profilesSlice.ts diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index dcdddafb1..553a2db3b 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -1,10 +1,8 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { Tool } from "core"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn"; -import { - defaultOnboardingCardState, - OnboardingCardState, -} from "../../components/OnboardingCard"; +import { OnboardingCardState } from "../../components/OnboardingCard/OnboardingCard"; +import { defaultOnboardingCardState } from "../../components/OnboardingCard/utils"; import { getLocalStorage, LocalStorageKey } from "../../util/localStorage"; export type ToolPolicy = diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 1e0d098f3..7cecae9be 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -15,10 +15,10 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger"; -import { profilesReducer } from "./slices"; import configReducer from "./slices/configSlice"; import editModeStateReducer from "./slices/editState"; import indexingReducer from "./slices/indexingSlice"; +import { profilesReducer } from "./slices/profilesSlice"; import sessionReducer from "./slices/sessionSlice"; import tabsReducer from "./slices/tabsSlice"; import uiReducer from "./slices/uiSlice"; diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts index 4471cc0b4..753d47466 100644 --- a/gui/src/redux/thunks/edit.ts +++ b/gui/src/redux/thunks/edit.ts @@ -6,7 +6,7 @@ import { SetCodeToEditPayload, } from "core"; import { stripImages } from "core/util/messageContent"; -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; import { clearCodeToEdit, INITIAL_EDIT_APPLY_STATE, diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 1078b9589..763429eb8 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -8,7 +8,7 @@ import { SlashCommandDescription, } from "core"; import * as URI from "uri-js"; -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; import { selectSelectedChatModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts deleted file mode 100644 index 43e35fd21..000000000 --- a/gui/src/redux/thunks/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from "./callCurrentTool"; -export * from "./cancelCurrentToolCall"; -export * from "./cancelStream"; -export * from "./edit"; -export * from "./gatherContext"; -export * from "./resetStateForNewMessage"; -export * from "./selectFirstHubProfile"; -export * from "./streamNormalInput"; -export * from "./streamResponse"; -export * from "./streamResponseAfterToolCall"; -export * from "./streamThunkWrapper"; -export * from "./updateSelectedModelByRole"; diff --git a/gui/src/redux/thunks/selectFirstHubProfile.ts b/gui/src/redux/thunks/selectFirstHubProfile.ts index d1715ed98..017d7d783 100644 --- a/gui/src/redux/thunks/selectFirstHubProfile.ts +++ b/gui/src/redux/thunks/selectFirstHubProfile.ts @@ -1,5 +1,5 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { setSelectedProfile } from "../slices"; +import { setSelectedProfile } from "../slices/profilesSlice"; import { ThunkApiType } from "../store"; /** diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts index 49e259421..68000145e 100644 --- a/gui/src/redux/thunks/updateFileSymbols.ts +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -1,6 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatHistoryItem, ContextItemWithId } from "core"; -import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions"; +import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock"; import { updateFileSymbols } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index a560aaf22..b52bf42bc 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -1,5 +1,5 @@ import { JSONContent } from "@tiptap/react"; -import { OnboardingStatus } from "../components/OnboardingCard"; +import { OnboardingStatus } from "../components/OnboardingCard/utils"; type LocalStorageTypes = { isExploreDialogOpen: boolean; diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 0ca3c7e3c..0354377a6 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -5,7 +5,7 @@ import { PropsWithChildren } from "react"; import { Provider } from "react-redux"; import { MemoryRouter, RouterProps } from "react-router-dom"; import { LumpProvider } from "../../components/mainInput/Lump/LumpContext"; -import { MainEditorProvider } from "../../components/mainInput/TipTapEditor"; +import { MainEditorProvider } from "../../components/mainInput/TipTapEditor/MainEditorProvider"; import { AuthProvider } from "../../context/Auth"; import { IdeMessengerProvider } from "../../context/IdeMessenger"; import { MockIdeMessenger } from "../../context/MockIdeMessenger"; From 5f166b6401437623d29527ea04f079783d14780e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 17:40:34 -0700 Subject: [PATCH 41/95] add maxResults param to getSearchResults message --- core/config/types.ts | 2 +- core/index.d.ts | 2 +- core/protocol/ide.ts | 2 +- core/protocol/messenger/messageIde.ts | 4 ++-- core/protocol/messenger/reverseMessageIde.ts | 2 +- core/util/filesystem.ts | 2 +- .../continue/IdeProtocolClient.kt | 2 +- .../continue/IntelliJIde.kt | 22 ++++++++++++++----- .../continueintellijextension/protocol/ide.kt | 2 +- .../continueintellijextension/types.kt | 2 +- extensions/vscode/src/VsCodeIde.ts | 3 ++- .../vscode/src/extension/VsCodeMessenger.ts | 2 +- 12 files changed, 29 insertions(+), 18 deletions(-) diff --git a/core/config/types.ts b/core/config/types.ts index 8b7b07e3d..df29d6071 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -719,7 +719,7 @@ declare global { getPinnedFiles(): Promise; - getSearchResults(query: string): Promise; + getSearchResults(query: string, maxResults?: number): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; diff --git a/core/index.d.ts b/core/index.d.ts index ce78a8d82..a881e7b42 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -781,7 +781,7 @@ export interface IDE { getPinnedFiles(): Promise; - getSearchResults(query: string): Promise; + getSearchResults(query: string, maxResults?: number): Promise; getFileResults(pattern: string): Promise; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index fda1b84fe..2363d1ca0 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -29,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { openFile: [{ path: string }, void]; openUrl: [string, void]; runCommand: [{ command: string; options?: TerminalOptions }, void]; - getSearchResults: [{ query: string }, string]; + getSearchResults: [{ query: string; maxResults?: number }, string]; getFileResults: [{ pattern: string }, string[]]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 2bc52bca8..87e1ec642 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -185,8 +185,8 @@ export class MessageIde implements IDE { return this.request("getPinnedFiles", undefined); } - getSearchResults(query: string): Promise { - return this.request("getSearchResults", { query }); + getSearchResults(query: string, maxResults?: number): Promise { + return this.request("getSearchResults", { query, maxResults }); } getFileResults(pattern: string): Promise { diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index f40915664..0771051aa 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -159,7 +159,7 @@ export class ReverseMessageIde { }); this.on("getSearchResults", (data) => { - return this.ide.getSearchResults(data.query); + return this.ide.getSearchResults(data.query, data.maxResults); }); this.on("getFileResults", (data) => { diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 0bdaffbfd..35eaa6b07 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -234,7 +234,7 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - async getSearchResults(query: string): Promise { + async getSearchResults(query: string, maxResults?: number): Promise { return ""; } 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 cd2b3b86a..4c2151921 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 @@ -356,7 +356,7 @@ class IdeProtocolClient( dataElement.toString(), GetSearchResultsParams::class.java ) - val results = ide.getSearchResults(params.query) + val results = ide.getSearchResults(params.query, params.maxResults) respond(results) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 908ba2edd..6fb0dc950 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -344,11 +344,11 @@ class IntelliJIDE( throw NotImplementedError("Ripgrep not supported, this workspace is remote") } } - override suspend fun getSearchResults(query: String): String { + override suspend fun getSearchResults(query: String, maxResults: Int?): String { val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { try { - val command = GeneralCommandLine( + val commandArgs = mutableListOf( ripgrep, "-i", "--ignore-file", @@ -357,11 +357,21 @@ class IntelliJIDE( ".gitignore", "-C", "2", - "--heading", - "-e", - query, - "." + "--heading" ) + + // Conditionally add maxResults flag + if (maxResults != null) { + commandArgs.add("-m") + commandArgs.add(maxResults.toString()) + } + + // Add the search query and path + commandArgs.add("-e") + commandArgs.add(query) + commandArgs.add(".") + + val command = GeneralCommandLine(commandArgs) command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 4c66fcc0c..807b9d0db 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -21,7 +21,7 @@ typealias OpenUrlParam = String typealias getTagsParams = String -data class GetSearchResultsParams(val query: String) +data class GetSearchResultsParams(val query: String, val maxResults: Int?) data class GetFileResultsParams(val pattern: String) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 71e7092e0..431173315 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -157,7 +157,7 @@ interface IDE { suspend fun getPinnedFiles(): List - suspend fun getSearchResults(query: String): String + suspend fun getSearchResults(query: String, maxResults: Int?): String suspend fun getFileResults(pattern: String): List diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index dcc17d179..7f27d123b 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -524,7 +524,7 @@ class VsCodeIde implements IDE { } } - async getSearchResults(query: string): Promise { + async getSearchResults(query: string, maxResults?: number): Promise { if (vscode.env.remoteName) { throw new Error("Ripgrep not supported, this workspace is remote"); } @@ -539,6 +539,7 @@ class VsCodeIde implements IDE { "-C", "2", // Show 2 lines of context "--heading", // Only show filepath once per result + ...(maxResults ? ["-m", maxResults.toString()] : []), "-e", query, // Pattern to search for ".", // Directory to search in diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index b0c0a4d7b..3e11b11e6 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -321,7 +321,7 @@ export class VsCodeMessenger { await ide.runCommand(msg.data.command); }); this.onWebviewOrCore("getSearchResults", async (msg) => { - return ide.getSearchResults(msg.data.query); + return ide.getSearchResults(msg.data.query, msg.data.maxResults); }); this.onWebviewOrCore("getFileResults", async (msg) => { return ide.getFileResults(msg.data.pattern); From d30c3571429ba754f61d2649a95b121e4a2894a1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 17:41:44 -0700 Subject: [PATCH 42/95] improved grep formatting function --- .../providers/SearchContextProvider.ts | 9 ++++- core/tools/implementations/grepSearch.ts | 38 +++++++++++++++++-- core/util/grepSearch.ts | 35 ++++++++++++++++- 3 files changed, 75 insertions(+), 7 deletions(-) diff --git a/core/context/providers/SearchContextProvider.ts b/core/context/providers/SearchContextProvider.ts index ec75994c3..b6ec40133 100644 --- a/core/context/providers/SearchContextProvider.ts +++ b/core/context/providers/SearchContextProvider.ts @@ -6,6 +6,7 @@ import { import { formatGrepSearchResults } from "../../util/grepSearch.js"; import { BaseContextProvider } from "../index.js"; +const DEFAULT_MAX_SEARCH_CONTEXT_RESULTS = 200; class SearchContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { title: "search", @@ -19,8 +20,12 @@ class SearchContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const results = await extras.ide.getSearchResults(query); - const formatted = formatGrepSearchResults(results); + const results = await extras.ide.getSearchResults( + query, + this.options?.maxResults ?? DEFAULT_MAX_SEARCH_CONTEXT_RESULTS, + ); + // Note, search context provider will not truncate result chars, but will limit number of results + const { formatted } = formatGrepSearchResults(results); return [ { description: "Search results", diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index a506be9cd..8481a89c8 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,13 +1,45 @@ import { ToolImpl } from "."; +import { ContextItem } from "../.."; import { formatGrepSearchResults } from "../../util/grepSearch"; +const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; +const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now + export const grepSearchImpl: ToolImpl = async (args, extras) => { - const results = await extras.ide.getSearchResults(args.query); - return [ + const results = await extras.ide.getSearchResults( + args.query, + DEFAULT_GREP_SEARCH_RESULTS_LIMIT, + ); + const { formatted, numResults, truncated } = formatGrepSearchResults( + results, + DEFAULT_GREP_SEARCH_CHAR_LIMIT, + ); + console.log(results); + const truncationReasons: string[] = []; + if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) { + truncationReasons.push( + `the number of results exceeded ${DEFAULT_GREP_SEARCH_RESULTS_LIMIT}`, + ); + } + if (truncated) { + truncationReasons.push( + `the number of characters exceeded ${DEFAULT_GREP_SEARCH_CHAR_LIMIT}`, + ); + } + + const contextItems: ContextItem[] = [ { name: "Search results", description: "Results from grep search", - content: formatGrepSearchResults(results), + content: formatted, }, ]; + if (truncationReasons.length > 0) { + contextItems.push({ + name: "Search truncation warning", + description: "Informs the model that search results were truncated", + content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`, + }); + } + return contextItems; }; diff --git a/core/util/grepSearch.ts b/core/util/grepSearch.ts index a30982e77..4d74d0cc6 100644 --- a/core/util/grepSearch.ts +++ b/core/util/grepSearch.ts @@ -1,4 +1,19 @@ -export function formatGrepSearchResults(results: string): string { +/* + Formats the output of a grep search to reduce unnecessary indentation, lines, etc + Assumes a command with these params + ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e . + + Also can truncate the output to a specified number of characters +*/ +export function formatGrepSearchResults( + results: string, + maxChars?: number, +): { + formatted: string; + numResults: number; + truncated: boolean; +} { + let numResults = 0; const keepLines: string[] = []; function countLeadingSpaces(line: string) { @@ -43,6 +58,9 @@ export function formatGrepSearchResults(results: string): string { let resultLines: string[] = []; for (const line of results.split("\n").filter((l) => !!l)) { if (line.startsWith("./") || line === "--") { + if (line.startsWith("./")) { + numResults++; + } processResult(resultLines); // process previous result resultLines = [line]; continue; @@ -57,5 +75,18 @@ export function formatGrepSearchResults(results: string): string { } processResult(resultLines); - return keepLines.join("\n"); + const formatted = keepLines.join("\n"); + if (maxChars && formatted.length > maxChars) { + return { + formatted: formatted.substring(0, maxChars), + numResults, + truncated: true, + }; + } else { + return { + formatted, + numResults, + truncated: false, + }; + } } From 5fdd168502ff66c52382755fabd406b2d3181bbf Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 17:42:09 -0700 Subject: [PATCH 43/95] update search tool and context provider docs/schema --- docs/docs/agent/how-it-works.md | 2 +- docs/docs/customize/context-providers.mdx | 7 ++++++- extensions/vscode/config_schema.json | 23 +++++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md index 1191fa9f8..650d5bf55 100644 --- a/docs/docs/agent/how-it-works.md +++ b/docs/docs/agent/how-it-works.md @@ -31,7 +31,7 @@ Continue includes several built-in tools which provide the model access to IDE f - **Read file** (`builtin_read_file`): read the contents of a file within the project - **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file - **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model -- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project +- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project. Results are limited to 100 results and 5000 characters (model is warned if this is exceeded) - **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root - **Search web** (`builtin_search_web`): Perform a web search to get top results - **View diff** (`builtin_view_diff`): View the current working git diff diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index 204f680f0..c55bbfbbd 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -288,6 +288,8 @@ Reference the results of codebase search, just like the results you would get fr ```yaml title="config.yaml" context: - provider: search + params: + maxResults: 100 # optional, defaults to 200 ``` @@ -295,7 +297,10 @@ Reference the results of codebase search, just like the results you would get fr { "contextProviders": [ { - "name": "search" + "name": "search", + "params": { + "maxResults": 100 // optional, defaults to 200 + } } ] } diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 76686f24e..29d882489 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2144,6 +2144,29 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": ["search"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "maxResults": { + "title": "Max Results", + "description": "The maximum number of results to return", + "default": 200, + "type": "integer" + } + } + } + } + } + }, { "if": { "properties": { From 4705ab6dae3fa4e0a1e7206ed914bc054f29fd8d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 17:42:19 -0700 Subject: [PATCH 44/95] add grep search tests --- core/util/grepSearch.vitest.ts | 217 +++++++++++++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 core/util/grepSearch.vitest.ts diff --git a/core/util/grepSearch.vitest.ts b/core/util/grepSearch.vitest.ts new file mode 100644 index 000000000..4b3c74656 --- /dev/null +++ b/core/util/grepSearch.vitest.ts @@ -0,0 +1,217 @@ +import { expect, test } from "vitest"; +import { formatGrepSearchResults } from "./grepSearch"; + +// Sample grep output mimicking what would come from ripgrep with the params: +// ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e . +const sampleGrepOutput = `./program.cs + Console.WriteLine("Hello World!"); + Calculator calc = new Calculator(); + calc.Add(5).Subtract(3); + Console.WriteLine("Result: " + calc.GetResult()); + } +-- + } + + public Calculator Subtract(double number) + { + result -= number; + +./test.kt + } + + fun subtract(number: Double): Test { + result -= number + return this + +./test.php + } + + public function subtract($number) { + $this->result -= $number; + return $this; +-- + +$calc = new Calculator(); +$calc->add(10)->subtract(5); +echo "Result: " . $calc->getResult() . "\n"; + + +./Calculator.java + } + + public Calculator subtract(double number) { + result -= number; + return this; +-- + public static void main(String[] args) { + Calculator calc = new Calculator(); + calc.add(10).subtract(5); + System.out.println("Result: " + calc.getResult()); + } + +./calculator_test/Calculator.java + } + + public int subtract(int a, int b) { + return a - b; + } + +./test.rb + end + + def subtract(number) + @result -= number + self +-- + +calc = Calculator.new +calc.add(5).subtract(3) +puts "Result: #{calc.get_result}" + +./test.js + return this; + } + subtract(number) { + return this; + } + +./test.py + return self + + def subtract(self, number): + self.result -= number + return self + +./test.ts + } + + subtract(number: number): Calculator { + this.result -= number; + return this;`; + +test("formats grep search results correctly", () => { + const result = formatGrepSearchResults(sampleGrepOutput); + + expect(result.numResults).toBe(9); // 4 file paths in the sample + expect(result.truncated).toBe(false); + + // Check that all file paths are preserved + expect(result.formatted).toContain("./program.cs"); + expect(result.formatted).toContain("./test.kt"); + expect(result.formatted).toContain("./test.php"); + expect(result.formatted).toContain("./Calculator.java"); + + // Check that content is preserved and properly indented + expect(result.formatted).toContain('Console.WriteLine("Hello World!");'); + expect(result.formatted).toContain("fun subtract(number: Double): Test {"); + expect(result.formatted).toContain("public function subtract($number) {"); + expect(result.formatted).toContain( + "public Calculator subtract(double number) {", + ); +}); + +test("handles empty input", () => { + const result = formatGrepSearchResults(""); + + expect(result.numResults).toBe(0); + expect(result.truncated).toBe(false); + expect(result.formatted).toBe(""); +}); + +test("handles input with only file paths (no content) - lines should be skipped", () => { + const input = + "./empty-file.ts\n./another-empty.js\n./has-content.ts\n searchMatch"; + const result = formatGrepSearchResults(input); + + expect(result.numResults).toBe(3); + expect(result.formatted).toBe("./has-content.ts\n searchMatch"); +}); + +test("truncates output when exceeding maxChars", () => { + const maxChars = 50; + const result = formatGrepSearchResults(sampleGrepOutput, maxChars); + + expect(result.truncated).toBe(true); + expect(result.formatted.length).toBe(maxChars); +}); + +test("normalizes indentation to 2 spaces", () => { + const input = `./file.ts + function test() { + const x = 1; + console.log(x); + }`; + + const result = formatGrepSearchResults(input); + + // The function should normalize the indentation to 2 spaces + expect(result.formatted).toContain("./file.ts"); + expect(result.formatted).toContain(" function test() {"); + expect(result.formatted).toContain(" const x = 1;"); + expect(result.formatted).toContain(" console.log(x);"); + expect(result.formatted).toContain(" }"); +}); + +test("skips leading single-char or empty lines after file paths", () => { + const input = `./file.ts + +function test() { + console.log("test"); +}`; + + const result = formatGrepSearchResults(input); + + expect(result.formatted).toContain("./file.ts"); + expect(result.formatted).not.toContain("\n \n"); // The single space line should be skipped + expect(result.formatted).toContain("function test() {"); +}); + +test("processes separator lines correctly", () => { + const input = `./file1.ts +function one() { + return 1; +} +-- +function two() { + return 2; +} + +./file2.ts +class Test { + method() {} +}`; + + const result = formatGrepSearchResults(input); + + expect(result.numResults).toBe(2); + expect(result.formatted).toContain("./file1.ts"); + expect(result.formatted).toContain("--"); + expect(result.formatted).toContain("function two() {"); + expect(result.formatted).toContain("./file2.ts"); +}); + +test("increases indentation when original is less than 2 spaces", () => { + const input = `./minimal-indent.ts +function test() { + singleSpaceIndent(); +}`; + + const result = formatGrepSearchResults(input); + + expect(result.formatted).toContain(" function test() {"); + expect(result.formatted).toContain(" singleSpaceIndent();"); + expect(result.formatted).toContain(" }"); +}); + +test("decreases indentation when original is more than 2 spaces", () => { + const input = `./excessive-indent.ts + function test() { + tooMuchIndent(); + }`; + + const result = formatGrepSearchResults(input); + + expect(result.formatted).toContain(" function test() {"); + expect(result.formatted).toContain(" tooMuchIndent();"); + expect(result.formatted).toContain(" }"); +}); From 26c50d0f9e666e2b89da0f6c5fead64d796ef22e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 18:02:14 -0700 Subject: [PATCH 45/95] update grep search tool description --- core/tools/definitions/grepSearch.ts | 3 ++- core/tools/implementations/grepSearch.ts | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index ca8a73a30..60a4e2710 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -12,7 +12,8 @@ export const grepSearchTool: Tool = { group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.GrepSearch, - description: "Perform a search over the repository using ripgrep.", + description: + "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries", parameters: { type: "object", required: ["query"], diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index 8481a89c8..149b68a75 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -14,7 +14,6 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { results, DEFAULT_GREP_SEARCH_CHAR_LIMIT, ); - console.log(results); const truncationReasons: string[] = []; if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) { truncationReasons.push( From 031c60b10ca77f386531c23103c7c2480fe4b0f5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 18:18:40 -0700 Subject: [PATCH 46/95] fix logic for multiple workspaces max results in vscode --- extensions/vscode/src/VsCodeIde.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 7f27d123b..04f39f1db 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -548,7 +548,12 @@ class VsCodeIde implements IDE { results.push(dirResults); } - return results.join("\n"); + if (maxResults) { + // With multiple workspaces, we will pull max results from EACH workspace and then truncate to max results just in case + return results.join("\n").split("\n./").slice(0, maxResults).join("\n./"); + } else { + return results.join("\n"); + } } async getProblems(fileUri?: string | undefined): Promise { From 262cd80a370cd5bd54080292a4c5cd4c530d51cb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 18:21:03 -0700 Subject: [PATCH 47/95] fix numResults logic in grep output formatting --- core/util/grepSearch.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/core/util/grepSearch.ts b/core/util/grepSearch.ts index 4d74d0cc6..be5b7ee08 100644 --- a/core/util/grepSearch.ts +++ b/core/util/grepSearch.ts @@ -58,11 +58,9 @@ export function formatGrepSearchResults( let resultLines: string[] = []; for (const line of results.split("\n").filter((l) => !!l)) { if (line.startsWith("./") || line === "--") { - if (line.startsWith("./")) { - numResults++; - } processResult(resultLines); // process previous result resultLines = [line]; + numResults++; continue; } From 75db17fb585762614f19762a2d5a0baf9e9bb74d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 18:22:42 -0700 Subject: [PATCH 48/95] fix grep formatting tests to account for -- --- core/util/grepSearch.vitest.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/util/grepSearch.vitest.ts b/core/util/grepSearch.vitest.ts index 4b3c74656..df1a71efd 100644 --- a/core/util/grepSearch.vitest.ts +++ b/core/util/grepSearch.vitest.ts @@ -92,7 +92,7 @@ puts "Result: #{calc.get_result}" test("formats grep search results correctly", () => { const result = formatGrepSearchResults(sampleGrepOutput); - expect(result.numResults).toBe(9); // 4 file paths in the sample + expect(result.numResults).toBe(13); // 4 file paths in the sample expect(result.truncated).toBe(false); // Check that all file paths are preserved @@ -183,7 +183,7 @@ class Test { const result = formatGrepSearchResults(input); - expect(result.numResults).toBe(2); + expect(result.numResults).toBe(3); expect(result.formatted).toContain("./file1.ts"); expect(result.formatted).toContain("--"); expect(result.formatted).toContain("function two() {"); From 68599341c580a843f96752e37ec3e77bcb770127 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 18:52:39 -0700 Subject: [PATCH 49/95] fix multiple workspaces grep logic --- extensions/vscode/src/VsCodeIde.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 04f39f1db..bb701db6a 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -548,11 +548,19 @@ class VsCodeIde implements IDE { results.push(dirResults); } + const allResults = results.join("\n"); if (maxResults) { - // With multiple workspaces, we will pull max results from EACH workspace and then truncate to max results just in case - return results.join("\n").split("\n./").slice(0, maxResults).join("\n./"); + // In case of multiple workspaces, do max results per workspace and then truncate to maxResults + // Will prioritize first workspace results, fine for now + // Results are separated by either ./ or -- + const matches = Array.from(allResults.matchAll(/(\n--|\n\.\/)/g)); + if (matches.length > maxResults) { + return allResults.substring(0, matches[maxResults].index); + } else { + return allResults; + } } else { - return results.join("\n"); + return allResults; } } From 73818bb7082694f46b3245a33c9f2c855e724c56 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 19:03:09 -0700 Subject: [PATCH 50/95] implement maxResults param for getFileResults ide message --- core/index.d.ts | 2 +- core/protocol/ide.ts | 2 +- core/protocol/messenger/reverseMessageIde.ts | 2 +- core/util/filesystem.ts | 5 ++++- .../continue/IdeProtocolClient.kt | 2 +- .../continue/IntelliJIde.kt | 12 +++++++++--- .../continueintellijextension/protocol/ide.kt | 2 +- .../continueintellijextension/types.kt | 2 +- extensions/vscode/src/VsCodeIde.ts | 18 ++++++++++++++---- .../vscode/src/extension/VsCodeMessenger.ts | 2 +- 10 files changed, 34 insertions(+), 15 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index ce78a8d82..4f422dfae 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -783,7 +783,7 @@ export interface IDE { getSearchResults(query: string): Promise; - getFileResults(pattern: string): Promise; + getFileResults(pattern: string, maxResults?: number): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index fda1b84fe..5e24a62ff 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -30,7 +30,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { openUrl: [string, void]; runCommand: [{ command: string; options?: TerminalOptions }, void]; getSearchResults: [{ query: string }, string]; - getFileResults: [{ pattern: string }, string[]]; + getFileResults: [{ pattern: string; maxResults?: number }, string[]]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; fileExists: [{ filepath: string }, boolean]; diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index f40915664..447a66c65 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -163,7 +163,7 @@ export class ReverseMessageIde { }); this.on("getFileResults", (data) => { - return this.ide.getFileResults(data.pattern); + return this.ide.getFileResults(data.pattern, data.maxResults); }); this.on("getProblems", (data) => { diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 0bdaffbfd..6f131df18 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -238,7 +238,10 @@ class FileSystemIde implements IDE { return ""; } - async getFileResults(pattern: string): Promise { + async getFileResults( + pattern: string, + maxResults?: number, + ): Promise { return []; } 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 cd2b3b86a..b1c91b1d7 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 @@ -365,7 +365,7 @@ class IdeProtocolClient( dataElement.toString(), GetFileResultsParams::class.java ) - val results = ide.getFileResults(params.pattern) + val results = ide.getFileResults(params.pattern, params.maxResults) respond(results) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 908ba2edd..0026ae518 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -315,11 +315,11 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getFileResults(pattern: String): List { + override suspend fun getFileResults(pattern: String, maxResults: Int?): List { val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { try { - val command = GeneralCommandLine( + var commandArgs = mutableListOf( ripgrep, "--files", "--iglob", @@ -327,8 +327,14 @@ class IntelliJIDE( "--ignore-file", ".continueignore", "--ignore-file", - ".gitignore", + ".gitignore" ) + if (maxResults != null) { + commandArgs.add("--max-count") + commandArgs.add(maxResults.toString()) + } + + val command = GeneralCommandLine(commandArgs) command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 4c66fcc0c..170ed05a6 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,7 +23,7 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) -data class GetFileResultsParams(val pattern: String) +data class GetFileResultsParams(val pattern: String, val maxResults: Int?) data class SaveFileParams(val filepath: String) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 71e7092e0..c09021fff 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -159,7 +159,7 @@ interface IDE { suspend fun getSearchResults(query: String): String - suspend fun getFileResults(pattern: String): List + suspend fun getFileResults(pattern: String, maxResults: Int?): List // Note: This should be a `Pair` but we use `List` because the keys of `Pair` // will serialize to `first and `second` rather than `0` and `1` like in JavaScript diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index dcc17d179..149d09066 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -433,8 +433,10 @@ class VsCodeIde implements IDE { }); } - async getFileResults(pattern: string): Promise { - const MAX_FILE_RESULTS = 200; + async getFileResults( + pattern: string, + maxResults?: number, + ): Promise { if (vscode.env.remoteName) { // TODO better tests for this remote search implementation // throw new Error("Ripgrep not supported, this workspace is remote"); @@ -501,7 +503,7 @@ class VsCodeIde implements IDE { const results = await vscode.workspace.findFiles( pattern, ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null, - MAX_FILE_RESULTS, + maxResults, ); return results.map((result) => vscode.workspace.asRelativePath(result)); } else { @@ -515,12 +517,20 @@ class VsCodeIde implements IDE { ".continueignore", "--ignore-file", ".gitignore", + ...(maxResults ? ["--max-count", String(maxResults)] : []), ]); results.push(dirResults); } - return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS); + const allResults = results.join("\n").split("\n"); + if (maxResults) { + // In the case of multiple workspaces, maxResults will be applied to each workspace + // And then the combined results will also be truncated + return allResults.slice(0, maxResults); + } else { + return allResults; + } } } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index b0c0a4d7b..6b34d04fc 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -324,7 +324,7 @@ export class VsCodeMessenger { return ide.getSearchResults(msg.data.query); }); this.onWebviewOrCore("getFileResults", async (msg) => { - return ide.getFileResults(msg.data.pattern); + return ide.getFileResults(msg.data.pattern, msg.data.maxResults); }); this.onWebviewOrCore("subprocess", async (msg) => { return ide.subprocess(msg.data.command, msg.data.cwd); From 2cf2a74646c65104a4f9481683b11872c49e5bc6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 19:07:59 -0700 Subject: [PATCH 51/95] implement glob limiting in tool --- core/tools/definitions/globSearch.ts | 3 ++- core/tools/implementations/globSearch.ts | 20 ++++++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index 5c2375124..b3cbcac5b 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -12,7 +12,8 @@ export const globSearchTool: Tool = { group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.FileGlobSearch, - description: "Search for files in the project", + description: + "Search for files in the project. Output may be truncated; use targeted patterns", parameters: { type: "object", required: ["pattern"], diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts index c0b214357..1e551d9e2 100644 --- a/core/tools/implementations/globSearch.ts +++ b/core/tools/implementations/globSearch.ts @@ -1,12 +1,28 @@ import { ToolImpl } from "."; +import { ContextItem } from "../.."; +const MAX_AGENT_GLOB_RESULTS = 100; export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { - const results = await extras.ide.getFileResults(args.pattern); - return [ + const results = await extras.ide.getFileResults( + args.pattern, + MAX_AGENT_GLOB_RESULTS, + ); + const contextItems: ContextItem[] = [ { name: "File results", description: "Results from file glob search", content: results.join("\n"), }, ]; + + // In case of truncation, add a warning + if (results.length === MAX_AGENT_GLOB_RESULTS) { + contextItems.push({ + name: "Truncation warning", + description: "Inform the model that results were truncated", + content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`, + }); + } + + return contextItems; }; From 2b5b09ebb2b16a76cf86812c84e94da314e0bb8b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 19:14:03 -0700 Subject: [PATCH 52/95] update the docs --- docs/docs/agent/how-it-works.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md index 1191fa9f8..5847b99a5 100644 --- a/docs/docs/agent/how-it-works.md +++ b/docs/docs/agent/how-it-works.md @@ -32,6 +32,7 @@ Continue includes several built-in tools which provide the model access to IDE f - **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file - **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model - **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project +- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. - **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root - **Search web** (`builtin_search_web`): Perform a web search to get top results - **View diff** (`builtin_view_diff`): View the current working git diff From 275c9035ba35d8248db0d3fb996fd1314134fb8d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 19:14:51 -0700 Subject: [PATCH 53/95] fix the incorrect grep tool name in the docs --- docs/docs/agent/how-it-works.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md index 650d5bf55..1bfeb075c 100644 --- a/docs/docs/agent/how-it-works.md +++ b/docs/docs/agent/how-it-works.md @@ -31,7 +31,7 @@ Continue includes several built-in tools which provide the model access to IDE f - **Read file** (`builtin_read_file`): read the contents of a file within the project - **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file - **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model -- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project. Results are limited to 100 results and 5000 characters (model is warned if this is exceeded) +- **Grep search** (`builtin_grep_search`): perform a `ripgrep` search within the project. Results are limited to 100 results and 5000 characters (model is warned if this is exceeded) - **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root - **Search web** (`builtin_search_web`): Perform a web search to get top results - **View diff** (`builtin_view_diff`): View the current working git diff From a4c5a489e288025a4452a6d6e8f0991ec8ed0eba Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 19 Jun 2025 19:35:19 -0700 Subject: [PATCH 54/95] update unit testing rules --- .continue/rules/unit-testing-rules.yaml | 30 ++++++++++++------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/.continue/rules/unit-testing-rules.yaml b/.continue/rules/unit-testing-rules.yaml index ec22e9467..f846986c2 100644 --- a/.continue/rules/unit-testing-rules.yaml +++ b/.continue/rules/unit-testing-rules.yaml @@ -6,25 +6,23 @@ rules: rule: >- For unit testing in this project: + 1. The project uses Vitest and Jest for testing. Prefer Vitest - 1. The project uses Jest as the testing framework + 2. Run tests from within the specific package directory (e.g., `cd core && ..` - 2. Run tests using `npm test` from within the specific package/module - directory + 3. For vitest tests, + - Test files follow the pattern `*.vitest.ts` + - Run tests using `vitest` from within the specific package/module + directory: `cd [directory] && vitest -- [test file path]` - 3. Command structure: `cd [directory] && npm test -- [test file path]` + 4. For jest tests, + - Test files follow the pattern `*.test.ts` + - Run tests using `npm test` from within the specific package/module + directory: `cd [directory] && npm test -- [test file path]` + - The test script uses experimental VM modules via NODE_OPTIONS flag - 4. The test script uses experimental VM modules via NODE_OPTIONS flag - - 5. Test files follow the pattern `*.test.ts` - - 6. Tests must import Jest with `import { jest } from "@jest/globals";` - - 7. Run tests from within the specific package directory (e.g., `cd core` - for core module tests) - - 8. Write tests as top-level `test()` functions - DO NOT use `describe()` + 5. For both + - Write tests as top-level `test()` functions - DO NOT use `describe()` blocks - - 9. Include the function name being tested in the test description for + - Include the function name being tested in the test description for clarity From 8a79d55cba7664d8ca7537a043f56b4910b114b7 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 20 Jun 2025 16:58:16 +0530 Subject: [PATCH 55/95] increase context length and add tests --- core/llm/constants.ts | 2 +- core/llm/index.test.ts | 31 +++++++++++++++++++++++++++++++ core/llm/llms/Anthropic.ts | 1 - core/llm/llms/Bedrock.ts | 1 - 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 19b067d15..0975fc142 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -1,5 +1,5 @@ const DEFAULT_MAX_TOKENS = 4096; -const DEFAULT_CONTEXT_LENGTH = 8192; +const DEFAULT_CONTEXT_LENGTH = 32_768; const DEFAULT_TEMPERATURE = 0.5; const DEFAULT_ARGS = { diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 7584e2122..1e7031f50 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -1,6 +1,10 @@ import { ChatMessage, LLMOptions } from ".."; +import { allModelProviders } from "@continuedev/llm-info"; +import { LlmInfo } from "@continuedev/llm-info/dist/types"; import { BaseLLM } from "."; +import { DEFAULT_CONTEXT_LENGTH } from "./constants"; +import { LLMClasses } from "./llms"; import { LLMLogger } from "./logger"; class DummyLLM extends BaseLLM { @@ -140,4 +144,31 @@ describe("BaseLLM", () => { describe("*streamChat", () => { // TODO: Implement tests for *streamChat method }); + + describe("default context length", () => { + allModelProviders.map((modelProvider) => { + const LLMClass = LLMClasses.find( + (llm) => llm.providerName === modelProvider.id, + ); + if (!LLMClass) { + throw new Error(`did not find LLM provider for ${modelProvider.id}`); + } + const testContextLength = (llmInfo: LlmInfo) => () => { + const llm = new LLMClass({ model: llmInfo.model }); + if (llmInfo.contextLength) { + expect(llm.contextLength).toEqual(llmInfo.contextLength); + } else { + expect(llm.contextLength).toEqual(DEFAULT_CONTEXT_LENGTH); + } + }; + describe(`${modelProvider.id}`, () => { + modelProvider.models.forEach((llmInfo) => { + test( + `should have correct context length for ${llmInfo.model}`, + testContextLength(llmInfo), + ); + }); + }); + }); + }); }); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8d1d3a67f..ff0f78c06 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -8,7 +8,6 @@ class Anthropic extends BaseLLM { static providerName = "anthropic"; static defaultOptions: Partial = { model: "claude-3-5-sonnet-latest", - contextLength: 200_000, completionOptions: { model: "claude-3-5-sonnet-latest", maxTokens: 8192, diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index ae595f3f3..30ce69e7a 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -48,7 +48,6 @@ class Bedrock extends BaseLLM { static defaultOptions: Partial = { region: "us-east-1", model: "anthropic.claude-3-sonnet-20240229-v1:0", - contextLength: 200_000, profile: "bedrock", }; From 2c0181bd3e20992bb7f93308e7f761ba2d861f6a Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:01:21 -0700 Subject: [PATCH 56/95] improv: clean up code --- core/llm/rules/getSystemMessageWithRules.ts | 158 ++++++++------------ 1 file changed, 60 insertions(+), 98 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 3a662b1b6..2a2ca584a 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -162,6 +162,45 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { return false; }; +const checkGlobsAndPatterns = ({ + hasGlobs, + hasPatterns, + rule, + filePaths, + fileContents, +}: { + hasGlobs: boolean; + hasPatterns: boolean; + rule: RuleWithSource; + filePaths: string[]; + fileContents: Record; +}) => { + const matchingFiles = hasGlobs + ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) + : filePaths; + + // If no files match the globs, don't apply the rule + if (matchingFiles.length === 0) { + return false; + } + + // Now check for pattern matches in file contents if patterns are specified + if (hasPatterns) { + console.log("HAS PATTERNS", rule.patterns); + // Check if any of the matching files also match the content patterns + return matchingFiles.some((filePath) => { + const content = fileContents[filePath]; + // If we don't have the content, we can't check patterns + if (!content) return false; + return contentMatchesPatterns(content, rule.patterns); + }); + } + + // If we have no patterns or if we couldn't check patterns (no content), + // just go with the glob matches + return matchingFiles.length > 0; +}; + /** * Determines if a rule should be applied based on its properties and file matching * @@ -177,6 +216,7 @@ export const shouldApplyRule = ( fileContents: Record = {}, rulePolicies: RulePolicies = {}, ): boolean => { + console.log("CHECKING SHOULD APPLY RULE", rule); const policy = rulePolicies[rule.name || ""]; // Never apply if policy is "off" @@ -198,6 +238,8 @@ export const shouldApplyRule = ( // Check if this is a root-level rule (in .continue directory or no file path) const isRootRule = isRootLevelRule(rule); + const hasGlobs = rule.globs !== undefined; + const hasPatterns = rule.patterns !== undefined; // For non-root rules, we need to check if any files are in the rule's directory if (!isRootRule && rule.ruleFile) { @@ -211,107 +253,27 @@ export const shouldApplyRule = ( isFileInDirectory(filePath, ruleDirPath), ); - // If no files are in this directory, don't apply the rule - if (filesInRuleDirectory.length === 0) { - return false; - } - - // First check if the files match the globs - const hasGlobs = rule.globs !== undefined; - - // Filter to files that match the globs (or all files if no globs) - const matchingFiles = hasGlobs - ? filesInRuleDirectory.filter((filePath) => - matchesGlobs(filePath, rule.globs), - ) - : filesInRuleDirectory; - - // If no files match the globs, don't apply the rule - if (matchingFiles.length === 0) { - return false; - } - - // Now check for pattern matches in file contents if patterns are specified - if (rule.patterns) { - // Check if any of the matching files also match the content patterns - return matchingFiles.some((filePath) => { - const content = fileContents[filePath]; - // If we don't have the content, we can't check patterns - if (!content) return false; - return contentMatchesPatterns(content, rule.patterns); - }); - } - - // If we have no patterns or if we couldn't check patterns (no content), - // just go with the glob matches - return matchingFiles.length > 0; - } - - // For root-level rules: - - // If alwaysApply is explicitly false, we need to check globs and/or patterns - if (rule.alwaysApply === false) { - const hasGlobs = rule.globs !== undefined; - const hasPatterns = rule.patterns !== undefined; - - if (!hasGlobs && !hasPatterns) { - return false; - } - - // Filter to files that match the globs (or all files if no globs) - const matchingFiles = hasGlobs - ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) - : filePaths; - - // If no files match the globs, don't apply the rule - if (matchingFiles.length === 0) { - return false; - } - - // Now check for pattern matches in file contents if patterns are specified - if (hasPatterns) { - // Check if any of the matching files also match the content patterns - return matchingFiles.some((filePath) => { - const content = fileContents[filePath]; - // If we don't have the content, we can't check patterns - if (!content) return false; - return contentMatchesPatterns(content, rule.patterns); - }); - } - - // If we have no patterns or if we couldn't check patterns (no content), - // just go with the glob matches - return matchingFiles.length > 0; - } - - // Default behavior for root rules with globs: - const hasGlobs = rule.globs !== undefined; - const hasPatterns = rule.patterns !== undefined; - - // Filter to files that match the globs (or all files if no globs) - const matchingFiles = hasGlobs - ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) - : filePaths; - - // If no files match the globs, don't apply the rule - if (matchingFiles.length === 0) { - return false; - } - - // Now check for pattern matches in file contents if patterns are specified - if (hasPatterns) { - // Check if any of the matching files also match the content patterns - return matchingFiles.some((filePath) => { - const content = fileContents[filePath]; - // If we don't have the content, we can't check patterns - if (!content) return false; - return contentMatchesPatterns(content, rule.patterns); + return checkGlobsAndPatterns({ + filePaths: filesInRuleDirectory, + fileContents, + rule, + hasGlobs, + hasPatterns, }); } - // If we have no patterns or if we couldn't check patterns (no content), - // just go with the glob matches - return matchingFiles.length > 0; + // If alwaysApply is explicitly false, we need to check globs and/or patterns + if (rule.alwaysApply === false && !hasGlobs && !hasPatterns) { + return false; + } + + return checkGlobsAndPatterns({ + filePaths, + fileContents, + rule, + hasGlobs, + hasPatterns, + }); }; /** From 559b5aa9fbb7c4fb60e7b67d34822ece16e5474d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:07:07 -0700 Subject: [PATCH 57/95] improv: clean up --- core/llm/rules/getSystemMessageWithRules.ts | 22 +++++++++------------ 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 2a2ca584a..54a7311d2 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -63,6 +63,7 @@ const contentMatchesPatterns = ( fileContent: string, patterns: string | string[] | undefined, ): boolean => { + console.log(""); if (!patterns) return true; // Handle single string pattern @@ -163,19 +164,16 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { }; const checkGlobsAndPatterns = ({ - hasGlobs, - hasPatterns, rule, filePaths, fileContents, }: { - hasGlobs: boolean; - hasPatterns: boolean; rule: RuleWithSource; filePaths: string[]; fileContents: Record; }) => { - const matchingFiles = hasGlobs + console.log("HERE ZZZZ"); + const matchingFiles = rule.globs ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) : filePaths; @@ -185,7 +183,7 @@ const checkGlobsAndPatterns = ({ } // Now check for pattern matches in file contents if patterns are specified - if (hasPatterns) { + if (rule.patterns) { console.log("HAS PATTERNS", rule.patterns); // Check if any of the matching files also match the content patterns return matchingFiles.some((filePath) => { @@ -238,8 +236,6 @@ export const shouldApplyRule = ( // Check if this is a root-level rule (in .continue directory or no file path) const isRootRule = isRootLevelRule(rule); - const hasGlobs = rule.globs !== undefined; - const hasPatterns = rule.patterns !== undefined; // For non-root rules, we need to check if any files are in the rule's directory if (!isRootRule && rule.ruleFile) { @@ -257,13 +253,15 @@ export const shouldApplyRule = ( filePaths: filesInRuleDirectory, fileContents, rule, - hasGlobs, - hasPatterns, }); } // If alwaysApply is explicitly false, we need to check globs and/or patterns - if (rule.alwaysApply === false && !hasGlobs && !hasPatterns) { + if ( + rule.alwaysApply === false && + rule.globs === undefined && + rule.patterns === undefined + ) { return false; } @@ -271,8 +269,6 @@ export const shouldApplyRule = ( filePaths, fileContents, rule, - hasGlobs, - hasPatterns, }); }; From b270e25059d942efce3e910fc670b4f4ff28dfa8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:22:14 -0700 Subject: [PATCH 58/95] Update getSystemMessageWithRules.ts --- core/llm/rules/getSystemMessageWithRules.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 54a7311d2..ccc70c092 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -61,15 +61,15 @@ const matchesGlobs = ( */ const contentMatchesPatterns = ( fileContent: string, - patterns: string | string[] | undefined, + patterns: string | string[], ): boolean => { - console.log(""); - if (!patterns) return true; + console.log("HERE XXXXX"); // Handle single string pattern if (typeof patterns === "string") { try { const regex = new RegExp(patterns); + console.log("REGEX", regex); return regex.test(fileContent); } catch (e) { console.error(`Invalid regex pattern: ${patterns}`, e); @@ -188,9 +188,10 @@ const checkGlobsAndPatterns = ({ // Check if any of the matching files also match the content patterns return matchingFiles.some((filePath) => { const content = fileContents[filePath]; + console.log("TESTING FILE MATCH", content); // If we don't have the content, we can't check patterns if (!content) return false; - return contentMatchesPatterns(content, rule.patterns); + return contentMatchesPatterns(content, rule.patterns!); }); } @@ -304,10 +305,12 @@ export const getApplicableRules = ( // Extract contents from context items with file URIs contextItems.forEach((item) => { + console.log("ITEM", item); if (item.uri?.type === "file" && item.uri?.value) { fileContents[item.uri.value] = item.content; } }); + console.log("FILE CONTENTS", fileContents); // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, // and path matching in a consistent way From 4cf154d9c9b90103fe5afaf69c28e8cfaaf8d028 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:27:33 -0700 Subject: [PATCH 59/95] fix: pattern matching --- core/llm/rules/getSystemMessageWithRules.ts | 17 ++++++++++- .../llm/utils/extractContentFromCodeBlocks.ts | 29 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 core/llm/utils/extractContentFromCodeBlocks.ts diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index ccc70c092..bdfe0aa0a 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -7,6 +7,7 @@ import { } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { getCleanUriPath } from "../../util/uri"; +import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; import { RulePolicies } from "./types"; @@ -305,11 +306,25 @@ export const getApplicableRules = ( // Extract contents from context items with file URIs contextItems.forEach((item) => { - console.log("ITEM", item); if (item.uri?.type === "file" && item.uri?.value) { fileContents[item.uri.value] = item.content; } }); + + // Extract contents from code blocks in the message for paths that don't have content yet + if (userMessage) { + const messageContent = renderChatMessage(userMessage); + filePathsFromMessage.forEach((path) => { + // Only extract content if we don't already have it from context items + if (!fileContents[path]) { + const blockContent = extractContentFromCodeBlock(messageContent, path); + if (blockContent) { + fileContents[path] = blockContent; + } + } + }); + } + console.log("FILE CONTENTS", fileContents); // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, diff --git a/core/llm/utils/extractContentFromCodeBlocks.ts b/core/llm/utils/extractContentFromCodeBlocks.ts new file mode 100644 index 000000000..00abc49cf --- /dev/null +++ b/core/llm/utils/extractContentFromCodeBlocks.ts @@ -0,0 +1,29 @@ +/** + * Extracts content from code blocks with given path + * @param content The full message content + * @param path The file path to look for + * @returns The content of the code block if found, undefined otherwise + */ +export function extractContentFromCodeBlock( + content: string, + path: string +): string | undefined { + // Escape special characters in the path for regex + const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + + // Match the code block with this path + // This regex looks for: + // 1. Code block start with the path (```[language] path) + // 2. The content until the closing ``` + const regex = new RegExp( + `\`\`\`[^\\n]*${escapedPath}[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, + "m" + ); + + const match = content.match(regex); + if (match && match[1]) { + return match[1]; + } + + return undefined; +} \ No newline at end of file From 0f174fca79a876233f0f78fb180fee74a584cb40 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:30:00 -0700 Subject: [PATCH 60/95] improv: tests --- .../extractContentFromCodeBlocks.test.ts | 71 +++++++++++++++++++ .../llm/utils/extractContentFromCodeBlocks.ts | 18 +++-- 2 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 core/llm/utils/extractContentFromCodeBlocks.test.ts diff --git a/core/llm/utils/extractContentFromCodeBlocks.test.ts b/core/llm/utils/extractContentFromCodeBlocks.test.ts new file mode 100644 index 000000000..b6a612ed3 --- /dev/null +++ b/core/llm/utils/extractContentFromCodeBlocks.test.ts @@ -0,0 +1,71 @@ +import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks"; + +describe("extractContentFromCodeBlock", () => { + it("should extract content from code block with language and filepath", () => { + const content = "```typescript src/main.ts\nconst x = 1;\n```"; + expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe("const x = 1;"); + }); + + it("should extract content from code block with filepath only (no language)", () => { + const content = "```test.js\nclass Calculator { }\n```"; + expect(extractContentFromCodeBlock(content, "test.js")).toBe("class Calculator { }"); + }); + + it("should extract content from code block with line ranges", () => { + const content = "```js test.js (19-25)\nfunction test() {}\n```"; + expect(extractContentFromCodeBlock(content, "test.js")).toBe("function test() {}"); + }); + + it("should handle multiple code blocks and find the right one", () => { + const content = + "```typescript src/main.ts\nconst x = 1;\n```\n" + + "```test.js\nclass Calculator { }\n```\n" + + "```js utils.js (19-25)\nfunction test() {}\n```"; + + expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe("const x = 1;"); + expect(extractContentFromCodeBlock(content, "test.js")).toBe("class Calculator { }"); + expect(extractContentFromCodeBlock(content, "utils.js")).toBe("function test() {}"); + }); + + it("should handle paths with special regex characters", () => { + const content = "```typescript src/special+chars.ts[123]\nconst special = true;\n```"; + expect(extractContentFromCodeBlock(content, "src/special+chars.ts[123]")).toBe("const special = true;"); + }); + + it("should handle multiline content", () => { + const content = + "```typescript src/multi-line.ts\n" + + "function example() {\n" + + " const x = 1;\n" + + " return x + 2;\n" + + "}\n" + + "```"; + + const expected = + "function example() {\n" + + " const x = 1;\n" + + " return x + 2;\n" + + "}"; + + expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(expected); + }); + + it("should return undefined when path doesn't exist in any code block", () => { + const content = "```typescript src/main.ts\nconst x = 1;\n```"; + expect(extractContentFromCodeBlock(content, "nonexistent.ts")).toBeUndefined(); + }); + + it("should extract content when the path has directory structure", () => { + const content = "```js src/components/Button.jsx\nconst Button = () => ;\n```"; + expect(extractContentFromCodeBlock(content, "src/components/Button.jsx")).toBe("const Button = () => ;"); + }); + + it("should match exact paths only", () => { + const content = + "```typescript src/utils.ts\nconst util = {};\n```\n" + + "```typescript src/utils/index.ts\nconst index = {};\n```"; + + expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe("const util = {};"); + expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe("const index = {};"); + }); +}); \ No newline at end of file diff --git a/core/llm/utils/extractContentFromCodeBlocks.ts b/core/llm/utils/extractContentFromCodeBlocks.ts index 00abc49cf..c67ab2f7d 100644 --- a/core/llm/utils/extractContentFromCodeBlocks.ts +++ b/core/llm/utils/extractContentFromCodeBlocks.ts @@ -6,24 +6,28 @@ */ export function extractContentFromCodeBlock( content: string, - path: string + path: string, ): string | undefined { // Escape special characters in the path for regex const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - + // Match the code block with this path // This regex looks for: // 1. Code block start with the path (```[language] path) // 2. The content until the closing ``` + // The path can be: + // - With language: ```typescript src/main.ts + // - Without language: ```src/main.ts + // - With line ranges: ```js src/main.ts (1-10) const regex = new RegExp( - `\`\`\`[^\\n]*${escapedPath}[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, - "m" + `\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, + "m", ); - + const match = content.match(regex); if (match && match[1]) { return match[1]; } - + return undefined; -} \ No newline at end of file +} From 897f7130e0d4f17c75013f6eebdbe97b3a07b592 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:32:10 -0700 Subject: [PATCH 61/95] improv: clean up --- core/llm/rules/getSystemMessageWithRules.ts | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index bdfe0aa0a..c0ea95fef 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -64,13 +64,10 @@ const contentMatchesPatterns = ( fileContent: string, patterns: string | string[], ): boolean => { - console.log("HERE XXXXX"); - // Handle single string pattern if (typeof patterns === "string") { try { const regex = new RegExp(patterns); - console.log("REGEX", regex); return regex.test(fileContent); } catch (e) { console.error(`Invalid regex pattern: ${patterns}`, e); @@ -148,7 +145,6 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { return true; } - console.log("RULE", rule); // Root-level rules with no globs or patterns are implicitly global if ( isRootLevelRule(rule) && @@ -156,11 +152,9 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { !rule.patterns && rule.alwaysApply !== false ) { - console.log("IS ROOT"); return true; } - console.log("NOT ROOT"); return false; }; @@ -173,7 +167,6 @@ const checkGlobsAndPatterns = ({ filePaths: string[]; fileContents: Record; }) => { - console.log("HERE ZZZZ"); const matchingFiles = rule.globs ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs)) : filePaths; @@ -185,11 +178,9 @@ const checkGlobsAndPatterns = ({ // Now check for pattern matches in file contents if patterns are specified if (rule.patterns) { - console.log("HAS PATTERNS", rule.patterns); // Check if any of the matching files also match the content patterns return matchingFiles.some((filePath) => { const content = fileContents[filePath]; - console.log("TESTING FILE MATCH", content); // If we don't have the content, we can't check patterns if (!content) return false; return contentMatchesPatterns(content, rule.patterns!); @@ -216,7 +207,6 @@ export const shouldApplyRule = ( fileContents: Record = {}, rulePolicies: RulePolicies = {}, ): boolean => { - console.log("CHECKING SHOULD APPLY RULE", rule); const policy = rulePolicies[rule.name || ""]; // Never apply if policy is "off" @@ -325,8 +315,6 @@ export const getApplicableRules = ( }); } - console.log("FILE CONTENTS", fileContents); - // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, // and path matching in a consistent way const applicableRules = rules.filter((rule) => From 1bc7b78a1c093a579b8a737dd77e07a2401714d8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 09:39:04 -0700 Subject: [PATCH 62/95] fix: args --- core/llm/rules/getSystemMessageWithRules.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index c0ea95fef..62756923e 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -204,8 +204,8 @@ const checkGlobsAndPatterns = ({ export const shouldApplyRule = ( rule: RuleWithSource, filePaths: string[], - fileContents: Record = {}, rulePolicies: RulePolicies = {}, + fileContents: Record = {}, ): boolean => { const policy = rulePolicies[rule.name || ""]; @@ -318,7 +318,7 @@ export const getApplicableRules = ( // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, // and path matching in a consistent way const applicableRules = rules.filter((rule) => - shouldApplyRule(rule, allFilePaths, fileContents, rulePolicies), + shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents), ); return applicableRules; From 3ec3a870cddedcf704f88c2766b92c3547d21db2 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Jun 2025 10:56:47 -0700 Subject: [PATCH 63/95] Add MCP provider refresh for @mention dropdown submenu items --- core/core.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core/core.ts b/core/core.ts index a06ae8b78..9710a552a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -147,6 +147,18 @@ export class Core { MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => { void this.configHandler.reloadConfig(); + + // Refresh @mention dropdown submenu items for MCP providers + const mcpManager = MCPManagerSingleton.getInstance(); + const mcpProviderNames = Array.from(mcpManager.connections.keys()).map( + (mcpId) => `mcp-${mcpId}` + ); + + if (mcpProviderNames.length > 0) { + this.messenger.send("refreshSubmenuItems", { + providers: mcpProviderNames, + }); + } }; this.codeBaseIndexer = new CodebaseIndexer( From a251c1b6f641d22aeaaaacd1a827e8a129c268fc Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 11:22:32 -0700 Subject: [PATCH 64/95] test: pattern matching --- .../rules/getSystemMessageWithRules.vitest.ts | 237 +++++++++++++++++- 1 file changed, 235 insertions(+), 2 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index f652d3a77..8425c8324 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -1,6 +1,14 @@ import { describe, expect, it } from "vitest"; -import { RuleWithSource } from "../.."; -import { shouldApplyRule } from "./getSystemMessageWithRules"; +import { + ContextItemId, + ContextItemWithId, + RuleWithSource, + UserChatMessage, +} from "../.."; +import { + getApplicableRules, + shouldApplyRule, +} from "./getSystemMessageWithRules"; import { RulePolicies } from "./types"; describe("Rule colocation glob matching", () => { @@ -244,3 +252,228 @@ describe("Rule policies", () => { ).toBe(false); }); }); + +describe("Content pattern matching", () => { + it("should apply rules when file content matches pattern", () => { + // Rule with pattern to match React component files + const reactComponentRule: RuleWithSource = { + name: "React Component Rule", + rule: "Follow React component standards", + patterns: "export (function|const) \\w+.*\\(", + source: "rules-block", + ruleFile: "src/components/rules.md", + }; + + // File that matches the pattern + const filePath = "src/components/Button.tsx"; + const fileContents = { + [filePath]: + "export function Button() { return }", + }; + + expect( + shouldApplyRule(reactComponentRule, [filePath], {}, fileContents), + ).toBe(true); + + // File that doesn't match the pattern + const nonMatchingContents = { + [filePath]: + "import React from 'react'; // Just an import, not a component", + }; + + expect( + shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents), + ).toBe(false); + }); + + it("should support multiple regex patterns as an array", () => { + // Rule with multiple patterns + const multiPatternRule: RuleWithSource = { + name: "Multi-Pattern Rule", + rule: "Apply to functions or classes", + patterns: ["function\\s+\\w+", "class\\s+\\w+"], + source: "rules-block", + ruleFile: "src/utils/rules.md", + }; + + const filePath = "src/utils/helper.ts"; + + // Content with function - should match + const functionContent = { + [filePath]: "function formatDate(date) { return date.toISOString(); }", + }; + expect( + shouldApplyRule(multiPatternRule, [filePath], {}, functionContent), + ).toBe(true); + + // Content with class - should match + const classContent = { + [filePath]: + "class DateFormatter { format(date) { return date.toISOString(); } }", + }; + expect( + shouldApplyRule(multiPatternRule, [filePath], {}, classContent), + ).toBe(true); + + // Content with neither - should not match + const nonMatchingContent = { + [filePath]: "const PI = 3.14159;", + }; + expect( + shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent), + ).toBe(false); + }); + + it("should apply rules based on both globs and patterns when both are specified", () => { + // Rule with both glob and pattern restrictions + const typescriptClassRule: RuleWithSource = { + name: "TypeScript Class Rule", + rule: "Follow class standards in TypeScript", + globs: "**/*.ts", + patterns: "class\\s+\\w+", + source: "rules-block", + ruleFile: "src/models/rules.md", + }; + + const tsFilePath = "src/models/User.ts"; + const jsFilePath = "src/models/Product.js"; + + // TypeScript file with class - should match + const tsClassContent = { + [tsFilePath]: "export class User { constructor(public name: string) {} }", + }; + expect( + shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent), + ).toBe(true); + + // TypeScript file without class - should not match + const tsNonClassContent = { + [tsFilePath]: "export const createUser = (name: string) => ({ name });", + }; + expect( + shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent), + ).toBe(false); + + // JavaScript file with class - should not match due to glob + const jsClassContent = { + [jsFilePath]: + "export class Product { constructor(name) { this.name = name; } }", + }; + expect( + shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent), + ).toBe(false); + }); + + it("should extract file content from messages for pattern matching", () => { + // Rule with pattern + const arrowFunctionRule: RuleWithSource = { + name: "Arrow Function Rule", + rule: "Use arrow functions for better this binding", + patterns: "const\\s+\\w+\\s*=\\s*\\(", + source: "rules-block", + ruleFile: "src/utils/rules.md", + }; + + // Message with code block containing a matching pattern + const messageWithArrowFn: UserChatMessage = { + role: "user", + content: + "Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```", + }; + + // Create context item to match the file in the message + const contextItem: ContextItemWithId = { + id: { providerTitle: "file", itemId: "formatter" } as ContextItemId, + uri: { type: "file", value: "src/utils/formatter.ts" }, + content: "const format = (date) => {\n return date.toISOString();\n};", + name: "formatter.ts", + description: "Utility formatter", + }; + + // Should match the pattern + const applicableRules = getApplicableRules( + messageWithArrowFn, + [arrowFunctionRule], + [contextItem], + ); + + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Arrow Function Rule"); + + // Message with code block that doesn't match the pattern + const messageWithoutArrowFn: UserChatMessage = { + role: "user", + content: + "Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```", + }; + + // Context item with non-matching content + const nonMatchingContextItem: ContextItemWithId = { + id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId, + uri: { type: "file", value: "src/utils/formatter.ts" }, + content: "function format(date) {\n return date.toISOString();\n}", + name: "formatter.ts", + description: "Utility formatter", + }; + + // Should not match the pattern + const nonApplicableRules = getApplicableRules( + messageWithoutArrowFn, + [arrowFunctionRule], + [nonMatchingContextItem], + ); + + expect(nonApplicableRules).toHaveLength(0); + }); + + it("should handle invalid regex patterns gracefully", () => { + // Rule with invalid regex pattern + const invalidRegexRule: RuleWithSource = { + name: "Invalid Regex Rule", + rule: "This rule has an invalid regex pattern", + patterns: "([unclosed parenthesis", + source: "rules-block", + ruleFile: "src/utils/rules.md", + }; + + const filePath = "src/utils/helper.ts"; + const fileContents = { + [filePath]: "function helper() { return true; }", + }; + + // Should not throw an error but gracefully not apply the rule + expect( + shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents), + ).toBe(false); + }); + + it("should respect directory restrictions for pattern rules", () => { + // Rule with pattern in a nested directory + const nestedPatternRule: RuleWithSource = { + name: "Nested Pattern Rule", + rule: "Apply only to model files with interfaces", + patterns: "interface\\s+\\w+", + source: "rules-block", + ruleFile: "src/models/rules.md", + }; + + // File in the correct directory with matching content + const modelFilePath = "src/models/User.ts"; + const modelContents = { + [modelFilePath]: "export interface User { id: string; name: string; }", + }; + expect( + shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents), + ).toBe(true); + + // File outside the directory with matching content - should not match + const utilFilePath = "src/utils/types.ts"; + const utilContents = { + [utilFilePath]: + "export interface Config { apiUrl: string; timeout: number; }", + }; + expect( + shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents), + ).toBe(false); + }); +}); From 77989095ba5334b6a9aff4e44a1a08f94220505f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 20 Jun 2025 11:24:06 -0700 Subject: [PATCH 65/95] fix: formatting --- .../extractContentFromCodeBlocks.test.ts | 75 ++++++++++++------- .../e2e/actions/Autocomplete.actions.ts | 4 +- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/core/llm/utils/extractContentFromCodeBlocks.test.ts b/core/llm/utils/extractContentFromCodeBlocks.test.ts index b6a612ed3..47a814934 100644 --- a/core/llm/utils/extractContentFromCodeBlocks.test.ts +++ b/core/llm/utils/extractContentFromCodeBlocks.test.ts @@ -3,17 +3,23 @@ import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks"; describe("extractContentFromCodeBlock", () => { it("should extract content from code block with language and filepath", () => { const content = "```typescript src/main.ts\nconst x = 1;\n```"; - expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe("const x = 1;"); + expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe( + "const x = 1;", + ); }); it("should extract content from code block with filepath only (no language)", () => { const content = "```test.js\nclass Calculator { }\n```"; - expect(extractContentFromCodeBlock(content, "test.js")).toBe("class Calculator { }"); + expect(extractContentFromCodeBlock(content, "test.js")).toBe( + "class Calculator { }", + ); }); it("should extract content from code block with line ranges", () => { const content = "```js test.js (19-25)\nfunction test() {}\n```"; - expect(extractContentFromCodeBlock(content, "test.js")).toBe("function test() {}"); + expect(extractContentFromCodeBlock(content, "test.js")).toBe( + "function test() {}", + ); }); it("should handle multiple code blocks and find the right one", () => { @@ -21,51 +27,68 @@ describe("extractContentFromCodeBlock", () => { "```typescript src/main.ts\nconst x = 1;\n```\n" + "```test.js\nclass Calculator { }\n```\n" + "```js utils.js (19-25)\nfunction test() {}\n```"; - - expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe("const x = 1;"); - expect(extractContentFromCodeBlock(content, "test.js")).toBe("class Calculator { }"); - expect(extractContentFromCodeBlock(content, "utils.js")).toBe("function test() {}"); + + expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe( + "const x = 1;", + ); + expect(extractContentFromCodeBlock(content, "test.js")).toBe( + "class Calculator { }", + ); + expect(extractContentFromCodeBlock(content, "utils.js")).toBe( + "function test() {}", + ); }); it("should handle paths with special regex characters", () => { - const content = "```typescript src/special+chars.ts[123]\nconst special = true;\n```"; - expect(extractContentFromCodeBlock(content, "src/special+chars.ts[123]")).toBe("const special = true;"); + const content = + "```typescript src/special+chars.ts[123]\nconst special = true;\n```"; + expect( + extractContentFromCodeBlock(content, "src/special+chars.ts[123]"), + ).toBe("const special = true;"); }); it("should handle multiline content", () => { - const content = + const content = "```typescript src/multi-line.ts\n" + "function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}\n" + "```"; - - const expected = - "function example() {\n" + - " const x = 1;\n" + - " return x + 2;\n" + - "}"; - - expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(expected); + + const expected = + "function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}"; + + expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe( + expected, + ); }); it("should return undefined when path doesn't exist in any code block", () => { const content = "```typescript src/main.ts\nconst x = 1;\n```"; - expect(extractContentFromCodeBlock(content, "nonexistent.ts")).toBeUndefined(); + expect( + extractContentFromCodeBlock(content, "nonexistent.ts"), + ).toBeUndefined(); }); it("should extract content when the path has directory structure", () => { - const content = "```js src/components/Button.jsx\nconst Button = () => ;\n```"; - expect(extractContentFromCodeBlock(content, "src/components/Button.jsx")).toBe("const Button = () => ;"); + const content = + "```js src/components/Button.jsx\nconst Button = () => ;\n```"; + expect( + extractContentFromCodeBlock(content, "src/components/Button.jsx"), + ).toBe("const Button = () => ;"); }); it("should match exact paths only", () => { - const content = + const content = "```typescript src/utils.ts\nconst util = {};\n```\n" + "```typescript src/utils/index.ts\nconst index = {};\n```"; - - expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe("const util = {};"); - expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe("const index = {};"); + + expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe( + "const util = {};", + ); + expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe( + "const index = {};", + ); }); -}); \ No newline at end of file +}); diff --git a/extensions/vscode/e2e/actions/Autocomplete.actions.ts b/extensions/vscode/e2e/actions/Autocomplete.actions.ts index 9e91355fd..29902e4f2 100644 --- a/extensions/vscode/e2e/actions/Autocomplete.actions.ts +++ b/extensions/vscode/e2e/actions/Autocomplete.actions.ts @@ -30,14 +30,14 @@ export class AutocompleteActions { expect(ghostText1).to.equal(messagePair1.llmResponse); } - public static async forceCompletion(editor: TextEditor): Promise { + public static async forceCompletion(editor: TextEditor): Promise { await editor.setText("def main():\n "); await editor.moveCursor(2, 5); await new Workbench().executeCommand("Continue: Force Autocomplete"); const ghostText = await TestUtils.waitForSuccess(() => - AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver) + AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver), ); return ghostText; From 8b6d1ff9a3e75087dedada70a63026efeb3b8164 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Jun 2025 11:26:26 -0700 Subject: [PATCH 66/95] Handle empty query by sending "null" instead of empty string in MCP context provider --- core/context/providers/MCPContextProvider.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index 6465d6b63..0336c2ec3 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -56,7 +56,9 @@ class MCPContextProvider extends BaseContextProvider { private insertInputToUriTemplate(uri: string, query: string): string { const TEMPLATE_VAR = "query"; if (uri.includes(`{${TEMPLATE_VAR}}`)) { - return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query)); + // Sending an empty string will result in an error, so we instead send "null" + const queryOrNull = query.trim() === "" ? "null" : query; + return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(queryOrNull)); } return uri; } From d10bfca67d0682b6f6d6fae6f577d6140b3bb5e9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Jun 2025 12:01:17 -0700 Subject: [PATCH 67/95] fix broken import --- .../components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx index 57ee2740a..02f404b54 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx @@ -1,7 +1,7 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch } from "../../../../redux/hooks"; -import { cancelStream } from "../../../../redux/thunks"; +import { cancelStream } from "../../../../redux/thunks/cancelStream"; import { getAltKeyLabel, getMetaKeyLabel } from "../../../../util"; import { Container, StopButton } from "./components"; import { GeneratingIndicator } from "./GeneratingIndicator"; From d000fb07982ee4878eb2336b623b57ffe651265c Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 20 Jun 2025 12:05:05 -0700 Subject: [PATCH 68/95] Delete gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx --- .../sections/rules/RulesSectionTooltip.tsx | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx diff --git a/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx b/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx deleted file mode 100644 index f5da60c54..000000000 --- a/gui/src/components/mainInput/Lump/sections/rules/RulesSectionTooltip.tsx +++ /dev/null @@ -1,20 +0,0 @@ -export const RulesSectionTooltip = () => ( -
-

- Rules allow you to control how coding - standards and preferences are applied. -

-
    -
  • - Always: Rule will always be applied, regardless of - context -
  • -
  • - Auto: Rule will be applied based on file matching -
  • -
  • - Never: Rule will never be applied -
  • -
-
-); From e235a3092c449cd1841c8c4bc730c3e738be8b24 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Jun 2025 13:42:04 -0700 Subject: [PATCH 69/95] fix azure url query params --- packages/openai-adapters/src/apis/Azure.ts | 29 ++++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/openai-adapters/src/apis/Azure.ts b/packages/openai-adapters/src/apis/Azure.ts index bf9a5ae4d..bbff66592 100644 --- a/packages/openai-adapters/src/apis/Azure.ts +++ b/packages/openai-adapters/src/apis/Azure.ts @@ -16,10 +16,13 @@ export class AzureApi extends OpenAIApi { provider: "openai", }); + const { baseURL, defaultQuery } = this._getAzureBaseURL(azureConfig); + this.openai = new OpenAI({ apiKey: azureConfig.apiKey, - baseURL: this._getAzureBaseURL(azureConfig), + baseURL, fetch: customFetch(azureConfig.requestOptions), + defaultQuery, }); } @@ -32,8 +35,20 @@ export class AzureApi extends OpenAIApi { return apiType === "azure-openai" || apiType === "azure"; } - private _getAzureBaseURL(config: z.infer): string { - const baseURL = new URL(this.apiBase).toString().replace(/\/$/, ""); + private _getAzureBaseURL(config: z.infer): { + baseURL: string; + defaultQuery: Record; + } { + const url = new URL(this.apiBase); + + // Copy search params to separate object for OpenAI + const queryParams: Record = {}; + for (const [key, value] of url.searchParams.entries()) { + queryParams[key] = value; + } + + url.pathname = url.pathname.replace(/\/$/, ""); // Remove trailing slash if present + url.search = ""; // Clear original search params // Default is `azure-openai` in docs, but previously was `azure` if (this._isAzureOpenAI(config.env?.apiType)) { @@ -48,11 +63,15 @@ export class AzureApi extends OpenAIApi { "`env.apiVersion` is a required configuration property for Azure OpenAI", ); } + url.pathname = `${url.pathname}/openai/deployments/${config.env.deployment}`; - return `${baseURL}/openai/deployments/${config.env.deployment}?api-version=${config.env.apiVersion}`; + queryParams["api-version"] = config.env.apiVersion; } - return baseURL; + return { + baseURL: url.toString(), + defaultQuery: queryParams, + }; } /** From 937d553bce1e9a529507b20bf4faf0e281552102 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Jun 2025 14:25:05 -0700 Subject: [PATCH 70/95] add imports back for components/x level files --- gui/src/App.tsx | 2 +- .../ConversationStarterCards.tsx | 2 +- .../components/ConversationStarters/index.ts | 1 + gui/src/components/Layout.tsx | 10 ++++++---- gui/src/components/ModeSelect/ModeSelect.tsx | 9 ++------- gui/src/components/ModeSelect/index.ts | 1 + .../OnboardingCard/hooks/useOnboardingCard.ts | 2 +- gui/src/components/OnboardingCard/index.ts | 8 ++++++++ .../components/mainInput/ContinueInputBox.tsx | 2 +- gui/src/components/mainInput/InputToolbar.tsx | 2 +- .../Lump/LumpToolbar/EditOutcomeToolbar.tsx | 2 +- .../mainInput/Lump/sections/PromptsSection.tsx | 2 +- .../mainInput/TipTapEditor/extensions/index.ts | 4 ++++ .../components/mainInput/TipTapEditor/index.ts | 3 +++ .../useMainEditorWebviewListeners.ts | 3 +-- .../TipTapEditor/utils/editorConfig.ts | 5 +---- .../TipTapEditor/utils/getSuggestion.ts | 2 +- .../utils/insertCurrentFileContextMention.ts | 2 +- .../TipTapEditor/utils/resolveEditorContent.ts | 4 +--- .../mainInput/util/handleMetaKeyIssues.ts | 2 +- .../modelSelection/ModelSelectionListbox.tsx | 4 ++-- .../modelSelection/platform/AssistantSelect.tsx | 17 ++++++++--------- .../modelSelection/platform/FreeTrialButton.tsx | 3 +-- gui/src/components/ui/index.ts | 10 ++++++++++ gui/src/hooks/ParallelListeners.tsx | 3 --- gui/src/pages/config/AccountButton.tsx | 6 +++--- gui/src/pages/config/ConfigItemSelect.tsx | 4 ++-- gui/src/pages/config/ModelRoleSelector.tsx | 4 ++-- gui/src/pages/gui/Chat.tsx | 4 ++-- gui/src/pages/gui/EmptyChatBody.tsx | 4 ++-- gui/src/pages/gui/StreamError.tsx | 2 +- gui/src/redux/slices/uiSlice.ts | 6 ++++-- gui/src/redux/thunks/edit.ts | 2 +- gui/src/redux/thunks/gatherContext.ts | 2 +- gui/src/redux/thunks/updateFileSymbols.ts | 2 +- gui/src/util/localStorage.ts | 2 +- gui/src/util/test/render.tsx | 2 +- 37 files changed, 80 insertions(+), 65 deletions(-) create mode 100644 gui/src/components/ConversationStarters/index.ts create mode 100644 gui/src/components/ModeSelect/index.ts create mode 100644 gui/src/components/OnboardingCard/index.ts create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/index.ts create mode 100644 gui/src/components/mainInput/TipTapEditor/index.ts create mode 100644 gui/src/components/ui/index.ts diff --git a/gui/src/App.tsx b/gui/src/App.tsx index e6f770eb3..6fc120707 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,6 +1,6 @@ import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; -import { MainEditorProvider } from "./components/mainInput/TipTapEditor/MainEditorProvider"; +import { MainEditorProvider } from "./components/mainInput/TipTapEditor"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import ParallelListeners from "./hooks/ParallelListeners"; diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 9ac9bcf91..776c0721b 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -2,7 +2,7 @@ import { SlashCommandDescription } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { useMainEditor } from "../mainInput/TipTapEditor/MainEditorProvider"; +import { useMainEditor } from "../mainInput/TipTapEditor"; import { ConversationStarterCard } from "./ConversationStarterCard"; const NUM_CARDS_TO_RENDER = 5; diff --git a/gui/src/components/ConversationStarters/index.ts b/gui/src/components/ConversationStarters/index.ts new file mode 100644 index 000000000..c7a6af018 --- /dev/null +++ b/gui/src/components/ConversationStarters/index.ts @@ -0,0 +1 @@ +export { ConversationStarterCards } from "./ConversationStarterCards"; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 4dd3239e8..1e2134e7a 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -19,10 +19,12 @@ import { FatalErrorIndicator } from "./config/FatalErrorNotice"; import TextDialog from "./dialogs"; import Footer from "./Footer"; import { LumpProvider } from "./mainInput/Lump/LumpContext"; -import { useMainEditor } from "./mainInput/TipTapEditor/MainEditorProvider"; -import { useOnboardingCard } from "./OnboardingCard/hooks/useOnboardingCard"; -import { OnboardingCard } from "./OnboardingCard/OnboardingCard"; -import { isNewUserOnboarding } from "./OnboardingCard/utils"; +import { useMainEditor } from "./mainInput/TipTapEditor"; +import { + isNewUserOnboarding, + OnboardingCard, + useOnboardingCard, +} from "./OnboardingCard"; import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index dec1b1e81..a5792d721 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -6,13 +6,8 @@ import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; import { getFontSize, getMetaKeyLabel } from "../../util"; -import { useMainEditor } from "../mainInput/TipTapEditor/MainEditorProvider"; -import { - Listbox, - ListboxButton, - ListboxOption, - ListboxOptions, -} from "../ui/Listbox"; +import { useMainEditor } from "../mainInput/TipTapEditor"; +import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; import { ModeIcon } from "./ModeIcon"; export function ModeSelect() { diff --git a/gui/src/components/ModeSelect/index.ts b/gui/src/components/ModeSelect/index.ts new file mode 100644 index 000000000..82bc8634a --- /dev/null +++ b/gui/src/components/ModeSelect/index.ts @@ -0,0 +1 @@ +export { ModeSelect } from "./ModeSelect"; diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index 34b7f4225..94a7fb7a8 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,5 +1,6 @@ import { OnboardingModes } from "core/protocol/core"; import { useNavigate } from "react-router-dom"; +import { OnboardingCardState } from ".."; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { setDialogMessage, @@ -7,7 +8,6 @@ import { setShowDialog, } from "../../../redux/slices/uiSlice"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; -import { OnboardingCardState } from "../OnboardingCard"; export interface UseOnboardingCard { show: OnboardingCardState["show"]; diff --git a/gui/src/components/OnboardingCard/index.ts b/gui/src/components/OnboardingCard/index.ts new file mode 100644 index 000000000..d3db336fe --- /dev/null +++ b/gui/src/components/OnboardingCard/index.ts @@ -0,0 +1,8 @@ +export { useOnboardingCard } from "./hooks/useOnboardingCard"; +export { useSubmitOnboarding } from "./hooks/useSubmitOnboarding"; +export { OnboardingCard, type OnboardingCardState } from "./OnboardingCard"; +export { + defaultOnboardingCardState, + isNewUserOnboarding, + type OnboardingStatus, +} from "./utils"; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 8ee50bc07..b50edfdbb 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -9,7 +9,7 @@ import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; import { RulesPeek } from "./belowMainInput/RulesPeek"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; -import { TipTapEditor } from "./TipTapEditor/TipTapEditor"; +import { TipTapEditor } from "./TipTapEditor"; interface ContinueInputBoxProps { isLastUserInput: boolean; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 7cff5fc7c..23d242ae2 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -14,7 +14,7 @@ import { exitEdit } from "../../redux/thunks/edit"; import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; -import { ModeSelect } from "../ModeSelect/ModeSelect"; +import { ModeSelect } from "../ModeSelect"; import { useFontSize } from "../ui/font"; import { EnterButton } from "./InputToolbar/EnterButton"; import HoverItem from "./InputToolbar/HoverItem"; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx index 832383f10..dc3779d22 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx @@ -3,7 +3,7 @@ import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { exitEdit } from "../../../../redux/thunks/edit"; import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons"; -import { useMainEditor } from "../../TipTapEditor/MainEditorProvider"; +import { useMainEditor } from "../../TipTapEditor"; export function EditOutcomeToolbar() { const dispatch = useAppDispatch(); diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index b057d68e7..d7fd74eee 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -11,7 +11,7 @@ import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands"; import { useAppSelector } from "../../../../redux/hooks"; import { fontSize } from "../../../../util"; -import { useMainEditor } from "../../TipTapEditor/MainEditorProvider"; +import { useMainEditor } from "../../TipTapEditor"; import { useLump } from "../LumpContext"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts new file mode 100644 index 000000000..77eae41bf --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -0,0 +1,4 @@ +export { CodeBlock } from "./CodeBlock/CodeBlock"; +export { Mention } from "./Mention"; +export { PromptBlock } from "./Prompt/PromptBlock"; +export { SlashCommand } from "./SlashCommand"; diff --git a/gui/src/components/mainInput/TipTapEditor/index.ts b/gui/src/components/mainInput/TipTapEditor/index.ts new file mode 100644 index 000000000..81aff8cae --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/index.ts @@ -0,0 +1,3 @@ +export { useMainEditor } from "./MainEditorProvider"; +export { TipTapEditor } from "./TipTapEditor"; +export { resolveEditorContent } from "./utils/resolveEditorContent"; diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index b73d12e73..0fe79297c 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -8,8 +8,7 @@ import { clearCodeToEdit } from "../../../redux/slices/editState"; import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { CodeBlock } from "./extensions/CodeBlock/CodeBlock"; -import { PromptBlock } from "./extensions/Prompt/PromptBlock"; +import { CodeBlock, PromptBlock } from "./extensions"; import { insertCurrentFileContextMention } from "./utils/insertCurrentFileContextMention"; /** diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 3ae001058..a759a5485 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -21,10 +21,7 @@ import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; import { AppDispatch } from "../../../../redux/store"; import { exitEdit } from "../../../../redux/thunks/edit"; import { getFontSize, isJetBrains } from "../../../../util"; -import { CodeBlock } from "../extensions/CodeBlock/CodeBlock"; -import { Mention } from "../extensions/Mention"; -import { PromptBlock } from "../extensions/Prompt/PromptBlock"; -import { SlashCommand } from "../extensions/SlashCommand"; +import { CodeBlock, Mention, PromptBlock, SlashCommand } from "../extensions"; import { TipTapEditorProps } from "../TipTapEditor"; import { getContextProviderDropdownOptions, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index 87175f317..8c0613a4a 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -11,7 +11,7 @@ import { AppDispatch } from "../../../../redux/store"; import AtMentionDropdown from "../../AtMentionDropdown"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; import { TIPPY_DIV_ID } from "../TipTapEditor"; -import { SlashCommand } from "../extensions/SlashCommand"; +import { SlashCommand } from "../extensions"; function getSuggestion( items: (props: { query: string }) => Promise, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts b/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts index 6f5398455..5f5284d52 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/insertCurrentFileContextMention.ts @@ -1,6 +1,6 @@ import { Editor } from "@tiptap/core"; import { ContextProviderDescription } from "core"; -import { Mention } from "../extensions/Mention"; +import { Mention } from "../extensions"; /** * inserts the current file context as a removable mention in the editor area diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index 8d1b402eb..958ea2331 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -18,9 +18,7 @@ import { renderChatMessage, stripImages } from "core/util/messageContent"; import { getUriFileExtension } from "core/util/uri"; import { IIdeMessenger } from "../../../../context/IdeMessenger"; import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; -import { CodeBlock } from "../extensions/CodeBlock/CodeBlock"; -import { Mention } from "../extensions/Mention"; -import { PromptBlock } from "../extensions/Prompt/PromptBlock"; +import { CodeBlock, Mention, PromptBlock } from "../extensions"; interface MentionAttrs { label: string; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 2ca436425..bc45d19f1 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,7 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; -import { CodeBlock } from "../TipTapEditor/extensions/CodeBlock/CodeBlock"; +import { CodeBlock } from "../TipTapEditor"; const isWebEnv = isWebEnvironment(); diff --git a/gui/src/components/modelSelection/ModelSelectionListbox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx index 041d6c9a5..04510b6bb 100644 --- a/gui/src/components/modelSelection/ModelSelectionListbox.tsx +++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx @@ -9,8 +9,8 @@ import { ListboxButton, ListboxOption, ListboxOptions, -} from "../../components/ui/Listbox"; -import { Transition } from "../../components/ui/Transition"; + Transition, +} from "../../components/ui"; import { DisplayInfo } from "../../pages/AddNewModel/configs/models"; interface ModelSelectionListboxProps { diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 21e62ed10..d360abce4 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -7,7 +7,9 @@ import { ExclamationTriangleIcon, PlusIcon, } from "@heroicons/react/24/outline"; +import type { ProfileDescription } from "core/config/ConfigHandler"; import { useContext, useEffect, useMemo, useRef, useState } from "react"; +import { useNavigate } from "react-router-dom"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; @@ -22,20 +24,17 @@ import { isLocalProfile, isMetaEquivalentKeyPressed, } from "../../../util"; +import { cn } from "../../../util/cn"; +import { ROUTES } from "../../../util/navigation"; +import { useLump } from "../../mainInput/Lump/LumpContext"; import { Listbox, ListboxButton, ListboxOption, ListboxOptions, -} from "../../ui/Listbox"; -import { Transition } from "../../ui/Transition"; - -import type { ProfileDescription } from "core/config/ConfigHandler"; -import { useNavigate } from "react-router-dom"; -import { cn } from "../../../util/cn"; -import { ROUTES } from "../../../util/navigation"; -import { useLump } from "../../mainInput/Lump/LumpContext"; -import { useFontSize } from "../../ui/font"; + Transition, + useFontSize, +} from "../../ui"; import AssistantIcon from "./AssistantIcon"; interface AssistantSelectOptionProps { profile: ProfileDescription; diff --git a/gui/src/components/modelSelection/platform/FreeTrialButton.tsx b/gui/src/components/modelSelection/platform/FreeTrialButton.tsx index 0ff4fb1dc..c34d0abce 100644 --- a/gui/src/components/modelSelection/platform/FreeTrialButton.tsx +++ b/gui/src/components/modelSelection/platform/FreeTrialButton.tsx @@ -4,8 +4,7 @@ import { useContext } from "react"; import { Button, SecondaryButton, vscButtonBackground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { fontSize } from "../../../util"; -import { Listbox, ListboxButton, ListboxOptions } from "../../ui/Listbox"; -import { Transition } from "../../ui/Transition"; +import { Listbox, ListboxButton, ListboxOptions, Transition } from "../../ui"; import { useFontSize } from "../../ui/font"; interface ProgressBarProps { diff --git a/gui/src/components/ui/index.ts b/gui/src/components/ui/index.ts new file mode 100644 index 000000000..bb4987608 --- /dev/null +++ b/gui/src/components/ui/index.ts @@ -0,0 +1,10 @@ +export { Button } from "./Button"; +export { useFontSize } from "./font"; +export { + Listbox, + ListboxButton, + ListboxOption, + ListboxOptions, +} from "./Listbox"; +export { Popover, PopoverButton, PopoverPanel } from "./Popover"; +export { Transition } from "./Transition"; diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 2c37a90e2..a283ed969 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -3,7 +3,6 @@ import { IdeMessengerContext } from "../context/IdeMessenger"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { FromCoreProtocol } from "core/protocol"; -import { useMainEditor } from "../components/mainInput/TipTapEditor/MainEditorProvider"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; import { setConfigResult } from "../redux/slices/configSlice"; @@ -54,8 +53,6 @@ function ParallelListeners() { selectCurrentToolCallApplyState, ); - const { mainEditor } = useMainEditor(); - const handleConfigUpdate = useCallback( async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => { const { diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 7c94827f7..888488208 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,12 +1,12 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; import { isOnPremSession } from "core/control-plane/AuthTypes"; -import { Button } from "../../components/ui/Button"; import { + Button, Popover, PopoverButton, PopoverPanel, -} from "../../components/ui/Popover"; -import { Transition } from "../../components/ui/Transition"; + Transition, +} from "../../components/ui"; import { useAuth } from "../../context/Auth"; import { useAppSelector } from "../../redux/hooks"; import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; diff --git a/gui/src/pages/config/ConfigItemSelect.tsx b/gui/src/pages/config/ConfigItemSelect.tsx index 882477382..320ea8cf7 100644 --- a/gui/src/pages/config/ConfigItemSelect.tsx +++ b/gui/src/pages/config/ConfigItemSelect.tsx @@ -16,8 +16,8 @@ import { Popover, PopoverButton, PopoverPanel, -} from "../../components/ui/Popover"; -import { Transition } from "../../components/ui/Transition"; + Transition, +} from "../../components/ui"; import { fontSize } from "../../util"; export function ConfigItemSelect({ diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index ea2b33f29..0065552a8 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -15,8 +15,8 @@ import { ListboxButton, ListboxOption, ListboxOptions, -} from "../../components/ui/Listbox"; -import { Transition } from "../../components/ui/Transition"; + Transition, +} from "../../components/ui"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { fontSize } from "../../util"; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index a771460c1..be03ed0a9 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -23,7 +23,7 @@ import TimelineItem from "../../components/gui/TimelineItem"; import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import { useOnboardingCard } from "../../components/OnboardingCard/hooks/useOnboardingCard"; +import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; import { TabBar } from "../../components/TabBar/TabBar"; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -42,10 +42,10 @@ import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiSlice"; +import { streamResponseThunk } from "../../redux/thunks"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; -import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; diff --git a/gui/src/pages/gui/EmptyChatBody.tsx b/gui/src/pages/gui/EmptyChatBody.tsx index f094c42ef..54185f597 100644 --- a/gui/src/pages/gui/EmptyChatBody.tsx +++ b/gui/src/pages/gui/EmptyChatBody.tsx @@ -1,6 +1,6 @@ -import { ConversationStarterCards } from "../../components/ConversationStarters/ConversationStarterCards"; +import { ConversationStarterCards } from "../../components/ConversationStarters"; import { ExploreHubCard } from "../../components/ExploreHubCard"; -import { OnboardingCard } from "../../components/OnboardingCard/OnboardingCard"; +import { OnboardingCard } from "../../components/OnboardingCard"; export interface EmptyChatBodyProps { showOnboardingCard?: boolean; diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index f3654993a..356f8f9b3 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -8,7 +8,7 @@ import { import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; import { useContext, useMemo } from "react"; import { GhostButton, SecondaryButton } from "../../components"; -import { useMainEditor } from "../../components/mainInput/TipTapEditor/MainEditorProvider"; +import { useMainEditor } from "../../components/mainInput/TipTapEditor"; import { DiscordIcon } from "../../components/svg/DiscordIcon"; import { GithubIcon } from "../../components/svg/GithubIcon"; import ToggleDiv from "../../components/ToggleDiv"; diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 5ac5d6306..15d6216a4 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -1,8 +1,10 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { RuleWithSource, Tool } from "core"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn"; -import { OnboardingCardState } from "../../components/OnboardingCard/OnboardingCard"; -import { defaultOnboardingCardState } from "../../components/OnboardingCard/utils"; +import { + defaultOnboardingCardState, + OnboardingCardState, +} from "../../components/OnboardingCard"; import { getLocalStorage, LocalStorageKey } from "../../util/localStorage"; export type ToolPolicy = diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts index 753d47466..4471cc0b4 100644 --- a/gui/src/redux/thunks/edit.ts +++ b/gui/src/redux/thunks/edit.ts @@ -6,7 +6,7 @@ import { SetCodeToEditPayload, } from "core"; import { stripImages } from "core/util/messageContent"; -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; import { clearCodeToEdit, INITIAL_EDIT_APPLY_STATE, diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 763429eb8..1078b9589 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -8,7 +8,7 @@ import { SlashCommandDescription, } from "core"; import * as URI from "uri-js"; -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { selectSelectedChatModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts index 68000145e..49e259421 100644 --- a/gui/src/redux/thunks/updateFileSymbols.ts +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -1,6 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatHistoryItem, ContextItemWithId } from "core"; -import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock"; +import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions"; import { updateFileSymbols } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index b52bf42bc..a560aaf22 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -1,5 +1,5 @@ import { JSONContent } from "@tiptap/react"; -import { OnboardingStatus } from "../components/OnboardingCard/utils"; +import { OnboardingStatus } from "../components/OnboardingCard"; type LocalStorageTypes = { isExploreDialogOpen: boolean; diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 0354377a6..0ca3c7e3c 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -5,7 +5,7 @@ import { PropsWithChildren } from "react"; import { Provider } from "react-redux"; import { MemoryRouter, RouterProps } from "react-router-dom"; import { LumpProvider } from "../../components/mainInput/Lump/LumpContext"; -import { MainEditorProvider } from "../../components/mainInput/TipTapEditor/MainEditorProvider"; +import { MainEditorProvider } from "../../components/mainInput/TipTapEditor"; import { AuthProvider } from "../../context/Auth"; import { IdeMessengerProvider } from "../../context/IdeMessenger"; import { MockIdeMessenger } from "../../context/MockIdeMessenger"; From 0701f1b761b2cbd0fb548b865e952b25d84cdc62 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Jun 2025 14:26:45 -0700 Subject: [PATCH 71/95] fix import errors --- gui/src/components/mainInput/TipTapEditor/index.ts | 2 +- gui/src/components/mainInput/util/handleMetaKeyIssues.ts | 2 +- gui/src/pages/gui/Chat.tsx | 2 +- gui/src/redux/thunks/gatherContext.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor/index.ts b/gui/src/components/mainInput/TipTapEditor/index.ts index 81aff8cae..613076b8b 100644 --- a/gui/src/components/mainInput/TipTapEditor/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/index.ts @@ -1,3 +1,3 @@ -export { useMainEditor } from "./MainEditorProvider"; +export { MainEditorProvider, useMainEditor } from "./MainEditorProvider"; export { TipTapEditor } from "./TipTapEditor"; export { resolveEditorContent } from "./utils/resolveEditorContent"; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index bc45d19f1..b56ec7a4a 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,7 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; -import { CodeBlock } from "../TipTapEditor"; +import { CodeBlock } from "../TipTapEditor/extensions"; const isWebEnv = isWebEnvironment(); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index be03ed0a9..4a6d33849 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -42,10 +42,10 @@ import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiSlice"; -import { streamResponseThunk } from "../../redux/thunks"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; +import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 1078b9589..8b72b5f88 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -8,7 +8,7 @@ import { SlashCommandDescription, } from "core"; import * as URI from "uri-js"; -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; import { selectSelectedChatModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; From d4274510f031216252cdae166ea157a16c8890d3 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Jun 2025 16:50:16 -0700 Subject: [PATCH 72/95] hot reloading for .continue/rules files --- core/core.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index a06ae8b78..d4875c50c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -892,7 +892,9 @@ export class Core { uri.endsWith(".prompt") || uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || (uri.includes(".continue") && uri.endsWith(".yaml")) || - uri.endsWith(RULES_MARKDOWN_FILENAME) + uri.endsWith(RULES_MARKDOWN_FILENAME) || + uri.includes(".continue/rules") || + uri.includes(".continue\\rules") ) { await this.configHandler.reloadConfig(); } else if ( From e4dcc2cf099ef0dd3c3015bbaf91daadc91a150c Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 20 Jun 2025 16:52:05 -0700 Subject: [PATCH 73/95] Update package.json --- packages/openai-adapters/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 2b5043cfb..d775bb0b3 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.38", + "version": "1.0.39", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From 8f27a84bc1642d1d4870ae3354034c4ace2a1599 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Jun 2025 16:53:59 -0700 Subject: [PATCH 74/95] fix prettier and complexity errors --- core/core.ts | 87 +++++++++++++++++++++++++++------------------------- 1 file changed, 46 insertions(+), 41 deletions(-) diff --git a/core/core.ts b/core/core.ts index 9710a552a..8665ed297 100644 --- a/core/core.ts +++ b/core/core.ts @@ -42,6 +42,7 @@ import { IdeSettings, ModelDescription, RangeInFile, + ToolCall, type ContextItem, type ContextItemId, type IDE, @@ -147,13 +148,13 @@ export class Core { MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => { void this.configHandler.reloadConfig(); - + // Refresh @mention dropdown submenu items for MCP providers const mcpManager = MCPManagerSingleton.getInstance(); const mcpProviderNames = Array.from(mcpManager.connections.keys()).map( - (mcpId) => `mcp-${mcpId}` + (mcpId) => `mcp-${mcpId}`, ); - + if (mcpProviderNames.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: mcpProviderNames, @@ -755,44 +756,9 @@ export class Core { return { url }; }); - on("tools/call", async ({ data: { toolCall } }) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } - - const tool = config.tools.find( - (t) => t.function.name === toolCall.function.name, - ); - - if (!tool) { - throw new Error(`Tool ${toolCall.function.name} not found`); - } - - if (!config.selectedModelByRole.chat) { - throw new Error("No chat model selected"); - } - - // Define a callback for streaming output updates - const onPartialOutput = (params: { - toolCallId: string; - contextItems: ContextItem[]; - }) => { - this.messenger.send("toolCallPartialOutput", params); - }; - - return await callTool(tool, toolCall, { - config, - ide: this.ide, - llm: config.selectedModelByRole.chat, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - toolCallId: toolCall.id, - onPartialOutput, - codeBaseIndexer: this.codeBaseIndexer, - }); - }); + on("tools/call", async ({ data: { toolCall } }) => + this.handleToolCall(toolCall), + ); on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); @@ -817,6 +783,45 @@ export class Core { }); } + private async handleToolCall(toolCall: ToolCall) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + const tool = config.tools.find( + (t) => t.function.name === toolCall.function.name, + ); + + if (!tool) { + throw new Error(`Tool ${toolCall.function.name} not found`); + } + + if (!config.selectedModelByRole.chat) { + throw new Error("No chat model selected"); + } + + // Define a callback for streaming output updates + const onPartialOutput = (params: { + toolCallId: string; + contextItems: ContextItem[]; + }) => { + this.messenger.send("toolCallPartialOutput", params); + }; + + return await callTool(tool, toolCall, { + config, + ide: this.ide, + llm: config.selectedModelByRole.chat, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + tool, + toolCallId: toolCall.id, + onPartialOutput, + codeBaseIndexer: this.codeBaseIndexer, + }); + } + private async isItemTooBig(item: ContextItemWithId) { const { config } = await this.configHandler.loadConfig(); if (!config) { From c39ee8999eb6a6a80c0c027fac52c09c33f17768 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Jun 2025 16:59:30 -0700 Subject: [PATCH 75/95] Update createRuleBlock tool description for clarity --- core/tools/definitions/createRuleBlock.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index ace3bc6b2..0ae12cbc2 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -13,7 +13,7 @@ export const createRuleBlock: Tool = { function: { name: BuiltInToolNames.CreateRuleBlock, description: - "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.", + 'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.', parameters: { type: "object", required: ["name", "rule", "alwaysApply", "description"], From 497597a9243d32a39727851dc8def97e937852b0 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Jun 2025 17:01:38 -0700 Subject: [PATCH 76/95] hot reload for all block types --- core/core.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/core/core.ts b/core/core.ts index d4875c50c..7cecd03ec 100644 --- a/core/core.ts +++ b/core/core.ts @@ -47,7 +47,7 @@ import { type IDE, } from "."; -import { ConfigYaml } from "@continuedev/config-yaml"; +import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; import { @@ -893,8 +893,11 @@ export class Core { uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || (uri.includes(".continue") && uri.endsWith(".yaml")) || uri.endsWith(RULES_MARKDOWN_FILENAME) || - uri.includes(".continue/rules") || - uri.includes(".continue\\rules") + BLOCK_TYPES.some( + (blockType) => + uri.includes(`.continue/${blockType}`) || + uri.includes(`.continue\\${blockType}`), + ) ) { await this.configHandler.reloadConfig(); } else if ( From 81c20c11dbbce2eccefd00364c5b74b298b2f24f Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Thu, 12 Jun 2025 22:13:39 -0700 Subject: [PATCH 77/95] fix: :bug: Add requestOptions to YAML config for mcp --- packages/config-yaml/src/schemas/index.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 224278cd7..80749d34f 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,7 +1,11 @@ import * as z from "zod"; import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; -import { modelSchema, partialModelSchema } from "./models.js"; +import { + modelSchema, + partialModelSchema, + requestOptionsSchema, +} from "./models.js"; export const contextSchema = z.object({ name: z.string().optional(), @@ -19,6 +23,7 @@ const mcpServerSchema = z.object({ args: z.array(z.string()).optional(), env: z.record(z.string()).optional(), connectionTimeout: z.number().gt(0).optional(), + requestOptions: requestOptionsSchema.optional(), }); export type MCPServer = z.infer; From ad7fb2da77116aab5fbac861dbec4500a04bc1ae Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 20 Jun 2025 19:49:58 -0700 Subject: [PATCH 78/95] Update package-lock.json --- packages/openai-adapters/package-lock.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 1d88a8b5e..155f8ab36 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.39", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.36", + "version": "1.0.39", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", From 3ae9cc069e3a3e7b58b1e155bae6a3b69276fa2a Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 20 Jun 2025 19:54:31 -0700 Subject: [PATCH 79/95] Update ide.ts --- core/protocol/ide.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 5e24a62ff..7a9b8d68e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -29,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { openFile: [{ path: string }, void]; openUrl: [string, void]; runCommand: [{ command: string; options?: TerminalOptions }, void]; - getSearchResults: [{ query: string }, string]; + getSearchResults: [{ query: string; maxResults?: number }, string]; getFileResults: [{ pattern: string; maxResults?: number }, string[]]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; From fdc63310494f259a871d7b9eeccd19971960eb3c Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 20 Jun 2025 20:48:49 -0700 Subject: [PATCH 80/95] chore: version bumps --- extensions/intellij/gradle.properties | 2 +- extensions/vscode/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 8c3302728..15326353d 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.24 +pluginVersion=1.0.25 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 81b1a142d..22c040f40 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.49", + "version": "1.1.50", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 5c7a5ae023655824fb18dd82ee2f092385bc1847 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 20 Jun 2025 21:45:40 -0700 Subject: [PATCH 81/95] chore: bump openai-adapters --- packages/openai-adapters/package-lock.json | 4 ++-- packages/openai-adapters/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 155f8ab36..c114ee618 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.39", + "version": "1.0.40", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.39", + "version": "1.0.40", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index d775bb0b3..dbbb23789 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.39", + "version": "1.0.40", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From ea52d138558cdb55b3ea0f9f8b252240a05c4106 Mon Sep 17 00:00:00 2001 From: Shankhadeep Dey Date: Sun, 22 Jun 2025 22:29:59 +0530 Subject: [PATCH 82/95] feat: add webview listener for index progress to load submenu items --- gui/src/context/SubmenuContextProviders.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index 8268377de..804d622f2 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -356,6 +356,16 @@ export const SubmenuContextProvidersProvider = ({ [loadSubmenuItems], ); + useWebviewListener( + "indexProgress", + async (data) => { + if (data.status === "done") { + loadSubmenuItems("dependsOnIndexing") + } + }, + [loadSubmenuItems], + ); + // Reload all submenu items on the initial config load useEffect(() => { if (!submenuContextProviders.length) { From 944f3e16d2aa33beae0810d8d3aa642fe1b959ed Mon Sep 17 00:00:00 2001 From: Shankhadeep Dey Date: Sun, 22 Jun 2025 22:36:44 +0530 Subject: [PATCH 83/95] fix: prettier format --- gui/src/context/SubmenuContextProviders.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index 804d622f2..cf3939c48 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -360,7 +360,7 @@ export const SubmenuContextProvidersProvider = ({ "indexProgress", async (data) => { if (data.status === "done") { - loadSubmenuItems("dependsOnIndexing") + loadSubmenuItems("dependsOnIndexing"); } }, [loadSubmenuItems], From 7927a6242244a21d950e550d5cf9512d4a86a0e3 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 22 Jun 2025 11:25:03 -0700 Subject: [PATCH 84/95] feat: create `AssistantAndOrgListbox` --- extensions/vscode/package-lock.json | 4 +- .../AssistantIcon.tsx | 4 +- .../AssistantOption.tsx | 118 ++++++ .../AssistantOptions.tsx | 54 +++ .../OrganizationInfo.tsx | 14 + .../AssistantAndOrgListbox}/ScopeSelect.tsx | 30 +- .../SelectedAssistantButton.tsx | 38 ++ .../AssistantAndOrgListbox/index.tsx | 173 ++++++++ .../shared.tsx | 4 +- .../platform => }/FreeTrialButton.tsx | 11 +- .../LumpToolbar/BlockSettingsTopToolbar.tsx | 6 +- .../platform/AssistantSelect.tsx | 388 ------------------ gui/src/pages/config/AccountButton.tsx | 2 +- packages/config-yaml/package-lock.json | 4 +- 14 files changed, 432 insertions(+), 418 deletions(-) rename gui/src/components/{modelSelection/platform => AssistantAndOrgListbox}/AssistantIcon.tsx (86%) create mode 100644 gui/src/components/AssistantAndOrgListbox/AssistantOption.tsx create mode 100644 gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx create mode 100644 gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx rename gui/src/{pages/config => components/AssistantAndOrgListbox}/ScopeSelect.tsx (81%) create mode 100644 gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx create mode 100644 gui/src/components/AssistantAndOrgListbox/index.tsx rename gui/src/components/{modelSelection/platform => AssistantAndOrgListbox}/shared.tsx (98%) rename gui/src/components/{modelSelection/platform => }/FreeTrialButton.tsx (93%) delete mode 100644 gui/src/components/modelSelection/platform/AssistantSelect.tsx diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 199c669c7..1d493deef 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.48", + "version": "1.1.49", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.48", + "version": "1.1.49", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/gui/src/components/modelSelection/platform/AssistantIcon.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx similarity index 86% rename from gui/src/components/modelSelection/platform/AssistantIcon.tsx rename to gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx index c901bfdf4..aca23dad7 100644 --- a/gui/src/components/modelSelection/platform/AssistantIcon.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx @@ -1,13 +1,13 @@ import { ComputerDesktopIcon, SparklesIcon } from "@heroicons/react/24/outline"; import { ProfileDescription } from "core/config/ProfileLifecycleManager"; -import { isLocalProfile } from "../../../util"; +import { isLocalProfile } from "../../util"; export interface AssistantIconProps { assistant: ProfileDescription; size?: number; } -export default function AssistantIcon({ assistant, size }: AssistantIconProps) { +export function AssistantIcon({ assistant, size }: AssistantIconProps) { const sizeTw = size ?? 4; if (isLocalProfile(assistant)) { return ( diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOption.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOption.tsx new file mode 100644 index 000000000..201a9e852 --- /dev/null +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOption.tsx @@ -0,0 +1,118 @@ +import { + ArrowTopRightOnSquareIcon, + Cog6ToothIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { ProfileDescription } from "core/config/ProfileLifecycleManager"; +import { useContext, useMemo } from "react"; +import { useNavigate } from "react-router-dom"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch } from "../../redux/hooks"; +import { setSelectedProfile } from "../../redux/slices/profilesSlice"; +import { isLocalProfile } from "../../util"; +import { ROUTES } from "../../util/navigation"; +import { useLump } from "../mainInput/Lump/LumpContext"; +import { ListboxOption, useFontSize } from "../ui"; +import { AssistantIcon } from "./AssistantIcon"; + +interface AssistantOptionProps { + profile: ProfileDescription; + selected: boolean; + onClick: () => void; +} + +export function AssistantOption({ + profile, + selected, + onClick, +}: AssistantOptionProps) { + const tinyFont = useFontSize(-4); + const navigate = useNavigate(); + const { setSelectedSection } = useLump(); + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const hasFatalErrors = useMemo(() => { + return !!profile.errors?.find((error) => error.fatal); + }, [profile.errors]); + + function handleOptionClick() { + // optimistic update + dispatch(setSelectedProfile(profile.id)); + // notify core which will handle actual update + ideMessenger.post("didChangeSelectedProfile", { + id: profile.id, + }); + onClick(); + } + + function handleConfigure() { + ideMessenger.post("config/openProfile", { profileId: profile.id }); + onClick(); + } + + function handleClickError() { + if (profile.id === "local") { + navigate(ROUTES.HOME); + setSelectedSection("error"); + } else { + ideMessenger.post("config/openProfile", { profileId: profile.id }); + } + onClick(); + } + + return ( + +
+
+
+ +
+ + {profile.title} + +
+
+ {profile.errors && profile.errors?.length > 0 && ( + { + e.preventDefault(); + e.stopPropagation(); + handleClickError(); + }} + /> + )} + {isLocalProfile(profile) ? ( + { + e.stopPropagation(); + e.preventDefault(); + handleConfigure(); + }} + /> + ) : ( + { + e.stopPropagation(); + e.preventDefault(); + handleConfigure(); + }} + /> + )} +
+
+
+ ); +} diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx new file mode 100644 index 000000000..304444b23 --- /dev/null +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx @@ -0,0 +1,54 @@ +import { ArrowPathIcon } from "@heroicons/react/24/outline"; +import { useState } from "react"; +import { useAuth } from "../../context/Auth"; +import { cn } from "../../util/cn"; +import { AssistantOption } from "./AssistantOption"; + +interface AssistantOptionsProps { + selectedProfileId: string | undefined; + onClose: () => void; +} + +export function AssistantOptions({ + selectedProfileId, + onClose, +}: AssistantOptionsProps) { + const [loading, setLoading] = useState(false); + const { profiles, refreshProfiles } = useAuth(); + + return ( + <> + {/* Assistants Section Header */} +
+ +
{ + e.stopPropagation(); + setLoading(true); + await refreshProfiles(); + setLoading(false); + }} + > + +
+
+ +
+ {profiles?.map((profile, idx) => ( + + ))} +
+ + ); +} diff --git a/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx b/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx new file mode 100644 index 000000000..7965616ad --- /dev/null +++ b/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx @@ -0,0 +1,14 @@ +import { ScopeSelect } from "./ScopeSelect"; + +export function OrganizationInfo() { + return ( +
+
+ + +
+
+ ); +} diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx similarity index 81% rename from gui/src/pages/config/ScopeSelect.tsx rename to gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx index 9e574f44a..6374394fd 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx @@ -4,12 +4,6 @@ import { } from "@heroicons/react/24/outline"; import { UserCircleIcon } from "@heroicons/react/24/solid"; import { useContext } from "react"; -import { - Listbox, - ListboxButton, - ListboxOption, - ListboxOptions, -} from "../../components/ui/Listbox"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -17,6 +11,12 @@ import { selectCurrentOrg, setSelectedOrgId, } from "../../redux/slices/profilesSlice"; +import { + Listbox, + ListboxButton, + ListboxOption, + ListboxOptions, +} from "../ui/Listbox"; interface ScopeSelectProps { onSelect?: () => void; @@ -54,15 +54,19 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) {
{selectedDisplay?.iconUrl ? ( - + ) : ( - + )} {selectedDisplay?.name || "Select Organization"}
-
@@ -70,9 +74,13 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) {
{org.iconUrl ? ( - + ) : ( - + )} {org.name}
diff --git a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx new file mode 100644 index 000000000..131f0d1e1 --- /dev/null +++ b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx @@ -0,0 +1,38 @@ +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import type { ProfileDescription } from "core/config/ConfigHandler"; +import { fontSize } from "../../util"; +import { useLump } from "../mainInput/Lump/LumpContext"; +import { ListboxButton } from "../ui"; +import { AssistantIcon } from "./AssistantIcon"; + +interface SelectedAssistantButtonProps { + selectedProfile: ProfileDescription; +} + +export function SelectedAssistantButton({ + selectedProfile, +}: SelectedAssistantButtonProps) { + const { isToolbarExpanded } = useLump(); + return ( + +
+
+ +
+ + {selectedProfile.title} + +
+
+ ); +} diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx new file mode 100644 index 000000000..f4e92c144 --- /dev/null +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -0,0 +1,173 @@ +import { PlusIcon } from "@heroicons/react/24/outline"; +import { useContext, useEffect, useRef } from "react"; +import { useAuth } from "../../context/Auth"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + selectCurrentOrg, + setSelectedProfile, +} from "../../redux/slices/profilesSlice"; +import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; +import { useLump } from "../mainInput/Lump/LumpContext"; +import { + Listbox, + ListboxOption, + ListboxOptions, + Transition, + useFontSize, +} from "../ui"; +import { AssistantOptions } from "./AssistantOptions"; +import { OrganizationInfo } from "./OrganizationInfo"; +import { SelectedAssistantButton } from "./SelectedAssistantButton"; + +export function AssistantAndOrgListbox() { + const dispatch = useAppDispatch(); + const listboxRef = useRef(null); + const currentOrg = useAppSelector(selectCurrentOrg); + const ideMessenger = useContext(IdeMessengerContext); + const { isToolbarExpanded } = useLump(); + const { profiles, logout, selectedProfile, session, login } = useAuth(); + const smallFont = useFontSize(-3); + const tinyFont = useFontSize(-4); + + function close() { + // Close the listbox by clicking outside or programmatically + const event = new KeyboardEvent("keydown", { key: "Escape" }); + document.dispatchEvent(event); + } + + function onNewAssistant() { + void ideMessenger.request("controlPlane/openUrl", { + path: "/new", + orgSlug: currentOrg?.slug, + }); + close(); + } + + function onLogout() { + logout(); + close(); + } + + useEffect(() => { + let lastToggleTime = 0; + const DEBOUNCE_MS = 800; + + const handleKeyDown = (event: KeyboardEvent) => { + if ( + event.key === "'" && + isMetaEquivalentKeyPressed(event as any) && + event.shiftKey + ) { + const now = Date.now(); + + if (now - lastToggleTime >= DEBOUNCE_MS) { + lastToggleTime = now; + + const profileIds = profiles?.map((profile) => profile.id) ?? []; + // In case of 1 or 0 profiles just does nothing + if (profileIds.length < 2) { + return; + } + let nextId = profileIds[0]; + if (selectedProfile) { + const curIndex = profileIds.indexOf(selectedProfile.id); + const nextIndex = (curIndex + 1) % profileIds.length; + nextId = profileIds[nextIndex]; + } + // Optimistic update + dispatch(setSelectedProfile(nextId)); + ideMessenger.post("didChangeSelectedProfile", { + id: nextId, + }); + } + } + }; + + window.addEventListener("keydown", handleKeyDown); + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, [currentOrg, selectedProfile]); + + if (!selectedProfile) { + return ( +
{ + void ideMessenger.request("controlPlane/openUrl", { + path: "/new?type=assistant", + orgSlug: currentOrg?.slug, + }); + }} + className="text-description flex cursor-pointer select-none items-center gap-1" + style={{ fontSize: smallFont }} + > + + + Create your first assistant + +
+ ); + } + + return ( + +
+ + + + + + + {/* Bottom Actions */} +
+ login(false)} + > +
+ New Assistant +
+
+ + {session && ( + +
+ Log out +
+
+ )} + +
+ + {getMetaKeyLabel()} ⇧ ' to toggle assistant + +
+
+
+
+
+
+ ); +} diff --git a/gui/src/components/modelSelection/platform/shared.tsx b/gui/src/components/AssistantAndOrgListbox/shared.tsx similarity index 98% rename from gui/src/components/modelSelection/platform/shared.tsx rename to gui/src/components/AssistantAndOrgListbox/shared.tsx index b617fd34e..1f57a4309 100644 --- a/gui/src/components/modelSelection/platform/shared.tsx +++ b/gui/src/components/AssistantAndOrgListbox/shared.tsx @@ -10,8 +10,8 @@ import { defaultBorderRadius, lightGray, vscCommandCenterInactiveBorder, -} from "../.."; -import { ToolTip } from "../../gui/Tooltip"; +} from ".."; +import { ToolTip } from "../gui/Tooltip"; export const OptionDiv = styled.div<{ isDisabled?: boolean; diff --git a/gui/src/components/modelSelection/platform/FreeTrialButton.tsx b/gui/src/components/FreeTrialButton.tsx similarity index 93% rename from gui/src/components/modelSelection/platform/FreeTrialButton.tsx rename to gui/src/components/FreeTrialButton.tsx index c34d0abce..1665b318d 100644 --- a/gui/src/components/modelSelection/platform/FreeTrialButton.tsx +++ b/gui/src/components/FreeTrialButton.tsx @@ -1,11 +1,10 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { FreeTrialStatus } from "core/control-plane/client"; import { useContext } from "react"; -import { Button, SecondaryButton, vscButtonBackground } from "../.."; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { fontSize } from "../../../util"; -import { Listbox, ListboxButton, ListboxOptions, Transition } from "../../ui"; -import { useFontSize } from "../../ui/font"; +import { Button, SecondaryButton, vscButtonBackground } from "."; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { fontSize } from "../util"; +import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui"; interface ProgressBarProps { label: string; @@ -78,8 +77,6 @@ interface FreeTrialButtonProps { export default function FreeTrialButton({ freeTrialStatus, }: FreeTrialButtonProps) { - const smallFont = useFontSize(-3); - const tinyFont = useFontSize(-4); const ideMessenger = useContext(IdeMessengerContext); return ( diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx index 4be749689..f902c757a 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx @@ -13,9 +13,8 @@ import { ReactNode, useContext, useEffect, useState } from "react"; import { vscBadgeForeground } from "../../.."; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppSelector } from "../../../../redux/hooks"; +import FreeTrialButton from "../../../FreeTrialButton"; import { ToolTip } from "../../../gui/Tooltip"; -import AssistantSelect from "../../../modelSelection/platform/AssistantSelect"; -import FreeTrialButton from "../../../modelSelection/platform/FreeTrialButton"; import { useFontSize } from "../../../ui/font"; import HoverItem from "../../InputToolbar/HoverItem"; import { useLump } from "../LumpContext"; @@ -25,6 +24,7 @@ import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSecti import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey"; import type { FreeTrialStatus } from "core/control-plane/client"; +import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox"; interface BlockSettingsToolbarIcon { title: string; @@ -236,7 +236,7 @@ export function BlockSettingsTopToolbar() { {isUsingFreeTrial ? ( ) : ( - + )} {isUsingFreeTrial ? "View free trial usage" : "Select Assistant"} diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx deleted file mode 100644 index d360abce4..000000000 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ /dev/null @@ -1,388 +0,0 @@ -import { - ArrowPathIcon, - ArrowTopRightOnSquareIcon, - BuildingOfficeIcon, - ChevronDownIcon, - Cog6ToothIcon, - ExclamationTriangleIcon, - PlusIcon, -} from "@heroicons/react/24/outline"; -import type { ProfileDescription } from "core/config/ConfigHandler"; -import { useContext, useEffect, useMemo, useRef, useState } from "react"; -import { useNavigate } from "react-router-dom"; -import { useAuth } from "../../../context/Auth"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { - selectCurrentOrg, - setSelectedOrgId, - setSelectedProfile, -} from "../../../redux/slices/profilesSlice"; -import { - fontSize, - getMetaKeyLabel, - isLocalProfile, - isMetaEquivalentKeyPressed, -} from "../../../util"; -import { cn } from "../../../util/cn"; -import { ROUTES } from "../../../util/navigation"; -import { useLump } from "../../mainInput/Lump/LumpContext"; -import { - Listbox, - ListboxButton, - ListboxOption, - ListboxOptions, - Transition, - useFontSize, -} from "../../ui"; -import AssistantIcon from "./AssistantIcon"; -interface AssistantSelectOptionProps { - profile: ProfileDescription; - selected: boolean; - onClick: () => void; -} - -const AssistantSelectOption = ({ - profile, - selected, - onClick, -}: AssistantSelectOptionProps) => { - const tinyFont = useFontSize(-4); - - const navigate = useNavigate(); - const { setSelectedSection } = useLump(); - - const hasFatalErrors = useMemo(() => { - return !!profile.errors?.find((error) => error.fatal); - }, [profile.errors]); - - const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - - function handleOptionClick() { - // optimistic update - dispatch(setSelectedProfile(profile.id)); - // notify core which will handle actual update - ideMessenger.post("didChangeSelectedProfile", { - id: profile.id, - }); - onClick(); - } - - function handleConfigure() { - ideMessenger.post("config/openProfile", { profileId: profile.id }); - onClick(); - } - - function handleClickError() { - if (profile.id === "local") { - navigate(ROUTES.HOME); - setSelectedSection("error"); - } else { - ideMessenger.post("config/openProfile", { profileId: profile.id }); - } - onClick(); - } - - return ( - -
-
-
-
- -
- - {profile.title} - -
-
- {profile.errors && profile.errors?.length > 0 && ( - { - e.preventDefault(); - e.stopPropagation(); - handleClickError(); - }} - /> - )} - {isLocalProfile(profile) ? ( - { - e.stopPropagation(); - e.preventDefault(); - handleConfigure(); - }} - /> - ) : ( - { - e.stopPropagation(); - e.preventDefault(); - handleConfigure(); - }} - /> - )} -
-
-
-
- ); -}; - -export default function AssistantSelect() { - const dispatch = useAppDispatch(); - const buttonRef = useRef(null); - const currentOrg = useAppSelector(selectCurrentOrg); - const orgs = useAppSelector((store) => store.profiles.organizations); - const ideMessenger = useContext(IdeMessengerContext); - const { isToolbarExpanded } = useLump(); - const [loading, setLoading] = useState(false); - const { profiles, session, login, selectedProfile, refreshProfiles } = - useAuth(); - - function close() { - if (buttonRef.current) { - buttonRef.current.click(); - } - } - function onNewAssistant() { - ideMessenger.post("controlPlane/openUrl", { - path: "new", - orgSlug: currentOrg?.slug, - }); - close(); - } - - useEffect(() => { - let lastToggleTime = 0; - const DEBOUNCE_MS = 800; - - const handleKeyDown = (event: KeyboardEvent) => { - if ( - event.key === "'" && - isMetaEquivalentKeyPressed(event as any) && - event.shiftKey - ) { - const now = Date.now(); - - if (now - lastToggleTime >= DEBOUNCE_MS) { - lastToggleTime = now; - - const profileIds = profiles?.map((profile) => profile.id) ?? []; - // In case of 1 or 0 profiles just does nothing - if (profileIds.length < 2) { - return; - } - let nextId = profileIds[0]; - if (selectedProfile) { - const curIndex = profileIds.indexOf(selectedProfile.id); - const nextIndex = (curIndex + 1) % profileIds.length; - nextId = profileIds[nextIndex]; - } - // Optimistic update - dispatch(setSelectedProfile(nextId)); - ideMessenger.post("didChangeSelectedProfile", { - id: nextId, - }); - } - } - }; - - window.addEventListener("keydown", handleKeyDown); - return () => { - window.removeEventListener("keydown", handleKeyDown); - }; - }, [currentOrg, selectedProfile]); - - const cycleOrgs = () => { - if (!session) { - void login(false); - return; - } - - const orgIds = orgs.map((org) => org.id); - if (orgIds.length < 2) { - return; - } - let nextId = orgIds[0]; - if (currentOrg) { - const curIndex = orgIds.indexOf(currentOrg.id); - const nextIndex = (curIndex + 1) % orgIds.length; - nextId = orgIds[nextIndex]; - } - // Optimistic update - dispatch(setSelectedOrgId(nextId)); - ideMessenger.post("didChangeSelectedOrg", { - id: nextId, - }); - }; - - const tinyFont = useFontSize(-4); - const smallFont = useFontSize(-3); - - if (!selectedProfile) { - return ( -
{ - void ideMessenger.request("controlPlane/openUrl", { - path: "/new?type=assistant", - orgSlug: currentOrg?.slug, - }); - }} - className="text-description flex cursor-pointer select-none items-center gap-1" - style={{ fontSize: smallFont }} - > - - - Create your first assistant - -
- ); - } - - return ( - -
- -
-
- -
- - {selectedProfile.title} - -
-
- - - -
- Assistants -
{ - e.stopPropagation(); - setLoading(true); - await refreshProfiles(); - setLoading(false); - buttonRef.current?.click(); - }} - > - -
-
- -
- {profiles?.map((profile, idx) => { - return ( - - ); - })} -
- -
-
- login(false)} - > -
- - New Assistant -
-
-
- -
- - {getMetaKeyLabel()} ⇧ ' to toggle - -
- {currentOrg?.iconUrl ? ( - - ) : ( - - )} - - {currentOrg?.name || "Personal"} - -
-
-
-
-
-
-
- ); -} diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 888488208..f108c8e65 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,5 +1,6 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; import { isOnPremSession } from "core/control-plane/AuthTypes"; +import { ScopeSelect } from "../../components/AssistantAndOrgListbox/ScopeSelect"; import { Button, Popover, @@ -10,7 +11,6 @@ import { import { useAuth } from "../../context/Auth"; import { useAppSelector } from "../../redux/hooks"; import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; -import { ScopeSelect } from "./ScopeSelect"; export function AccountButton() { const { session, logout, login, organizations } = useAuth(); diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 492e0eaa5..6d02d51d8 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.93", + "version": "1.0.94", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.93", + "version": "1.0.94", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From b96068408e65b2c5687b7736eba831febcc02fc8 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 22 Jun 2025 11:35:16 -0700 Subject: [PATCH 85/95] remove accountbutton --- .../AssistantAndOrgListbox/AccountOption.tsx | 42 ++++++++++ .../OrganizationInfo.tsx | 14 +++- .../AssistantAndOrgListbox/index.tsx | 24 +----- gui/src/pages/config/AccountButton.tsx | 82 ------------------- gui/src/pages/config/index.tsx | 2 - gui/src/pages/history/index.tsx | 8 +- 6 files changed, 57 insertions(+), 115 deletions(-) create mode 100644 gui/src/components/AssistantAndOrgListbox/AccountOption.tsx delete mode 100644 gui/src/pages/config/AccountButton.tsx diff --git a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx b/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx new file mode 100644 index 000000000..8f4f8e11e --- /dev/null +++ b/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx @@ -0,0 +1,42 @@ +import { isOnPremSession } from "core/control-plane/AuthTypes"; +import { useAuth } from "../../context/Auth"; +import { ListboxOption, useFontSize } from "../ui"; + +interface AccountOptionProps { + onClose: () => void; +} + +export function AccountOption({ onClose }: AccountOptionProps) { + const { session, logout, login } = useAuth(); + const tinyFont = useFontSize(-4); + + // No account option for on-prem deployments + if (session && isOnPremSession(session)) { + return null; + } + + async function handleClick() { + if (session) { + logout(); + } else { + await login(false); + } + onClose(); + } + + return ( + +
+ {session ? "Log out" : "Sign in"} +
+
+ ); +} diff --git a/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx b/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx index 7965616ad..a4439afab 100644 --- a/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx +++ b/gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx @@ -1,12 +1,20 @@ +import { useAuth } from "../../context/Auth"; import { ScopeSelect } from "./ScopeSelect"; export function OrganizationInfo() { + const { session } = useAuth(); + return (
- +
+ + {!session && ( + (Signed out) + )} +
diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index f4e92c144..114b70ef2 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -16,6 +16,7 @@ import { Transition, useFontSize, } from "../ui"; +import { AccountOption } from "./AccountOption"; import { AssistantOptions } from "./AssistantOptions"; import { OrganizationInfo } from "./OrganizationInfo"; import { SelectedAssistantButton } from "./SelectedAssistantButton"; @@ -26,7 +27,7 @@ export function AssistantAndOrgListbox() { const currentOrg = useAppSelector(selectCurrentOrg); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); - const { profiles, logout, selectedProfile, session, login } = useAuth(); + const { profiles, selectedProfile, session, login } = useAuth(); const smallFont = useFontSize(-3); const tinyFont = useFontSize(-4); @@ -44,11 +45,6 @@ export function AssistantAndOrgListbox() { close(); } - function onLogout() { - logout(); - close(); - } - useEffect(() => { let lastToggleTime = 0; const DEBOUNCE_MS = 800; @@ -140,21 +136,7 @@ export function AssistantAndOrgListbox() {
- {session && ( - -
- Log out -
-
- )} +
login(false)} - > - Sign in - - ); - } - - // No login button for on-prem deployments - if (isOnPremSession(session)) { - return null; - } - - return ( - - {({ close }) => ( - <> - -
- - {selectedOrg === null ? "Personal" : selectedOrg.name} - - -
-
- - - -
-
- {session.account.label} - - {session.account.id} - -
- - {organizations.length > 0 && ( -
- - -
- )} - - -
-
-
- - )} -
- ); -} diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index ea5ccef44..d9939a2c8 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -9,7 +9,6 @@ import { useNavigate } from "react-router-dom"; import { PageHeader } from "../../components/PageHeader"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { fontSize } from "../../util"; -import { AccountButton } from "./AccountButton"; import { HelpCenterSection } from "./HelpCenterSection"; import { IndexingSettingsSection } from "./IndexingSettingsSection"; import KeyboardShortcuts from "./KeyboardShortcuts"; @@ -63,7 +62,6 @@ function ConfigPage() { showBorder onTitleClick={() => navigate("/")} title="Chat" - rightContent={} /> {/* Tab Headers */} diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx index a8be3d92f..86950ff24 100644 --- a/gui/src/pages/history/index.tsx +++ b/gui/src/pages/history/index.tsx @@ -2,7 +2,6 @@ import { useNavigate } from "react-router-dom"; import { History } from "../../components/History"; import { PageHeader } from "../../components/PageHeader"; import { getFontSize } from "../../util"; -import { AccountButton } from "../config/AccountButton"; export default function HistoryPage() { const navigate = useNavigate(); @@ -12,12 +11,7 @@ export default function HistoryPage() { className="flex flex-1 flex-col overflow-auto" style={{ fontSize: getFontSize() }} > - navigate("/")} - title="Chat" - rightContent={} - /> + navigate("/")} title="Chat" />
); From 7e80ca94ce128dcb2e63c6b1950b02c03401ae17 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 22 Jun 2025 11:41:23 -0700 Subject: [PATCH 86/95] remove auth dialog --- .../AssistantAndOrgListbox/index.tsx | 2 +- gui/src/context/Auth.tsx | 31 ++++--------------- 2 files changed, 7 insertions(+), 26 deletions(-) diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index 114b70ef2..ee175a725 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -113,7 +113,7 @@ export function AssistantAndOrgListbox() {
- + = ({ const selectedProfile = useAppSelector(selectSelectedProfile); const login: AuthContextType["login"] = (useOnboarding: boolean) => { - return new Promise((resolve) => { - ideMessenger + return new Promise(async (resolve) => { + await ideMessenger .request("getControlPlaneSessionInfo", { silent: false, useOnboarding, @@ -73,27 +71,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }; const logout = () => { - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - { - ideMessenger.post("logoutOfControlPlane", undefined); - dispatch( - setOrganizations(orgs.filter((org) => org.id === "personal")), - ); - dispatch(setSelectedOrgId("personal")); - setSession(undefined); - }} - onCancel={() => { - dispatch(setDialogMessage(undefined)); - dispatch(setShowDialog(false)); - }} - />, - ), - ); + ideMessenger.post("logoutOfControlPlane", undefined); + dispatch(setOrganizations(orgs.filter((org) => org.id === "personal"))); + dispatch(setSelectedOrgId("personal")); + setSession(undefined); }; useEffect(() => { From 94113e0ee18785c55414ec6744b8147ca0d88f60 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 22 Jun 2025 12:06:51 -0700 Subject: [PATCH 87/95] fix: use last 2 parts of file uri for rule names --- .../src/markdown/markdownToRule.test.ts | 123 ++++++++++++++++-- .../src/markdown/markdownToRule.ts | 24 +++- 2 files changed, 137 insertions(+), 10 deletions(-) diff --git a/packages/config-yaml/src/markdown/markdownToRule.test.ts b/packages/config-yaml/src/markdown/markdownToRule.test.ts index 71c22343b..1b930220a 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.test.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.test.ts @@ -1,5 +1,5 @@ import { PackageIdentifier } from "../browser.js"; -import { markdownToRule } from "./markdownToRule.js"; +import { getRuleName, markdownToRule } from "./markdownToRule.js"; describe("markdownToRule", () => { // Use a mock PackageIdentifier for testing @@ -36,7 +36,7 @@ This is a test rule.`; const result = markdownToRule(content, mockId); expect(result.globs).toBe("**/test/**/*.kt"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should handle missing frontmatter", () => { @@ -47,7 +47,7 @@ This is a test rule without frontmatter.`; const result = markdownToRule(content, mockId); expect(result.globs).toBeUndefined(); expect(result.rule).toBe(content); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should handle empty frontmatter", () => { @@ -63,7 +63,7 @@ This is a test rule with empty frontmatter.`; expect(result.rule).toBe( "# Test Rule\n\nThis is a test rule with empty frontmatter.", ); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should handle frontmatter with whitespace", () => { @@ -78,7 +78,7 @@ This is a test rule.`; const result = markdownToRule(content, mockId); expect(result.globs).toBe("**/test/**/*.kt"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should handle Windows line endings (CRLF)", () => { @@ -95,7 +95,7 @@ This is a test rule.`; expect(result.globs).toBe("**/test/**/*.kt"); // The result should be normalized to \n expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should handle malformed frontmatter", () => { @@ -112,7 +112,7 @@ This is a test rule.`; const result = markdownToRule(content, mockId); expect(result.globs).toBeUndefined(); expect(result.rule).toBe(content); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should use packageIdentifierToDisplayName if no heading or frontmatter name", () => { @@ -125,7 +125,7 @@ globs: "**/test/**/*.kt" This is a test rule.`; const result = markdownToRule(content, mockId); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should use packageIdentifierToDisplayName if no heading or frontmatter name (no heading)", () => { @@ -136,7 +136,7 @@ globs: "**/test/**/*.kt" This is a test rule without a heading.`; const result = markdownToRule(content, mockId); - expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result + expect(result.name).toBe("to/file"); // Should use last two path segments }); it("should include description from frontmatter", () => { @@ -171,3 +171,108 @@ This is a rule with alwaysApply explicitly set to false.`; expect(result.alwaysApply).toBe(false); }); }); + +describe("getRuleName", () => { + it("should return frontmatter name when provided", () => { + const frontmatter = { name: "Custom Rule Name" }; + const id: PackageIdentifier = { + uriType: "file", + filePath: "/path/to/my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("Custom Rule Name"); + }); + + it("should return last two path segments for file identifier when no name", () => { + const frontmatter = {}; + const id: PackageIdentifier = { + uriType: "file", + filePath: "/long/path/to/rules/my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("rules/my-rule.md"); + }); + + it("should handle file paths with backslashes", () => { + const frontmatter = {}; + const id: PackageIdentifier = { + uriType: "file", + filePath: "C:\\long\\path\\to\\rules\\my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("rules/my-rule.md"); + }); + + it("should handle mixed forward and back slashes", () => { + const frontmatter = {}; + const id: PackageIdentifier = { + uriType: "file", + filePath: "/path/to\\rules/my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("rules/my-rule.md"); + }); + + it("should handle single segment path", () => { + const frontmatter = {}; + const id: PackageIdentifier = { + uriType: "file", + filePath: "my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("my-rule.md"); + }); + + it("should handle two segment path", () => { + const frontmatter = {}; + const id: PackageIdentifier = { + uriType: "file", + filePath: "rules/my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("rules/my-rule.md"); + }); + + it("should return display name for non-file identifiers", () => { + const frontmatter = {}; + const id: PackageIdentifier = { + uriType: "slug", + fullSlug: { + ownerSlug: "test-owner", + packageSlug: "my-rule-package", + versionSlug: "v1.0.0", + }, + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("my-rule-package"); // packageIdentifierToDisplayName returns just the packageSlug + }); + + it("should prioritize frontmatter name over file path", () => { + const frontmatter = { name: "Override Name" }; + const id: PackageIdentifier = { + uriType: "file", + filePath: "/very/long/path/to/rules/original-name.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("Override Name"); + }); + + it("should handle empty string name in frontmatter by falling back to path", () => { + const frontmatter = { name: "" }; + const id: PackageIdentifier = { + uriType: "file", + filePath: "/path/to/rules/my-rule.md", + }; + + const result = getRuleName(frontmatter, id); + expect(result).toBe("rules/my-rule.md"); // Empty string is falsy, so falls back to path logic + }); +}); diff --git a/packages/config-yaml/src/markdown/markdownToRule.ts b/packages/config-yaml/src/markdown/markdownToRule.ts index a48f8176a..6c52cd82f 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.ts @@ -46,6 +46,28 @@ export function parseMarkdownRule(content: string): { return { frontmatter: {}, markdown: normalizedContent }; } +export function getRuleName( + frontmatter: RuleFrontmatter, + id: PackageIdentifier, +): string { + if (frontmatter.name) { + return frontmatter.name; + } + + const displayName = packageIdentifierToDisplayName(id); + + // If it's a file identifier, extract the last two parts of the file path + if (id.uriType === "file") { + // Handle both forward slashes and backslashes, get the last two segments + const segments = displayName.split(/[/\\]/); + const lastTwoParts = segments.slice(-2); + return lastTwoParts.join("/"); + } + + // Otherwise return the display name as-is (for slug identifiers) + return displayName; +} + export function markdownToRule( rule: string, id: PackageIdentifier, @@ -53,7 +75,7 @@ export function markdownToRule( const { frontmatter, markdown } = parseMarkdownRule(rule); return { - name: frontmatter.name ?? packageIdentifierToDisplayName(id), + name: getRuleName(frontmatter, id), rule: markdown, globs: frontmatter.globs, description: frontmatter.description, From 141e7dc30b9442d4eeaf9913dab2e337a1b06c9d Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 22 Jun 2025 12:21:59 -0700 Subject: [PATCH 88/95] Update ScopeSelect.tsx --- .../AssistantAndOrgListbox/ScopeSelect.tsx | 37 ++++++++----------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx b/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx index 6374394fd..7cac430a8 100644 --- a/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx +++ b/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx @@ -21,6 +21,19 @@ import { interface ScopeSelectProps { onSelect?: () => void; } + +function getOrgIcon(org: { name: string; iconUrl?: string | null }) { + if (org.iconUrl) { + return ( + + ); + } + + const IconComponent = + org.name === "Personal" ? UserCircleIcon : BuildingOfficeIcon; + return ; +} + export function ScopeSelect({ onSelect }: ScopeSelectProps) { const { organizations } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); @@ -39,10 +52,6 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) { onSelect?.(); }; - const CurScopeEntityFallBackIcon = selectedOrgId - ? BuildingOfficeIcon - : UserCircleIcon; - const selectedDisplay = currentOrg ?? { name: "Personal", iconUrl: null, @@ -53,15 +62,7 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) {
- {selectedDisplay?.iconUrl ? ( - - ) : ( - - )} + {getOrgIcon(selectedDisplay)} {selectedDisplay?.name || "Select Organization"} @@ -73,15 +74,7 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) { {organizations.map((org) => (
- {org.iconUrl ? ( - - ) : ( - - )} + {getOrgIcon(org)} {org.name}
From bf470aecda7121996b893de2a21f76b07ea084ba Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 22 Jun 2025 16:57:48 -0700 Subject: [PATCH 89/95] feat: new rules --- .../rules/github-pr-documentation-updater.md | 7 +++ .continue/rules/pure-function-unit-tests.md | 1 + .../vs-code-commands-helper-functions.md | 5 ++ extensions/intellij/rules.md | 56 +++++++++++++++++++ extensions/vscode/package-lock.json | 4 +- packages/config-yaml/package-lock.json | 4 +- 6 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 .continue/rules/github-pr-documentation-updater.md create mode 100644 .continue/rules/pure-function-unit-tests.md create mode 100644 .continue/rules/vs-code-commands-helper-functions.md create mode 100644 extensions/intellij/rules.md diff --git a/.continue/rules/github-pr-documentation-updater.md b/.continue/rules/github-pr-documentation-updater.md new file mode 100644 index 000000000..3560ccdad --- /dev/null +++ b/.continue/rules/github-pr-documentation-updater.md @@ -0,0 +1,7 @@ +--- +name: Update docs from GitHub PR +description: Provide a PR link to update docs based on +alwaysApply: false +--- + +When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style. diff --git a/.continue/rules/pure-function-unit-tests.md b/.continue/rules/pure-function-unit-tests.md new file mode 100644 index 000000000..68a1ff983 --- /dev/null +++ b/.continue/rules/pure-function-unit-tests.md @@ -0,0 +1 @@ +Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions. diff --git a/.continue/rules/vs-code-commands-helper-functions.md b/.continue/rules/vs-code-commands-helper-functions.md new file mode 100644 index 000000000..bf2e0a8da --- /dev/null +++ b/.continue/rules/vs-code-commands-helper-functions.md @@ -0,0 +1,5 @@ +--- +globs: "extensions/vscode/src/commands.ts" +--- + +When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry. diff --git a/extensions/intellij/rules.md b/extensions/intellij/rules.md new file mode 100644 index 000000000..1f95724c9 --- /dev/null +++ b/extensions/intellij/rules.md @@ -0,0 +1,56 @@ +# Continue JetBrains Extension + +## Project Purpose + +JetBrains/IntelliJ extension for Continue AI code assistant. Provides chat, autocomplete, inline edit, and agent features within JetBrains IDEs. + +## Architecture + +- **Language**: Kotlin (JDK 17), Gradle build +- **Communication**: stdin/stdout message passing with core binary from `../../binary` +- **UI**: Embeds React webview from `../../gui` +- **Platform**: IntelliJ Platform Plugin (IDEA, PyCharm, WebStorm, etc.) + +## Key Source Structure + +``` +src/main/kotlin/com/github/continuedev/continueintellijextension/ +├── continue/ # Core integration (CoreMessenger, IntelliJIde, IdeProtocolClient) +├── autocomplete/ # Code completion logic +├── editor/ # Diff handling, inline edits +├── toolWindow/ # Main UI panel +├── services/ # Settings, plugin lifecycle +├── actions/ # Keyboard shortcuts, menu actions +├── protocol/ # Message type definitions +└── constants/ # App constants, paths + +src/main/resources/ +├── META-INF/plugin.xml # Plugin configuration +└── webview/ # Embedded React UI assets +``` + +## Core Files + +- `IntelliJIde.kt`: Main IDE interface implementation +- `CoreMessenger.kt`: Binary communication handler +- `plugin.xml`: Plugin manifest and extension points +- `build.gradle.kts`: Build configuration +- `ContinuePluginService.kt`: Main service orchestrator + +## Message Protocol + +JSON messages between Extension ↔ Core ↔ GUI. Message types in `constants/MessageTypes.kt`. Extension relays messages between core binary and webview. + +## Testing + +- Unit tests: `src/test/kotlin/` +- E2E tests: UI automation with intellij-ui-test-robot +- Test command: `./gradlew test` +- Debug: `runIde` Gradle task + +## Key Integration Points + +- File operations via IntelliJ VFS +- Editor integration for diffs/autocomplete +- Git operations for repository context +- Settings via IntelliJ platform storage diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 199c669c7..1d493deef 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.48", + "version": "1.1.49", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.48", + "version": "1.1.49", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 492e0eaa5..6d02d51d8 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.93", + "version": "1.0.94", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.93", + "version": "1.0.94", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From 084f6cc27eeb2f784b522da2e835a9835dc03564 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 23 Jun 2025 16:25:45 +0530 Subject: [PATCH 90/95] add enable reasoning button --- gui/src/components/mainInput/InputToolbar.tsx | 30 ++++++++++++++++++- gui/src/hooks/ParallelListeners.tsx | 10 ++++++- gui/src/redux/slices/sessionSlice.ts | 5 ++++ gui/src/redux/thunks/streamNormalInput.ts | 8 +++++ 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 23d242ae2..0dfbcd493 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,4 +1,8 @@ -import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; +import { + AtSymbolIcon, + LightBulbIcon, + PhotoIcon, +} from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; import { useContext, useRef } from "react"; @@ -10,8 +14,10 @@ import { selectCurrentToolCallApplyState, } from "../../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; +import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice"; import { exitEdit } from "../../redux/thunks/edit"; import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; +import { cn } from "../../util/cn"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; import { ModeSelect } from "../ModeSelect"; @@ -51,6 +57,9 @@ function InputToolbar(props: InputToolbarProps) { const currentToolCallApplyState = useAppSelector( selectCurrentToolCallApplyState, ); + const hasReasoningEnabled = useAppSelector( + (store) => store.session.hasReasoningEnabled, + ); const isEnterDisabled = props.disabled || @@ -143,6 +152,25 @@ function InputToolbar(props: InputToolbarProps) { )} + {defaultModel?.provider === "anthropic" && ( + + dispatch(setHasReasoningEnabled(!hasReasoningEnabled)) + } + > + + + + Use Model Reasoning + + + )}
diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index a283ed969..8d0fef86d 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -20,6 +20,7 @@ import { import { acceptToolCall, addContextItemsAtIndex, + setHasReasoningEnabled, updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; @@ -86,6 +87,13 @@ function ParallelListeners() { setLocalStorage("fontSize", configResult.config.ui.fontSize); document.body.style.fontSize = `${configResult.config.ui.fontSize}px`; } + + if ( + configResult.config?.selectedModelByRole.chat?.completionOptions + ?.reasoning + ) { + dispatch(setHasReasoningEnabled(true)); + } }, [dispatch, hasDoneInitialConfigLoad], ); @@ -241,7 +249,7 @@ function ParallelListeners() { dispatch(updateEditStateApplyState(state)); if (state.status === "closed") { - dispatch(exitEdit({})); + void dispatch(exitEdit({})); } } else { // chat or agent diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 37eba4b4f..6803947fb 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -51,6 +51,7 @@ type SessionState = { curIndex: number; }; newestToolbarPreviewForInput: Record; + hasReasoningEnabled?: boolean; }; const initialState: SessionState = { @@ -594,6 +595,9 @@ export const sessionSlice = createSlice({ setIsInEdit: (state, action: PayloadAction) => { state.isInEdit = action.payload; }, + setHasReasoningEnabled: (state, action: PayloadAction) => { + state.hasReasoningEnabled = action.payload; + }, setNewestToolbarPreviewForInput: ( state, { @@ -691,6 +695,7 @@ export const { deleteSessionMetadata, setNewestToolbarPreviewForInput, setIsInEdit, + setHasReasoningEnabled, } = sessionSlice.actions; export const { selectIsGatheringContext } = sessionSlice.selectors; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 441cf3c20..6d84f800e 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -45,6 +45,14 @@ export const streamNormalInput = createAsyncThunk< }; } + if (state.session.hasReasoningEnabled) { + completionOptions = { + ...completionOptions, + reasoning: true, + reasoningBudgetTokens: completionOptions.reasoningBudgetTokens ?? 2048, + }; + } + // Send request const gen = extra.ideMessenger.llmStreamChat( { From 2574a8b4b57d1287f0c75b6519606130b996d9f3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 23 Jun 2025 18:41:59 +0530 Subject: [PATCH 91/95] rename to vitest --- core/commands/{util.test.ts => util.vitest.ts} | 0 core/control-plane/mdm/{mdm.test.ts => mdm.vitest.ts} | 0 core/data/{log.test.ts => log.vitest.ts} | 0 core/diff/{myers.test.ts => myers.vitest.ts} | 0 core/diff/{streamDiff.test.ts => streamDiff.vitest.ts} | 0 core/diff/{util.test.ts => util.vitest.ts} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename core/commands/{util.test.ts => util.vitest.ts} (100%) rename core/control-plane/mdm/{mdm.test.ts => mdm.vitest.ts} (100%) rename core/data/{log.test.ts => log.vitest.ts} (100%) rename core/diff/{myers.test.ts => myers.vitest.ts} (100%) rename core/diff/{streamDiff.test.ts => streamDiff.vitest.ts} (100%) rename core/diff/{util.test.ts => util.vitest.ts} (100%) diff --git a/core/commands/util.test.ts b/core/commands/util.vitest.ts similarity index 100% rename from core/commands/util.test.ts rename to core/commands/util.vitest.ts diff --git a/core/control-plane/mdm/mdm.test.ts b/core/control-plane/mdm/mdm.vitest.ts similarity index 100% rename from core/control-plane/mdm/mdm.test.ts rename to core/control-plane/mdm/mdm.vitest.ts diff --git a/core/data/log.test.ts b/core/data/log.vitest.ts similarity index 100% rename from core/data/log.test.ts rename to core/data/log.vitest.ts diff --git a/core/diff/myers.test.ts b/core/diff/myers.vitest.ts similarity index 100% rename from core/diff/myers.test.ts rename to core/diff/myers.vitest.ts diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.vitest.ts similarity index 100% rename from core/diff/streamDiff.test.ts rename to core/diff/streamDiff.vitest.ts diff --git a/core/diff/util.test.ts b/core/diff/util.vitest.ts similarity index 100% rename from core/diff/util.test.ts rename to core/diff/util.vitest.ts From 7f541da7ecaec0dee26d51218ccb22fa534e3dc4 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 23 Jun 2025 09:23:00 -0700 Subject: [PATCH 92/95] improv: naming --- core/index.d.ts | 2 +- core/llm/rules/getSystemMessageWithRules.ts | 44 +++++++++---------- .../rules/getSystemMessageWithRules.vitest.ts | 20 ++++----- core/tools/definitions/createRuleBlock.ts | 2 +- core/tools/implementations/createRuleBlock.ts | 8 ++-- docs/docs/customize/deep-dives/rules.mdx | 1 + .../src/markdown/createMarkdownRule.ts | 10 ++--- .../src/markdown/markdownToRule.ts | 4 +- packages/config-yaml/src/schemas/index.ts | 2 +- 9 files changed, 46 insertions(+), 47 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 1c7f336f2..3dde3bc78 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1576,7 +1576,7 @@ export interface RuleWithSource { slug?: string; source: RuleSource; globs?: string | string[]; - patterns?: string | string[]; + regex?: string | string[]; rule: string; description?: string; ruleFile?: string; diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 62756923e..65c04f2a6 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -54,33 +54,33 @@ const matchesGlobs = ( }; /** - * Checks if file content matches any of the provided regex patterns + * Checks if file content matches any of the provided regex regex * * @param fileContent - The content of the file to check - * @param patterns - A single regex pattern string or array of regex pattern strings - * @returns true if the content matches any pattern (or if no patterns are provided), false otherwise + * @param regex - A single regex pattern string or array of regex pattern strings + * @returns true if the content matches any pattern (or if no regex is provided), false otherwise */ const contentMatchesPatterns = ( fileContent: string, - patterns: string | string[], + regex: string | string[], ): boolean => { // Handle single string pattern - if (typeof patterns === "string") { + if (typeof regex === "string") { try { - const regex = new RegExp(patterns); - return regex.test(fileContent); + const expression = new RegExp(regex); + return expression.test(fileContent); } catch (e) { - console.error(`Invalid regex pattern: ${patterns}`, e); + console.error(`Invalid regex pattern: ${regex}`, e); return false; } } - // Handle array of patterns - if (Array.isArray(patterns)) { - if (patterns.length === 0) return true; + // Handle array of regex + if (Array.isArray(regex)) { + if (regex.length === 0) return true; // Content must match at least one pattern - return patterns.some((pattern) => { + return regex.some((pattern) => { try { const regex = new RegExp(pattern); return regex.test(fileContent); @@ -145,11 +145,11 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { return true; } - // Root-level rules with no globs or patterns are implicitly global + // Root-level rules with no globs or regex are implicitly global if ( isRootLevelRule(rule) && !rule.globs && - !rule.patterns && + !rule.regex && rule.alwaysApply !== false ) { return true; @@ -176,18 +176,18 @@ const checkGlobsAndPatterns = ({ return false; } - // Now check for pattern matches in file contents if patterns are specified - if (rule.patterns) { - // Check if any of the matching files also match the content patterns + // Now check for pattern matches in file contents if regex are specified + if (rule.regex) { + // Check if any of the matching files also match the content regex return matchingFiles.some((filePath) => { const content = fileContents[filePath]; - // If we don't have the content, we can't check patterns + // If we don't have the content, we can't check regex if (!content) return false; - return contentMatchesPatterns(content, rule.patterns!); + return contentMatchesPatterns(content, rule.regex!); }); } - // If we have no patterns or if we couldn't check patterns (no content), + // If we have no regex or if we couldn't check regex (no content), // just go with the glob matches return matchingFiles.length > 0; }; @@ -248,11 +248,11 @@ export const shouldApplyRule = ( }); } - // If alwaysApply is explicitly false, we need to check globs and/or patterns + // If alwaysApply is explicitly false, we need to check globs and/or regex if ( rule.alwaysApply === false && rule.globs === undefined && - rule.patterns === undefined + rule.regex === undefined ) { return false; } diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 8425c8324..0b4444cd1 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -259,7 +259,7 @@ describe("Content pattern matching", () => { const reactComponentRule: RuleWithSource = { name: "React Component Rule", rule: "Follow React component standards", - patterns: "export (function|const) \\w+.*\\(", + regex: "export (function|const) \\w+.*\\(", source: "rules-block", ruleFile: "src/components/rules.md", }; @@ -286,12 +286,12 @@ describe("Content pattern matching", () => { ).toBe(false); }); - it("should support multiple regex patterns as an array", () => { - // Rule with multiple patterns + it("should support multiple regex regex as an array", () => { + // Rule with multiple regex const multiPatternRule: RuleWithSource = { name: "Multi-Pattern Rule", rule: "Apply to functions or classes", - patterns: ["function\\s+\\w+", "class\\s+\\w+"], + regex: ["function\\s+\\w+", "class\\s+\\w+"], source: "rules-block", ruleFile: "src/utils/rules.md", }; @@ -324,13 +324,13 @@ describe("Content pattern matching", () => { ).toBe(false); }); - it("should apply rules based on both globs and patterns when both are specified", () => { + it("should apply rules based on both globs and regex when both are specified", () => { // Rule with both glob and pattern restrictions const typescriptClassRule: RuleWithSource = { name: "TypeScript Class Rule", rule: "Follow class standards in TypeScript", globs: "**/*.ts", - patterns: "class\\s+\\w+", + regex: "class\\s+\\w+", source: "rules-block", ruleFile: "src/models/rules.md", }; @@ -369,7 +369,7 @@ describe("Content pattern matching", () => { const arrowFunctionRule: RuleWithSource = { name: "Arrow Function Rule", rule: "Use arrow functions for better this binding", - patterns: "const\\s+\\w+\\s*=\\s*\\(", + regex: "const\\s+\\w+\\s*=\\s*\\(", source: "rules-block", ruleFile: "src/utils/rules.md", }; @@ -426,12 +426,12 @@ describe("Content pattern matching", () => { expect(nonApplicableRules).toHaveLength(0); }); - it("should handle invalid regex patterns gracefully", () => { + it("should handle invalid regex regex gracefully", () => { // Rule with invalid regex pattern const invalidRegexRule: RuleWithSource = { name: "Invalid Regex Rule", rule: "This rule has an invalid regex pattern", - patterns: "([unclosed parenthesis", + regex: "([unclosed parenthesis", source: "rules-block", ruleFile: "src/utils/rules.md", }; @@ -452,7 +452,7 @@ describe("Content pattern matching", () => { const nestedPatternRule: RuleWithSource = { name: "Nested Pattern Rule", rule: "Apply only to model files with interfaces", - patterns: "interface\\s+\\w+", + regex: "interface\\s+\\w+", source: "rules-block", ruleFile: "src/models/rules.md", }; diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 2afb19d70..dfb6294ae 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -37,7 +37,7 @@ export const createRuleBlock: Tool = { description: "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])", }, - patterns: { + regex: { type: "string", description: "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)", diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index cfa60a5a3..06921f770 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -7,7 +7,7 @@ export type CreateRuleBlockArgs = Pick< Required, "rule" | "description" | "alwaysApply" | "name" > & - Pick; + Pick; export const createRuleBlockImpl: ToolImpl = async ( args: CreateRuleBlockArgs, @@ -19,9 +19,9 @@ export const createRuleBlockImpl: ToolImpl = async ( globs: args.globs, }; - // Add patterns if provided - if (args.patterns) { - options.patterns = args.patterns; + // Add regex if provided + if (args.regex) { + options.regex = args.regex; } const fileContent = createRuleMarkdown(args.name, args.rule, options); diff --git a/docs/docs/customize/deep-dives/rules.mdx b/docs/docs/customize/deep-dives/rules.mdx index 147606f85..bb0730afd 100644 --- a/docs/docs/customize/deep-dives/rules.mdx +++ b/docs/docs/customize/deep-dives/rules.mdx @@ -63,6 +63,7 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark - `name` (**required** for YAML): A display name/title for the rule - `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). +- `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`). - `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context. - `alwaysApply`: true - Always include the rule, regardless of file context - `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description diff --git a/packages/config-yaml/src/markdown/createMarkdownRule.ts b/packages/config-yaml/src/markdown/createMarkdownRule.ts index 13cce86f4..0fdf522f8 100644 --- a/packages/config-yaml/src/markdown/createMarkdownRule.ts +++ b/packages/config-yaml/src/markdown/createMarkdownRule.ts @@ -34,7 +34,7 @@ export function createRuleMarkdown( options: { description?: string; globs?: string | string[]; - patterns?: string | string[]; + regex?: string | string[]; alwaysApply?: boolean; } = {}, ): string { @@ -45,11 +45,9 @@ export function createRuleMarkdown( typeof options.globs === "string" ? options.globs.trim() : options.globs; } - if (options.patterns) { - frontmatter.patterns = - typeof options.patterns === "string" - ? options.patterns.trim() - : options.patterns; + if (options.regex) { + frontmatter.regex = + typeof options.regex === "string" ? options.regex.trim() : options.regex; } if (options.description) { diff --git a/packages/config-yaml/src/markdown/markdownToRule.ts b/packages/config-yaml/src/markdown/markdownToRule.ts index 5bed93ac8..85d5b3036 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.ts @@ -7,7 +7,7 @@ import { RuleObject } from "../schemas/index.js"; export interface RuleFrontmatter { globs?: RuleObject["globs"]; - patterns?: RuleObject["patterns"]; + regex?: RuleObject["regex"]; name?: RuleObject["name"]; description?: RuleObject["description"]; alwaysApply?: RuleObject["alwaysApply"]; @@ -57,7 +57,7 @@ export function markdownToRule( name: frontmatter.name ?? packageIdentifierToDisplayName(id), rule: markdown, globs: frontmatter.globs, - patterns: frontmatter.patterns, + regex: frontmatter.regex, description: frontmatter.description, alwaysApply: frontmatter.alwaysApply, }; diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 14d4a7486..7a0a6562b 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -45,7 +45,7 @@ const ruleObjectSchema = z.object({ rule: z.string(), description: z.string().optional(), globs: z.union([z.string(), z.array(z.string())]).optional(), - patterns: z.union([z.string(), z.array(z.string())]).optional(), + regex: z.union([z.string(), z.array(z.string())]).optional(), alwaysApply: z.boolean().optional(), }); const ruleSchema = z.union([z.string(), ruleObjectSchema]); From be7c31779971dc9402d80b710cbd1f822987eaac Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 23 Jun 2025 09:42:00 -0700 Subject: [PATCH 93/95] improv: naming --- core/llm/rules/getSystemMessageWithRules.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 65c04f2a6..c005a5f92 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -60,7 +60,7 @@ const matchesGlobs = ( * @param regex - A single regex pattern string or array of regex pattern strings * @returns true if the content matches any pattern (or if no regex is provided), false otherwise */ -const contentMatchesPatterns = ( +const contentMatchesRegex = ( fileContent: string, regex: string | string[], ): boolean => { @@ -158,7 +158,7 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { return false; }; -const checkGlobsAndPatterns = ({ +const checkGlobsAndRegex = ({ rule, filePaths, fileContents, @@ -183,7 +183,7 @@ const checkGlobsAndPatterns = ({ const content = fileContents[filePath]; // If we don't have the content, we can't check regex if (!content) return false; - return contentMatchesPatterns(content, rule.regex!); + return contentMatchesRegex(content, rule.regex!); }); } @@ -241,7 +241,7 @@ export const shouldApplyRule = ( isFileInDirectory(filePath, ruleDirPath), ); - return checkGlobsAndPatterns({ + return checkGlobsAndRegex({ filePaths: filesInRuleDirectory, fileContents, rule, @@ -257,7 +257,7 @@ export const shouldApplyRule = ( return false; } - return checkGlobsAndPatterns({ + return checkGlobsAndRegex({ filePaths, fileContents, rule, From b7119ddb64857d9eb518e9806a0fd7004b4bb992 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 23 Jun 2025 10:11:53 -0700 Subject: [PATCH 94/95] rules for vs code and navigating user requests --- .continue/rules/navigating-responses.md | 4 ++++ extensions/vscode/rules.md | 6 ++++++ 2 files changed, 10 insertions(+) create mode 100644 .continue/rules/navigating-responses.md create mode 100644 extensions/vscode/rules.md diff --git a/.continue/rules/navigating-responses.md b/.continue/rules/navigating-responses.md new file mode 100644 index 000000000..dadbd0f80 --- /dev/null +++ b/.continue/rules/navigating-responses.md @@ -0,0 +1,4 @@ +If the user's request is vague and you don't have enough information to confidently answer, you can either + +- In Chat OR Agent mode, stop and ask questions to clarify before proceeding +- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available. diff --git a/extensions/vscode/rules.md b/extensions/vscode/rules.md new file mode 100644 index 000000000..865f0dac5 --- /dev/null +++ b/extensions/vscode/rules.md @@ -0,0 +1,6 @@ +The `extensions/vscode` folder contains code for the "Continue" VS Code Extension. Continue is a coding assistant extension which extends IDE functionality with AI. +Core IDE functionality, such as reading files, is implemented using the `VSCodeIDE` class. Code to enable editing/diff streaming into the editor, code suggestion autocompletion, and more can also be found in this directory. +Shared code that has abstract logic for the extension is in `core/`. Avoid importing code from `core/` directly where possible. Core is designed to be bundalable as a binary. Use `core.invoke` to send messages to the + +- see `core/protocol/core.ts` for a list of commands VS Code can post/request to Core +- see `core/portocol/ide.ts` for a list of commands/message types core can post/request to VS Code From 393bf0854a7c9aa8e8d3f67cac8c93b2a7ee18b5 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 23 Jun 2025 11:15:51 -0700 Subject: [PATCH 95/95] nate's feedback --- .../AssistantAndOrgListbox/AccountOption.tsx | 11 ++++++- .../AssistantOptions.tsx | 2 +- .../OrganizationInfo.tsx | 22 -------------- .../AssistantAndOrgListbox/index.tsx | 30 ++++++++++++++----- 4 files changed, 34 insertions(+), 31 deletions(-) delete mode 100644 gui/src/components/AssistantAndOrgListbox/OrganizationInfo.tsx diff --git a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx b/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx index 8f4f8e11e..98e8adbc5 100644 --- a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx @@ -1,3 +1,7 @@ +import { + ArrowRightEndOnRectangleIcon, + UserCircleIcon as UserCircleIconOutline, +} from "@heroicons/react/24/outline"; import { isOnPremSession } from "core/control-plane/AuthTypes"; import { useAuth } from "../../context/Auth"; import { ListboxOption, useFontSize } from "../ui"; @@ -28,13 +32,18 @@ export function AccountOption({ onClose }: AccountOptionProps) {
+ {session ? ( + + ) : ( + + )} {session ? "Log out" : "Sign in"}
diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx index 304444b23..869aa5c67 100644 --- a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx @@ -19,7 +19,7 @@ export function AssistantOptions({ return ( <> {/* Assistants Section Header */} -
+
-
-
- - {!session && ( - (Signed out) - )} -
- -
-
- ); -} diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index ee175a725..dcf0bb4a4 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -1,4 +1,5 @@ import { PlusIcon } from "@heroicons/react/24/outline"; +import { isOnPremSession } from "core/control-plane/AuthTypes"; import { useContext, useEffect, useRef } from "react"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -18,7 +19,7 @@ import { } from "../ui"; import { AccountOption } from "./AccountOption"; import { AssistantOptions } from "./AssistantOptions"; -import { OrganizationInfo } from "./OrganizationInfo"; +import { ScopeSelect } from "./ScopeSelect"; import { SelectedAssistantButton } from "./SelectedAssistantButton"; export function AssistantAndOrgListbox() { @@ -27,9 +28,12 @@ export function AssistantAndOrgListbox() { const currentOrg = useAppSelector(selectCurrentOrg); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); - const { profiles, selectedProfile, session, login } = useAuth(); + const { profiles, selectedProfile, session, login, organizations } = + useAuth(); const smallFont = useFontSize(-3); const tinyFont = useFontSize(-4); + const shouldRenderOrgInfo = + session && organizations.length > 1 && !isOnPremSession(session); function close() { // Close the listbox by clicking outside or programmatically @@ -114,7 +118,19 @@ export function AssistantAndOrgListbox() { - + {shouldRenderOrgInfo && ( +
+
+ + {session.account.id} + + + +
+
+ )} login(false)} > -
- New Assistant -
+ New Assistant +