diff --git a/.continue/rules/documentation-standards.md b/.continue/rules/documentation-standards.md index a510b7ca7..4fa6984de 100644 --- a/.continue/rules/documentation-standards.md +++ b/.continue/rules/documentation-standards.md @@ -1,16 +1,111 @@ --- -globs: docs/**/*.{md,mdx} -description: Standards for writing and maintaining Continue Docs +globs: docs/\*_/_.{md,mdx} +description: This style guide should be used as a reference for maintaining consistency across all Continue documentation +alwaysApply: false --- -# Continue Docs Standards +# Continue Documentation Style Guide + +## Overview + +## Writing Tone & Voice + +### Conversational and Direct - Follow Docusaurus documentation standards -- Include YAML frontmatter with title, description, and keywords -- Use consistent heading hierarchy starting with h2 (##) -- Include relevant Admonition components for tips, warnings, and info -- Use descriptive alt text for images -- Include cross-references to related documentation -- Reference other docs with relative paths +- Use simple, conversational language that gets straight to the point +- Avoid overly technical jargon when simpler terms work +- Write as if speaking directly to the developer using the tool - Keep paragraphs concise and scannable -- Use code blocks with appropriate language tags + +**Example:** +✅ "You send it a question, and it replies with an answer" +❌ "The system processes user queries and generates corresponding responses" + +### Helpful and Instructional + +- Focus on helping users accomplish their goals +- Use active voice and imperative mood for instructions +- Assume users want to get things done quickly +- Include relevant Admonition components for tips, warnings, and info + +**Example:** +✅ "Press cmd/ctrl + L to begin a new session" +❌ "A new session can be initiated by pressing cmd/ctrl + L" + +### Practical and Task-Oriented + +- Emphasize what users can accomplish with each feature +- Lead with benefits and use cases before diving into mechanics +- Keep explanations grounded in real-world scenarios + +## Content Structure + +### Page Organization + +1. **Visual Introduction**: Lead with GIFs or images showing the feature in action +2. **Purpose Statement**: Brief explanation of what the feature does and when to use it +3. **Step-by-Step Instructions**: Clear, actionable steps with keyboard shortcuts +4. **Platform-Specific Notes**: Separate sections for VS Code and JetBrains when needed +5. **Additional Tips**: Advanced usage or troubleshooting notes + +### Section Headers + +- Use consistent heading hierarchy starting with h2 (##) +- Include YAML frontmatter with title, description, and keywords +- Use action-oriented headers that describe what users will do +- Format: "Verb + object" (e.g., "Type a request and press enter") +- Keep headers concise but descriptive +- Use title case + +**Examples:** +✅ "Highlight code and activate" +✅ "Accept or reject changes" +✅ "Switch between different models" + +### Lists and Steps + +- Use numbered lists for sequential steps +- Use bullet points for feature lists or options +- Keep list items parallel in structure +- Start action items with verbs + +## Technical Writing Standards + +### Code and Keyboard Shortcuts + +- Use `backticks` for inline code elements +- Format keyboard shortcuts consistently: `cmd/ctrl + L` +- Always provide shortcuts for Mac/Windows/Linux +- Use code blocks for configuration examples with proper syntax highlighting + +### Cross-References + +- Link to related sections using descriptive anchor text +- Use relative links to other documentation pages +- Format: `[descriptive text](/path/to/page)` + +### Platform Differences + +- Always address both VS Code and JetBrains when applicable +- Use clear subheadings to separate platform-specific instructions +- Lead with the more common platform (typically VS Code) when both are covered + +## Language Conventions + +### Terminology + +- **Consistent Terms**: Use the same terms throughout (e.g., "LLM" not "AI model" in some places) +- **Product Names**: Capitalize product names correctly (VS Code, JetBrains, Continue) +- **Feature Names**: Use consistent capitalization for Continue features (Chat, Edit, Agent, Autocomplete) + +### Abbreviations + +- Spell out acronyms on first use, then use abbreviation consistently +- Common abbreviations: LLM, IDE, API, URL + +### Pronouns + +- Use "you" to address the user directly +- Use "it" to refer to the tool/model +- Avoid "we" unless referring to the Continue team diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index e1e1078c5..326934314 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -439,7 +439,7 @@ jobs: GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} - AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} diff --git a/binary/package-lock.json b/binary/package-lock.json index f3c2cf2a9..ead2d8b83 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -20,6 +20,7 @@ "posthog-node": "^3.6.3", "system-ca": "^1.0.2", "tar": "^7.4.3", + "undici": "^7.10.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "win-ca": "^3.5.1" @@ -105,6 +106,7 @@ "sqlite3": "^5.1.7", "system-ca": "^1.0.3", "tar": "^7.4.3", + "tree-sitter-structured-text": "^0.0.1", "tree-sitter-wasms": "^0.1.11", "uuid": "^9.0.1", "vectordb": "^0.4.20", @@ -143,6 +145,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "tree-sitter-cli": "^0.22.5", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" @@ -6774,6 +6777,15 @@ "node": ">=8" } }, + "node_modules/undici": { + "version": "7.10.0", + "resolved": "https://registry.npmmirror.com/undici/-/undici-7.10.0.tgz", + "integrity": "sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/universal-user-agent": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", diff --git a/binary/package.json b/binary/package.json index 0e8949aa6..11161d67e 100644 --- a/binary/package.json +++ b/binary/package.json @@ -53,6 +53,7 @@ "posthog-node": "^3.6.3", "system-ca": "^1.0.2", "tar": "^7.4.3", + "undici": "^7.10.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "win-ca": "^3.5.1" diff --git a/binary/utils/ripgrep.js b/binary/utils/ripgrep.js index 9a26ebe26..725c4d8fe 100644 --- a/binary/utils/ripgrep.js +++ b/binary/utils/ripgrep.js @@ -4,6 +4,7 @@ const { rimrafSync } = require("rimraf"); const tar = require("tar"); const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets"); const AdmZip = require("adm-zip"); +const { ProxyAgent } = require("undici"); const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`; @@ -16,8 +17,13 @@ const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/downloa */ async function downloadFile(url, destPath) { // Use the built-in fetch API instead of node-fetch + // Use proxy if set in environment variables + const proxy = process.env.https_proxy || process.env.HTTPS_PROXY; + const agent = proxy ? new ProxyAgent(proxy) : undefined; + const response = await fetch(url, { redirect: "follow", // Automatically follow redirects + dispatcher: agent, }); if (!response.ok) { 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/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/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/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/core.ts b/core/core.ts index 4c79f18d1..5e8d4d060 100644 --- a/core/core.ts +++ b/core/core.ts @@ -42,12 +42,13 @@ import { IdeSettings, ModelDescription, RangeInFile, + ToolCall, type ContextItem, type ContextItemId, 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 { @@ -58,6 +59,7 @@ import { import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; +import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; @@ -67,7 +69,6 @@ import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; -import { StreamAbortManager } from "./util/abortManager"; import { getUriPathBasename } from "./util/uri"; const hasRulesFiles = (uris: string[]): boolean => { @@ -147,6 +148,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( @@ -512,6 +525,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, @@ -525,13 +543,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("onboarding/complete", this.handleCompleteOnboarding.bind(this)); @@ -738,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); @@ -800,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) { @@ -887,7 +909,12 @@ 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) || + BLOCK_TYPES.some( + (blockType) => + uri.includes(`.continue/${blockType}`) || + uri.includes(`.continue\\${blockType}`), + ) ) { await this.configHandler.reloadConfig(); } else if ( 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/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 0b4f6cc6b..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: @@ -88,7 +89,7 @@ export async function* getReplacementWithLlm( { role: "user", content: userPrompt }, { role: "assistant", content: assistantPrompt }, ], - new AbortController().signal, + abortController.signal, ); let lines = streamLines(completion); 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/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 ce78a8d82..d2792a228 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -781,9 +781,9 @@ export interface IDE { getPinnedFiles(): Promise; - getSearchResults(query: string): Promise; + getSearchResults(query: string, maxResults?: number): Promise; - getFileResults(pattern: string): Promise; + getFileResults(pattern: string, maxResults?: number): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; @@ -833,6 +833,7 @@ export interface ContinueSDK { config: ContinueConfig; fetch: FetchFunction; completionOptions?: LLMFullCompletionOptions; + abortController: AbortController; } export interface SlashCommand { @@ -1280,7 +1281,7 @@ export interface HighlightedCodePayload { } export interface AcceptOrRejectDiffPayload { - filepath: string; + filepath?: string; streamId?: string; } diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 9c6917dcb..d46dd2e3b 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -63,13 +63,12 @@ export async function* chunkDocument({ resolve({ ...chunkWithoutId, digest, - index, + index: index++, filepath, }); })(); }), ); - index++; } for await (const chunk of chunkPromises) { if (!chunk) { 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()) { diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index ae21e68ee..c3acdb211 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -161,12 +161,7 @@ function testLLM( group: "Hello", }, ], - toolChoice: { - type: "function", - function: { - name: "say_hello", - }, - }, + toolChoice: { type: "function", function: { name: "say_hello" } }, }, )) { const typedChunk = chunk as AssistantChatMessage; @@ -211,10 +206,7 @@ describe("LLM", () => { model: "claude-3-5-sonnet-latest", apiKey: process.env.ANTHROPIC_API_KEY, }), - { - skip: false, - testToolCall: true, - }, + { skip: false, testToolCall: true }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), { skip: false, @@ -240,12 +232,7 @@ describe("LLM", () => { apiKey: process.env.MISTRAL_API_KEY, model: "codestral-latest", }), - { - testFim: true, - skip: false, - testToolCall: true, - timeout: 60000, - }, + { testFim: true, skip: false, testToolCall: true, timeout: 60000 }, ); testLLM( new Azure({ @@ -260,11 +247,10 @@ describe("LLM", () => { ); testLLM( new Azure({ - apiKey: process.env.AZURE_FOUNDRY_API_KEY, - model: "codestral-latest", - apiBase: - "https://codestral-2501-continue-testing.eastus.models.ai.azure.com", - apiType: "azure-foundry", + apiKey: process.env.AZURE_FOUNDRY_CODESTRAL_API_KEY, + model: "Codestral-2501", + apiBase: "https://continue-foundry-resource.services.ai.azure.com", + env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" }, }), { testFim: false, skip: false, timeout: 20000 }, ); 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", + ); + }); +}); diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts index 0508a1e38..538ab03cf 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 'off' 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": "off", + }; + + // 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, + [globalRule], + [], + rulePolicies, + ); + + expect(applicableRules).toHaveLength(0); + expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule"); + }); }); diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index e83a2cbfc..a0f3cf64f 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 @@ -120,13 +121,21 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { export const shouldApplyRule = ( rule: RuleWithSource, filePaths: string[], + rulePolicies: RulePolicies = {}, ): boolean => { + const policy = rulePolicies[rule.name || ""]; + + // Never apply if policy is "off" + if (policy === "off") { + return false; + } + // If it's a global rule, always apply it regardless of file paths if (isGlobalRule(rule)) { 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) { @@ -196,11 +205,9 @@ 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)); - - // Get file paths from message and context for regular rule matching + // Get file paths from message and context for rule matching const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) : []; @@ -213,41 +220,34 @@ 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)); - - // Combine global rules with matching rules, ensuring no duplicates - return [...globalRules, ...matchingRules]; + return applicableRules; }; -/** - * 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/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 0e7bd39fe..f652d3a77 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,114 @@ 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 never apply rules with 'off' policy regardless of file paths", () => { + const rulePolicies: RulePolicies = { + "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 'off' 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 offPolicies: RulePolicies = { + "Always Apply Rule": "off", + }; + + expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe( + false, + ); + }); + + it("should apply 'on' policy rules based on normal matching logic", () => { + const rulePolicies: RulePolicies = { + "Components Rule": "on", + }; + + // 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", + }; + + // Off policy should override even global rules + const offPolicies: RulePolicies = { + "Root Rule": "off", + }; + + expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false); + + // On policy should maintain global rule behavior + const onPolicies: RulePolicies = { + "Root Rule": "on", + }; + + expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true); + }); + + it("should prioritize 'off' policy 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", + }; + + // Off policy should win over everything + const offPolicies: RulePolicies = { + "Complex Rule": "off", + }; + + // Even with matching files and alwaysApply: true, off policy wins + expect( + shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies), + ).toBe(false); + }); +}); diff --git a/core/llm/rules/types.ts b/core/llm/rules/types.ts new file mode 100644 index 000000000..f973d8260 --- /dev/null +++ b/core/llm/rules/types.ts @@ -0,0 +1,2 @@ +export type RulePolicy = "on" | "off"; +export type RulePolicies = { [ruleName: string]: RulePolicy }; diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 62c7cf38d..3f52a0192 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -85,6 +85,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 d9904d6d8..8e1478648 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -79,7 +79,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/core/protocol/ide.ts b/core/protocol/ide.ts index fda1b84fe..7a9b8d68e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -29,8 +29,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { openFile: [{ path: string }, void]; openUrl: [string, void]; runCommand: [{ command: string; options?: TerminalOptions }, void]; - getSearchResults: [{ query: string }, string]; - getFileResults: [{ pattern: 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]; fileExists: [{ filepath: string }, boolean]; 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..ba37c610d 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -159,11 +159,11 @@ 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) => { - return this.ide.getFileResults(data.pattern); + return this.ide.getFileResults(data.pattern, data.maxResults); }); this.on("getProblems", (data) => { 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/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/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; }; diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index a506be9cd..149b68a75 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,13 +1,44 @@ 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, + ); + 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/filesystem.ts b/core/util/filesystem.ts index 0bdaffbfd..8b50a3cae 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -234,11 +234,14 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - async getSearchResults(query: string): Promise { + async getSearchResults(query: string, maxResults?: number): Promise { return ""; } - async getFileResults(pattern: string): Promise { + async getFileResults( + pattern: string, + maxResults?: number, + ): Promise { return []; } diff --git a/core/util/grepSearch.ts b/core/util/grepSearch.ts index a30982e77..be5b7ee08 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) { @@ -45,6 +60,7 @@ export function formatGrepSearchResults(results: string): string { if (line.startsWith("./") || line === "--") { processResult(resultLines); // process previous result resultLines = [line]; + numResults++; continue; } @@ -57,5 +73,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, + }; + } } diff --git a/core/util/grepSearch.vitest.ts b/core/util/grepSearch.vitest.ts new file mode 100644 index 000000000..df1a71efd --- /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(13); // 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(3); + 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(" }"); +}); 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/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 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/docs/docs/customize/model-providers/top-level/anthropic.mdx b/docs/docs/customize/model-providers/top-level/anthropic.mdx index 8a33e8a35..4786c3719 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.mdx +++ b/docs/docs/customize/model-providers/top-level/anthropic.mdx @@ -31,7 +31,7 @@ We recommend configuring **Claude 4 Sonnet** as your chat model. { "title": "Claude 4 Sonnet", "provider": "anthropic", - "model": "claude-sonnet-4-20250514", + "model": "claude-sonnet-4-latest", "apiKey": "" } ] @@ -68,9 +68,6 @@ Prompt caching is generally available for: - Claude 3.7 Sonnet - Claude 3.5 Sonnet - Claude 3.5 Haiku -- Claude 3 Opus -- Claude 3 Sonnet -- Claude 3 Haiku To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows: @@ -84,9 +81,8 @@ To enable caching of the system message and the turn-by-turn conversation, updat apiKey: roles: - chat - cacheBehavior: - cacheSystemMessage: true - cacheConversation: true + defaultCompletionOptions: + promptCaching: true ``` @@ -100,7 +96,10 @@ To enable caching of the system message and the turn-by-turn conversation, updat }, "title": "Anthropic", "provider": "anthropic", - "model": "claude-sonnet-4-20250514", + "model": "claude-sonnet-4-latest", + "defaultCompletionOptions": { + "promptCaching": true + }, "apiKey": "" } ] diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index b2f511a64..4e873f0db 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -203,6 +203,14 @@ const config = { }, }), plugins: [ + [ + "posthog-docusaurus", + { + apiKey: process.env.POSTHOG_API_KEY || "DEV", + appUrl: "https://us.i.posthog.com", + enableInDevelopment: false, + }, + ], [ "@docusaurus/plugin-client-redirects", { diff --git a/docs/package-lock.json b/docs/package-lock.json index e96349847..f3a3ea446 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -14,6 +14,7 @@ "@docusaurus/preset-classic": "^3.7.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", + "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" @@ -14990,6 +14991,15 @@ "postcss": "^8.4.31" } }, + "node_modules/posthog-docusaurus": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/posthog-docusaurus/-/posthog-docusaurus-2.0.4.tgz", + "integrity": "sha512-xnEVCBovSuvQvYXGny03CDTc0yZCl7O3Mz21sJpXmE1Gvs21gM33WzWaA9Cm6WvWGYZtQy8t8/g8OjCkmTWlXA==", + "license": "MIT", + "engines": { + "node": ">=10.15.1" + } + }, "node_modules/pretty-error": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz", diff --git a/docs/package.json b/docs/package.json index 8f6ad8c95..67b995070 100644 --- a/docs/package.json +++ b/docs/package.json @@ -22,6 +22,7 @@ "@docusaurus/preset-classic": "^3.7.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", + "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index df6cebfe5..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.23 +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/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index 755b16d85..8cb05dc31 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -169,7 +169,11 @@ class ApplyToFileHandler( ide: IDE, params: ApplyToFileParams ) { - val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath) + val editorUtils = if (EditorUtils.editorFileExist(params.filepath)) + EditorUtils.getOrOpenEditor(project, params.filepath) + else + EditorUtils.getEditorByCreateFile(project, params.filepath) + val diffStreamService = project.getService(DiffStreamService::class.java) val handler = ApplyToFileHandler( 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..ddbb5f738 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) } @@ -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..a692759b9 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 @@ -344,11 +350,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 +363,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/editor/EditorUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt index 857c0104f..391c0423d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel @@ -14,6 +15,8 @@ import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.ui.JBColor import com.intellij.openapi.editor.ScrollType +import com.intellij.openapi.vfs.LocalFileSystem +import java.io.File /** * Utility class for working with Editor instances. @@ -166,5 +169,38 @@ class EditorUtils(val editor: Editor) { val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null return EditorUtils(editor) } + + /** + * Gets editor for the filepath is existed + */ + fun editorFileExist(filepath: String?): Boolean { + return !filepath.isNullOrEmpty() && VirtualFileManager.getInstance().findFileByUrl(filepath) != null + } + + /** + * Gets editor for the no exist filepath and returns an EditorUtils instance + */ + fun getEditorByCreateFile(project: Project, filepath: String?): EditorUtils? { + if (!filepath.isNullOrEmpty()) { + // file not exists and create + val ioFile = File(filepath.replace("file:///", "")) + if (!ioFile.exists()) { + ioFile.parentFile?.mkdirs() + ioFile.createNewFile() + } + // IntelliJ refresh VirtualFile + val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + runWriteAction { + FileEditorManager.getInstance(project).openFile(virtualFile, true) + } + } + } + } + + val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null + return EditorUtils(editor) + } } } 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..bf377e675 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,9 +21,9 @@ 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) +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..34b0e25d7 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,9 +157,9 @@ 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 + 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 @@ -239,7 +239,7 @@ data class StreamDiffLinesPayload( ) data class AcceptOrRejectDiffPayload( - val filepath: String, + val filepath: String? = null, val streamId: String? = null ) 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": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index e4fdccca3..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.48", + "version": "1.1.50", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index dcc17d179..a01ecd515 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,16 +517,24 @@ 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; + } } } - 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 +549,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 @@ -547,7 +558,20 @@ class VsCodeIde implements IDE { results.push(dirResults); } - return results.join("\n"); + const allResults = results.join("\n"); + if (maxResults) { + // 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 allResults; + } } async getProblems(fileUri?: string | undefined): Promise { diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index df5791335..fb446e174 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 { ApplyAbortManager } from "core/edit/applyAbortManager"; 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 = ApplyAbortManager.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) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 2162b1fca..82d045a01 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -28,6 +28,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"; @@ -86,56 +87,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, @@ -226,8 +177,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, @@ -235,10 +187,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, @@ -246,7 +200,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/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index b0c0a4d7b..5aff7056e 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -321,10 +321,10 @@ 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); + return ide.getFileResults(msg.data.pattern, msg.data.maxResults); }); this.onWebviewOrCore("subprocess", async (msg) => { return ide.subprocess(msg.data.command, msg.data.cwd); 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/components/ConversationStarters/index.ts b/gui/src/components/ConversationStarters/index.ts index 72b23e0b7..c7a6af018 100644 --- a/gui/src/components/ConversationStarters/index.ts +++ b/gui/src/components/ConversationStarters/index.ts @@ -1 +1 @@ -export * from "./ConversationStarterCards"; +export { ConversationStarterCards } from "./ConversationStarterCards"; diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index dbd5cabfe..a5792d721 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -7,12 +7,7 @@ import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; import { getFontSize, getMetaKeyLabel } from "../../util"; import { useMainEditor } from "../mainInput/TipTapEditor"; -import { - Listbox, - ListboxButton, - ListboxOption, - ListboxOptions, -} from "../ui/Listbox"; +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 index 04cc20156..82bc8634a 100644 --- a/gui/src/components/ModeSelect/index.ts +++ b/gui/src/components/ModeSelect/index.ts @@ -1 +1 @@ -export * from "./ModeSelect"; +export { ModeSelect } 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/index.ts b/gui/src/components/OnboardingCard/index.ts index 5a9a0c0d8..d3db336fe 100644 --- a/gui/src/components/OnboardingCard/index.ts +++ b/gui/src/components/OnboardingCard/index.ts @@ -1,3 +1,8 @@ -export * from "./OnboardingCard"; -export * from "./utils"; -export * from "./hooks/useOnboardingCard"; +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/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/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/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 0faf43e0e..02f404b54 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx @@ -1,24 +1,29 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../../redux/hooks"; +import { cancelStream } from "../../../../redux/thunks/cancelStream"; 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 ( - + { // 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 + void dispatch(cancelStream()); + ideMessenger.post("rejectDiff", {}); }} > {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} 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/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 3617ae632..1097805d2 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -16,10 +16,13 @@ import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { + DEFAULT_RULE_SETTING, setDialogMessage, setShowDialog, + toggleRuleSetting, } from "../../../../redux/slices/uiSlice"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; +import Switch from "../../../gui/Switch"; import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; @@ -31,6 +34,13 @@ const RuleCard: React.FC = ({ rule }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const mode = useAppSelector((store) => store.session.mode); + const policy = useAppSelector((state) => + rule.name + ? state.ui.ruleSettings[rule.name] || DEFAULT_RULE_SETTING + : undefined, + ); + + const isDisabled = policy === "off"; const handleOpen = async () => { if (rule.slug) { @@ -53,6 +63,12 @@ const RuleCard: React.FC = ({ rule }) => { } }; + const handleTogglePolicy = () => { + if (rule.name) { + dispatch(toggleRuleSetting(rule.name)); + } + }; + const title = useMemo(() => { if (rule.name) { return rule.name; @@ -90,31 +106,45 @@ const RuleCard: React.FC = ({ rule }) => { const smallFont = useFontSize(-2); const tinyFont = useFontSize(-3); return ( -
+
{title} -
- - - {" "} - {rule.source === "default-chat" || - rule.source === "default-agent" ? ( - - - - ) : ( - - - +
+ {rule.name && policy && ( +
+ handleTogglePolicy()} + size={10} + text="" + /> +
)} +
+ + + {" "} + {rule.source === "default-chat" || + rule.source === "default-agent" ? ( + + + + ) : ( + + + + )} +
@@ -122,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} @@ -134,7 +164,9 @@ const RuleCard: React.FC = ({ rule }) => { className="mt-1.5 flex flex-col gap-1" > Applies to files - + {rule.globs}
@@ -146,7 +178,6 @@ const RuleCard: React.FC = ({ rule }) => { export function RulesSection() { const { selectedProfile } = useAuth(); - const config = useAppSelector((store) => store.config.config); const mode = useAppSelector((store) => store.session.mode); const sortedRules: RuleWithSource[] = useMemo(() => { 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 index 717557fdc..77eae41bf 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -1,4 +1,4 @@ -export * from "./CodeBlock"; -export * from "./Mention"; -export * from "./Prompt"; -export * from "./SlashCommand"; +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 index b2d446398..613076b8b 100644 --- a/gui/src/components/mainInput/TipTapEditor/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/index.ts @@ -1,4 +1,3 @@ -export * from "./extensions"; -export * from "./MainEditorProvider"; -export * from "./TipTapEditor"; -export * from "./utils"; +export { MainEditorProvider, useMainEditor } from "./MainEditorProvider"; +export { TipTapEditor } from "./TipTapEditor"; +export { resolveEditorContent } from "./utils/resolveEditorContent"; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 774a95446..a759a5485 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,12 @@ 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, Mention, PromptBlock, SlashCommand } from "../extensions"; import { TipTapEditorProps } from "../TipTapEditor"; +import { + getContextProviderDropdownOptions, + getSlashCommandDropdownOptions, +} from "./getSuggestion"; import { handleImageFile } from "./imageUtils"; export function getPlaceholderText( @@ -52,9 +52,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 +304,7 @@ export function createEditorConfig(options: { }, }), Text, - ContinueExtensions.Mention.configure({ + Mention.configure({ suggestion: getContextProviderDropdownOptions( availableContextProvidersRef, getSubmenuContextItemsRef, @@ -317,7 +315,7 @@ export function createEditorConfig(options: { ideMessenger, ), }), - ContinueExtensions.SlashCommand.configure({ + SlashCommand.configure({ suggestion: getSlashCommandDropdownOptions( availableSlashCommandsRef, onClose, @@ -327,8 +325,8 @@ export function createEditorConfig(options: { props.inputId, ), }), - ContinueExtensions.PromptBlock, - ContinueExtensions.CodeBlock, + PromptBlock, + CodeBlock, ], editorProps: { attributes: { 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..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 * as ContinueExtensions from "../extensions"; +import { Mention } from "../extensions"; /** * 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/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/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/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index aebae2aa6..d360abce4 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -7,35 +7,34 @@ 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"; import { selectCurrentOrg, setSelectedOrgId, setSelectedProfile, -} from "../../../redux"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +} 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 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"; import AssistantIcon from "./AssistantIcon"; interface AssistantSelectOptionProps { profile: ProfileDescription; 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/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..a283ed969 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -3,13 +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"; -import { - initializeProfilePreferences, - setOrganizations, - setSelectedOrgId, - setSelectedProfile, -} from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; import { setConfigResult } from "../redux/slices/configSlice"; @@ -18,13 +11,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"; @@ -52,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/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..888488208 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, Popover, PopoverButton, PopoverPanel, Transition, } from "../../components/ui"; -import { Button } from "../../components/ui/Button"; 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/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.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(); + }); }); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6b2a6a364..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"; @@ -132,7 +132,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/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 580cbd3c0..356f8f9b3 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -14,11 +14,11 @@ 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/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, 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..15d6216a4 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 = "on" | "off"; + 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 = "on"; 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,25 @@ 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 "on": + state.ruleSettings[action.payload] = "off"; + break; + case "off": + state.ruleSettings[action.payload] = "on"; + break; + default: + state.ruleSettings[action.payload] = DEFAULT_RULE_SETTING; + break; + } + }, setTTSActive: (state, { payload }: PayloadAction) => { state.ttsActive = payload; }, @@ -142,6 +167,8 @@ export const { toggleToolSetting, toggleToolGroupSetting, addTool, + addRule, + toggleRuleSetting, setTTSActive, } = uiSlice.actions; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 1e0d098f3..542ee7ffc 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"; @@ -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", [ 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"; 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/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", { diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 4ca5c45f1..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 ?? []; diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 2737504fb..492e0eaa5 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.92", + "version": "1.0.93", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.92", + "version": "1.0.93", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index d243e17fc..07bd240ef 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.92", + "version": "1.0.94", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 92c51429e..1424b2aea 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -254,7 +254,7 @@ export async function unrollAssistantFromContent( options: UnrollAssistantOptions, ): Promise> { // Parse string to Zod-validated YAML - let parsedYaml = parseConfigYaml(rawYaml); + let parsedYaml = parseMarkdownRuleOrConfigYaml(rawYaml, id); // Unroll blocks and convert their secrets to FQSNs const { 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; diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 1d88a8b5e..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.36", + "version": "1.0.40", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.36", + "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 2b5043cfb..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.38", + "version": "1.0.40", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", 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, + }; } /**