diff --git a/.idea/scopes/Continue.xml b/.idea/scopes/Continue.xml index 3b28a76b1..d5943c932 100644 --- a/.idea/scopes/Continue.xml +++ b/.idea/scopes/Continue.xml @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 3daa2757e..85e94bbb2 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -56,7 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { return { source: "rules-block", rule: rule.rule, - if: rule.if, + globs: rule.globs, name: rule.name, }; } diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 38178e737..f88aeefc0 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -117,7 +117,6 @@ export async function* streamDiffLines({ ) as UserChatMessage | ToolResultChatMessage | undefined); const systemMessage = getSystemMessageWithRules({ - currentModel: llm.model, rules, userMessage: lastUserMessage, baseSystemMessage: undefined, diff --git a/core/index.d.ts b/core/index.d.ts index 877f308ae..b5cac75ae 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,8 @@ -import { DataDestination, ModelRole, PromptTemplates } from "@continuedev/config-yaml"; +import { + DataDestination, + ModelRole, + PromptTemplates, +} from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; @@ -1502,7 +1506,7 @@ export interface RuleWithSource { | "rules-block" | "json-systemMessage" | ".continuerules"; - if?: string; + globs?: string | string[]; rule: string; description?: string; ruleFile?: string; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 972d5d9e3..11701feb8 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -12,7 +12,7 @@ import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8"; + "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ @@ -58,14 +58,10 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ of changes unless the user specifically asks for code only. `; -const CANCELED_TOOL_CALL_MESSAGE = - "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; - export function constructMessages( history: ChatHistoryItem[], baseChatSystemMessage: string | undefined, rules: RuleWithSource[], - modelName: string, ): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", @@ -107,8 +103,8 @@ export function constructMessages( baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, rules, userMessage: lastUserMsg, - currentModel: modelName, }); + if (systemMessage.trim()) { msgs.unshift({ role: "system", diff --git a/core/llm/rules/getSystemMessageWithRules.test.ts b/core/llm/rules/getSystemMessageWithRules.test.ts new file mode 100644 index 000000000..c1a7765ee --- /dev/null +++ b/core/llm/rules/getSystemMessageWithRules.test.ts @@ -0,0 +1,201 @@ +import { RuleWithSource, UserChatMessage } from "../.."; +import { getSystemMessageWithRules } from "./getSystemMessageWithRules"; + +describe("getSystemMessageWithRules", () => { + const baseSystemMessage = "Base system message"; + const tsRule: RuleWithSource = { + name: "TypeScript Rule", + rule: "Follow TypeScript best practices", + globs: "**/*.ts?(x)", + source: "rules-block", + }; + + // Rule without pattern (always active) + const generalRule: RuleWithSource = { + name: "General Rule", + rule: "Always write clear comments", + source: "rules-block", + }; + + // Rule with a different pattern + const pythonRule: RuleWithSource = { + name: "Python Rule", + rule: "Follow PEP 8 guidelines", + globs: "**/*.py", + source: "rules-block", + }; + + it("should not include pattern-matched rules when no file paths are mentioned", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [tsRule], + }); + + expect(result).toBe(baseSystemMessage); + }); + + it("should include general rules (without matches) regardless of file paths", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [generalRule], + }); + + expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`); + }); + + it("should include only matching rules based on file paths", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```tsx Component.tsx\nexport const Component = () =>
Hello
;\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + }); + + // Should include TS rule and general rule, but not Python rule + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include multiple matching rules", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```tsx Component.tsx\nexport const Component = () =>
Hello
;\n```\n```python test.py\nprint('hello')\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + }); + + // Should include all rules + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include only general rules when no paths match pattern-specific rules", () => { + const userMessage: UserChatMessage = { + role: "user", + content: "```ruby test.rb\nputs 'hello'\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + }); + + // Should only include the general rule + const expected = `${baseSystemMessage}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should NOT match with comma-separated glob patterns", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```", + }; + + // Rule with comma-separated glob patterns + const commaRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for comma-separated globs", + globs: "src/**/*.ts, tests/**/*.ts", + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [commaRule], + }); + + // With the current implementation, the comma-separated pattern is treated as a single string, + // so it won't match any of the file paths (minimatch doesn't support comma-separated patterns) + expect(result).toBe(baseSystemMessage); + }); + + it("should match with an array of glob patterns", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```\n```ts config/settings.ts\nconst config = {};\n```", + }; + + // Rule with an array of glob patterns + const arrayGlobRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for array globs", + globs: ["src/**/*.ts", "tests/**/*.ts"], + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [arrayGlobRule], + }); + + // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts + expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`); + }); + + it("should match only patterns in the array", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts src/main.ts\nconsole.log('hello');\n```\n```ts config/settings.ts\nconst config = {};\n```", + }; + + // Rule with an array of glob patterns + const arrayGlobRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for array globs", + globs: ["src/**/*.ts", "tests/**/*.ts"], + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [arrayGlobRule], + }); + + // Should match src/main.ts but not config/settings.ts + expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`); + }); + + it("should not match any when no patterns in the array match", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts config/settings.ts\nconst config = {};\n```\n```ruby test.rb\nputs 'hello'\n```", + }; + + // Rule with an array of glob patterns + const arrayGlobRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for array globs", + globs: ["src/**/*.ts", "tests/**/*.ts"], + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [arrayGlobRule], + }); + + // Should not match any file paths + expect(result).toBe(baseSystemMessage); + }); +}); diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 6f3d48583..dacd941bb 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -1,32 +1,52 @@ +import { minimatch } from "minimatch"; import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; -import { isRuleActive } from "./isRuleActive"; + +/** + * Checks if a path matches any of the provided globs + */ +const matchesGlobs = ( + path: string, + globs: string | string[] | undefined, +): boolean => { + if (!globs) return true; + + if (typeof globs === "string") { + return minimatch(path, globs); + } + + if (Array.isArray(globs)) { + return globs.some((glob) => minimatch(path, glob)); + } + + return false; +}; export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, rules, - currentModel, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; rules: RuleWithSource[]; - currentModel: string; }) => { const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) : []; let systemMessage = baseSystemMessage ?? ""; + for (const rule of rules) { - if ( - isRuleActive({ - rule, - activePaths: filePathsFromMessage, - currentModel, - }) - ) { + // A rule is active if it has no globs (applies to all files) + // or if at least one file path matches its globs + const hasNoGlobs = !rule.globs; + const matchesAnyFilePath = filePathsFromMessage.some((path) => + matchesGlobs(path, rule.globs), + ); + + if (hasNoGlobs || matchesAnyFilePath) { systemMessage += `\n\n${rule.rule}`; } } diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts deleted file mode 100644 index 89e06e148..000000000 --- a/core/llm/rules/isRuleActive.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { RuleWithSource } from "../.."; -import { isRuleActive } from "./isRuleActive"; - -describe("isRuleActive", () => { - const rule: RuleWithSource = { - name: "My Rule", - rule: "Do no harm", - if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', - source: "rules-block", - }; - - it("should return false when activePaths is empty", () => { - expect( - isRuleActive({ - rule, - activePaths: [], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(false); - }); - - it("should return false when no matching paths exist", () => { - expect( - isRuleActive({ - rule, - activePaths: ["test.py", "main.js"], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(false); - }); - - it("should return true when both conditions are met", () => { - expect( - isRuleActive({ - rule, - activePaths: ["Component.tsx", "main.js"], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(true); - }); - - it("should return false when only glob matches but model doesn't", () => { - expect( - isRuleActive({ - rule, - activePaths: ["Component.tsx"], - currentModel: "gpt-4", - }), - ).toBe(false); - }); - - it("should return false when model matches but glob doesn't", () => { - expect( - isRuleActive({ - rule, - activePaths: ["Component.ts"], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(false); - }); -}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts deleted file mode 100644 index 9c80f67ec..000000000 --- a/core/llm/rules/isRuleActive.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { compileExpression } from "filtrex"; -import { minimatch } from "minimatch"; -import { RuleWithSource } from "../.."; - -const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; - -const createGlobFunction = (activePaths: string[]) => { - return (pattern: string) => { - const result = activePaths.some((path) => minimatch(path, pattern)); - return result; - }; -}; - -const contains = (str: string, searchStr: string): boolean => { - return str.includes(searchStr); -}; - -const evaluateIf = ({ - condition, - activePaths, - currentModel, -}: { - condition: string; - activePaths: string[]; - currentModel: string; -}) => { - const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); - if (!expression) { - return true; - } - - try { - const evaluate = compileExpression(expression, { - extraFunctions: { - glob: createGlobFunction(activePaths), - contains, - }, - constants: { - "current.model.model": currentModel, - }, - }); - - return evaluate({}); - } catch (error) { - console.error("Error evaluating rule condition:", error); - return false; - } -}; - -export const isRuleActive = ({ - rule, - activePaths, - currentModel, -}: { - rule: RuleWithSource; - activePaths: string[]; - currentModel: string; -}): boolean => { - if (rule.if) { - return evaluateIf({ condition: rule.if, activePaths, currentModel }); - } - - return true; -}; diff --git a/docs/docs/blocks/context-providers.md b/docs/docs/blocks/context-providers.md new file mode 100644 index 000000000..918ff3961 --- /dev/null +++ b/docs/docs/blocks/context-providers.md @@ -0,0 +1,21 @@ +--- +title: Context Blocks +sidebar_label: Context +description: Determine what internal information your AI assistant can access +keywords: [context, blocks, repositories, integration, knowledge base] +sidebar_position: 2 +--- + +These blocks determine what internal information your AI assistant can access: + +- **Connect to source repositories** and issues, CI/CD systems, wikis, and knowledge bases +- **Determine the scope** of what the AI can "see" when providing assistance +- **Customize** to match your specific development environment +- **Include proprietary code patterns** unique to your organization +- **Integrate data sources** to connect to any internal system with valuable context + +![Context Blocks Overview](/img/context-blocks-overview.png) + +## Learn More + +Learn more about context providers [here](../reference.md#context), and check out [this guide](../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. diff --git a/docs/docs/blocks/data.md b/docs/docs/blocks/data.md new file mode 100644 index 000000000..6e38e35e8 --- /dev/null +++ b/docs/docs/blocks/data.md @@ -0,0 +1,20 @@ +--- +title: Data Blocks +sidebar_label: Data +description: Help organizations capture and analyze AI assistant usage data +keywords: [data, blocks, analytics, metrics, storage, compliance] +sidebar_position: 7 +--- + +These help organizations capture and analyze AI assistant usage data: + +- **Analytics Integration**: Export metrics to observability platforms like Splunk or New Relic +- **Cloud Storage**: Store development data in S3/Azure Blob for model fine-tuning and auditing +- **Impact Measurement**: Track acceptance rates and productivity outcomes for ROI calculation +- **Compliance Reporting**: Generate audit trails for security and governance requirements + +![Data Blocks Overview](/img/data-blocks-overview.png) + +## Learn More + +You can read more about development data [here](../customize/deep-dives/development-data.md). Data destinations are configured in the [`data`](../reference.md#data) section of `config.yaml`. diff --git a/docs/docs/blocks/docs.md b/docs/docs/blocks/docs.md new file mode 100644 index 000000000..304a8c474 --- /dev/null +++ b/docs/docs/blocks/docs.md @@ -0,0 +1,19 @@ +--- +title: Docs Blocks +sidebar_label: Docs +description: Bring your documentation directly into the IDE +keywords: [docs, blocks, documentation, guidance, flow] +sidebar_position: 3 +--- + +This is how Continue brings your documentation directly into the IDE: + +- **Provide just-in-time guidance** without context switching +- **Reduce support burden** by making information discoverable +- **Keep developers in flow** by eliminating searches through multiple systems + +![Docs Blocks Overview](/img/docs-blocks-overview.png) + +## Learn More + +Learn more in the [@Docs deep dive](../customize/deep-dives/docs.mdx), and view [`docs`](../reference.md#docs) in the YAML Reference for more details. diff --git a/docs/docs/blocks/mcp.md b/docs/docs/blocks/mcp.md new file mode 100644 index 000000000..7201c4ac1 --- /dev/null +++ b/docs/docs/blocks/mcp.md @@ -0,0 +1,44 @@ +--- +title: MCP Blocks +--- + +title: MCP Blocks +sidebar_label: MCP +description: Model Context Protocol servers provide specialized functionality +keywords: [mcp, blocks, model context protocol, integrations, tools] +sidebar_position: 4 + +--- + +Model Context Protocol servers provide specialized functionality: + +- **Enable integration** with external tools and systems +- **Create extensible interfaces** for custom capabilities +- **Support complex interactions** with your development environment +- **Allow partners** to contribute specialized functionality +- **Connect to databases** to understand schema and data models during development + +![MCP Blocks Overview](/img/mcp-blocks-overview.png) + +## Learn More + +Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details. +description: Model Context Protocol servers provide specialized functionality +keywords: [mcp, blocks, model context protocol, integrations, tools] +sidebar_position: 4 + +--- + +Model Context Protocol servers provide specialized functionality: + +- Enable integration with external tools and systems +- Create extensible interfaces for custom capabilities +- Support more complex interactions with your development environment +- Allow partners to contribute specialized functionality +- Database Connectors: Understand schema and data models during development + +![MCP Blocks Overview](/img/mcp-blocks-overview.png) + +## Learn More + +Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details. diff --git a/docs/docs/blocks/models.md b/docs/docs/blocks/models.md new file mode 100644 index 000000000..bcf78be02 --- /dev/null +++ b/docs/docs/blocks/models.md @@ -0,0 +1,24 @@ +--- +title: Model Blocks +sidebar_label: Model +description: Foundation of the entire assistant experience offering specialized capabilities +keywords: [model, blocks, chat, edit, apply, autocomplete, embedding, reranker] +sidebar_position: 1 +--- + +These blocks form the foundation of the entire assistant experience, offering different specialized capabilities: + +- **[Chat](../customize/model-roles/chat.mdx)**: Power conversational interactions about code and provide detailed guidance +- **[Edit](../customize/model-roles/edit.mdx)**: Handle complex code transformations and refactoring tasks +- **[Apply](../customize/model-roles/apply.mdx)**: Execute targeted code modifications with high accuracy +- **[Autocomplete](../customize/model-roles/autocomplete.md)**: Provide real-time suggestions as developers type +- **[Embedding](../customize/model-roles/embeddings.mdx)**: Transform code into vector representations for semantic search +- **[Reranker](../customize/model-roles/reranking.mdx)**: Improve search relevance by ordering results based on semantic meaning + +![Model Blocks Overview](/img/model-blocks-overview.png) + +## Learn More + +Continue supports [many model providers](../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. + +Read more about roles [here](../customize/model-roles/intro.mdx) and view [`models`](../reference.md#models) in the YAML Reference. diff --git a/docs/docs/blocks/prompts.md b/docs/docs/blocks/prompts.md new file mode 100644 index 000000000..07cc9fb53 --- /dev/null +++ b/docs/docs/blocks/prompts.md @@ -0,0 +1,21 @@ +--- +title: Prompt Blocks +sidebar_label: Prompt +description: Specialized instructions that shape how models respond +keywords: [prompts, blocks, instructions, guidance, code review] +sidebar_position: 6 +--- + +These are the specialized instructions that shape how models respond: + +- **Define interaction patterns** for specific tasks or frameworks +- **Encode domain expertise** for particular technologies +- **Ensure consistent guidance** aligned with organizational practices +- **Can be shared and reused** across multiple assistants +- **Act as automated code reviewers** that ensure consistency across teams + +![Prompt Blocks Overview](/img/prompts-blocks-overview.png) + +## Learn More + +Prompt blocks have the same syntax as [prompt files](../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../reference.md#prompts). diff --git a/docs/docs/blocks/rules.md b/docs/docs/blocks/rules.md new file mode 100644 index 000000000..bc1baaf4b --- /dev/null +++ b/docs/docs/blocks/rules.md @@ -0,0 +1,19 @@ +--- +title: Rules Blocks +sidebar_label: Rules +description: Guardrails for your AI coding assistants +keywords: [rules, blocks, standards, practices, guardrails] +sidebar_position: 5 +--- + +Think of these as the guardrails for your AI coding assistants: + +- **Enforce company-specific coding standards** and security practices +- **Implement quality checks** that match your engineering culture +- **Create paved paths** for developers to follow organizational best practices + +![Rules Blocks Overview](/img/rules-blocks-overview.png) + +## Learn More + +Learn more in the [rules deep dive](../customize/deep-dives/rules.md), and view [`rules`](../reference.md#rules) in the YAML Reference for more details. diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index c6c87ae7a..ec30bb46e 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -17,12 +17,14 @@ Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editi Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: -To open `config.yaml`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open Assistant configuration` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. - - `~/.continue/config.yaml` (MacOS / Linux) - `%USERPROFILE%\.continue\config.yaml` (Windows) -When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. +To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`. + +![local-config-open-steps](/img/local-config-open-steps.png) + +When editing this file, you can see the available options suggested as you type, or check the reference below. When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. See the full reference for `config.yaml` [here](../../reference.md). diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 94dec8a07..27a1e61a9 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -7,7 +7,7 @@ keywords: [rules, .continuerules, system, prompt, message] Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. -Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). +Rules are not included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). You can view the current rules by clicking the pen icon above the main toolbar: @@ -25,22 +25,31 @@ When in Agent mode, you can simply prompt the agent to create a rule for you. For example, you can say "Create a rule for this", and a rule will be created for you in `~/.continue/rules` based on your conversation. ::: +### Syntax + Rules blocks can be simple text, or have the following properties: - `name` (**required**): A display name/title for the rule - `rule` (**required**): The text content of the rule - -Examples: +- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). ```yaml title="config.yaml" rules: + - Always annotate Python functions with their parameter and return types + + - name: TypeScript best practices + rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly. + globs: "**/*.{ts,tsx}" + + - name: TypeScript test patterns + rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking. + globs: + - "src/**/*.test.ts" + - "tests/**/*.ts" + - uses: myprofile/my-mood-setter with: - TONE: consise - - Always annotate Python functions with their parameter and return types - - Always write Google style docstrings for functions and classes - - name: Server-side components - rule: When writing Next.js React components, use server-side components where possible instead of client components. + TONE: concise ``` ## Chat System Message diff --git a/docs/docs/reference.md b/docs/docs/reference.md index ca794416a..dd8f7bc3b 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b ### Using Blocks -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from https://hub.continue.dev. +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev). Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. @@ -270,19 +270,25 @@ Explicit rules can either be simple text or an object with the following propert - `name` (**required**): A display name/title for the rule - `rule` (**required**): The text content of the rule - - -Example +- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). ```yaml title="config.yaml" rules: + - Always annotate Python functions with their parameter and return types + + - name: TypeScript best practices + rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly. + globs: "**/*.{ts,tsx}" + + - name: TypeScript test patterns + rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking. + globs: + - "src/**/*.test.ts" + - "tests/**/*.ts" + - uses: myprofile/my-mood-setter with: TONE: concise - - Always annotate Python functions with their parameter and return types - - Always write Google style docstrings for functions and classes - - name: Server-side components - rule: When writing Next.js React components, use server-side components where possible instead of client components. ``` --- diff --git a/docs/sidebars.js b/docs/sidebars.js index 1a634d163..89bfb71bd 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -55,6 +55,16 @@ const sidebars = { }, ], }, + { + type: "category", + label: "Blocks", + items: [ + { + type: "autogenerated", + dirName: "blocks", + }, + ], + }, "telemetry", "troubleshooting", { diff --git a/docs/static/img/context-blocks-overview.png b/docs/static/img/context-blocks-overview.png new file mode 100644 index 000000000..2db89de89 Binary files /dev/null and b/docs/static/img/context-blocks-overview.png differ diff --git a/docs/static/img/data-blocks-overview.png b/docs/static/img/data-blocks-overview.png new file mode 100644 index 000000000..dc7ec288e Binary files /dev/null and b/docs/static/img/data-blocks-overview.png differ diff --git a/docs/static/img/docs-blocks-overview.png b/docs/static/img/docs-blocks-overview.png new file mode 100644 index 000000000..ac7876784 Binary files /dev/null and b/docs/static/img/docs-blocks-overview.png differ diff --git a/docs/static/img/local-config-open-steps.png b/docs/static/img/local-config-open-steps.png new file mode 100644 index 000000000..07b27c976 Binary files /dev/null and b/docs/static/img/local-config-open-steps.png differ diff --git a/docs/static/img/mcp-blocks-overview.png b/docs/static/img/mcp-blocks-overview.png new file mode 100644 index 000000000..0967ee831 Binary files /dev/null and b/docs/static/img/mcp-blocks-overview.png differ diff --git a/docs/static/img/model-blocks-overview.png b/docs/static/img/model-blocks-overview.png new file mode 100644 index 000000000..56e139a29 Binary files /dev/null and b/docs/static/img/model-blocks-overview.png differ diff --git a/docs/static/img/prompts-blocks-overview.png b/docs/static/img/prompts-blocks-overview.png new file mode 100644 index 000000000..109f58654 Binary files /dev/null and b/docs/static/img/prompts-blocks-overview.png differ diff --git a/docs/static/img/rules-blocks-overview.png b/docs/static/img/rules-blocks-overview.png new file mode 100644 index 000000000..7864c8d6b Binary files /dev/null and b/docs/static/img/rules-blocks-overview.png differ 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 677d0bd84..031783597 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 @@ -432,6 +432,25 @@ class IdeProtocolClient( } } + "acceptDiff" -> { + val params = Gson().fromJson( + dataElement.toString(), + AcceptDiffParams::class.java + ) + val filepath = params.filepath; + + acceptOrRejectDiff(filepath, true) + } + + "rejectDiff" -> { + val params = Gson().fromJson( + dataElement.toString(), + RejectDiffParams::class.java + ) + val filepath = params.filepath; + acceptOrRejectDiff(filepath, false) + } + "applyToFile" -> { val params = Gson().fromJson( dataElement.toString(), @@ -648,6 +667,29 @@ class IdeProtocolClient( continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid()) } + fun acceptOrRejectDiff(filepath: String, accepted: Boolean) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + val openedEditor = + FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() + if (openedEditor != null) { + val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor + + if (editor != null) { + val diffStreamService = project.service() + if (accepted) { + diffStreamService.accept(editor) + } else { + diffStreamService.reject(editor) + } + } + } + } + } + } + fun deleteAtIndex(index: Int) { continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid()) } 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 41bcc2941..afd3f8b1c 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 @@ -42,7 +42,7 @@ class IntelliJIDE( private val project: Project, private val continuePluginService: ContinuePluginService, -) : IDE { + ) : IDE { private val gitService = GitService(project, continuePluginService) @@ -57,6 +57,19 @@ class IntelliJIDE( val os = getOS() ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString() + + // Make ripgrep executable if on Unix-like systems + try { + if (os == OS.LINUX || os == OS.MAC) { + val file = File(ripgrep) + if (!file.canExecute()) { + file.setExecutable(true) + } + } + } catch (e: Throwable) { + e.printStackTrace() + } + } /** @@ -179,6 +192,7 @@ class IntelliJIDE( override suspend fun writeFile(path: String, contents: String) { val file = File(URI(path)) + file.parentFile?.mkdirs() file.writeText(contents) } @@ -194,7 +208,13 @@ class IntelliJIDE( } override suspend fun openFile(path: String) { - val file = LocalFileSystem.getInstance().findFileByPath(URI(path).path) + // Convert URI path to absolute file path + val filePath = File(URI(path)).absolutePath + // Find the file using the absolute path + val file = withContext(Dispatchers.IO) { + LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath) + } + file?.let { ApplicationManager.getApplication().invokeLater { FileEditorManager.getInstance(project).openFile(it, true) @@ -311,7 +331,7 @@ class IntelliJIDE( val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { val command = GeneralCommandLine( - ripgrep, + ripgrep, "--files", "--iglob", pattern, @@ -320,37 +340,37 @@ class IntelliJIDE( "--ignore-file", ".gitignore", ) - + command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout return results.split("\n") } else { - throw NotImplementedError("Ripgrep not supported, this workspace is remote") + throw NotImplementedError("Ripgrep not supported, this workspace is remote") - // Leaving in here for ideas - // val projectBasePath = project.basePath ?: return emptyList() - // val scope = GlobalSearchScope.projectScope(project) - // - // // Get all ignore patterns from .continueignore files - // val ignorePatterns = mutableSetOf() - // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> - // VfsUtil.collectChildrenRecursively(root).forEach { file -> - // if (file.name == ".continueignore") { - // file.inputStream.bufferedReader().useLines { lines -> - // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) - // } - // } - // } - // } - // - // return FilenameIndex.getAllFilesByExt(project, "*", scope) - // .filter { file -> - // val relativePath = file.path.removePrefix("$projectBasePath/") - // // Check if file matches pattern and isn't ignored - // PatternUtil.(relativePath, pattern) && - // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } - // } - // .map { it.path.removePrefix("$projectBasePath/") } + // Leaving in here for ideas + // val projectBasePath = project.basePath ?: return emptyList() + // val scope = GlobalSearchScope.projectScope(project) + // + // // Get all ignore patterns from .continueignore files + // val ignorePatterns = mutableSetOf() + // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> + // VfsUtil.collectChildrenRecursively(root).forEach { file -> + // if (file.name == ".continueignore") { + // file.inputStream.bufferedReader().useLines { lines -> + // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) + // } + // } + // } + // } + // + // return FilenameIndex.getAllFilesByExt(project, "*", scope) + // .filter { file -> + // val relativePath = file.path.removePrefix("$projectBasePath/") + // // Check if file matches pattern and isn't ignored + // PatternUtil.(relativePath, pattern) && + // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } + // } + // .map { it.path.removePrefix("$projectBasePath/") } } } @@ -358,20 +378,20 @@ class IntelliJIDE( val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { val command = GeneralCommandLine( - ripgrep, - "-i", + ripgrep, + "-i", "--ignore-file", ".continueignore", "--ignore-file", - ".gitignore", - "-C", - "2", - "--heading", - "-e", - query, + ".gitignore", + "-C", + "2", + "--heading", + "-e", + query, "." ) - + command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout } else { @@ -415,7 +435,7 @@ class IntelliJIDE( // return searchResults.toString() } } - + override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 718755a99..b875f744c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -15,6 +15,16 @@ data class ApplyToFileParams( val toolCallId: String? ) +data class AcceptDiffParams( + val filepath: String, + val streamId: String +) + +data class RejectDiffParams( + val filepath: String, + val streamId: String +) + data class InsertAtCursorParams( val text: String ) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 012651f84..079e05660 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.25", + "version": "1.1.26", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/package-lock.json b/gui/package-lock.json index 3f934ca59..765d4d78a 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -4364,9 +4364,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001662", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001662.tgz", - "integrity": "sha512-sgMUVwLmGseH8ZIrm1d51UbrhqMCH3jvS7gF/M6byuHOnKyLOBL7W8yz5V02OHwgLGA36o/AFhWzzh4uc5aqTA==", + "version": "1.0.30001715", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001715.tgz", + "integrity": "sha512-7ptkFGMm2OAOgvZpwgA4yjQ5SQbrNVGdRjzH0pBdy1Fasvcr+KAeECmbCAECzTuDuoX0FCY8KzUxjf9+9kfZEw==", "funding": [ { "type": "opencollective", @@ -4380,7 +4380,8 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ] + ], + "license": "CC-BY-4.0" }, "node_modules/ccount": { "version": "2.0.1", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 15082d35b..2f3a94dd8 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -45,7 +45,7 @@ const router = createMemoryRouter([ Prevents entire app from rerendering continuously with useSetup in App TODO - look into a more redux-esque way to do this */ -function SetupListeners() { +export function SetupListeners() { useSetup(); return <>; } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index a50c953f4..6154b3452 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -2,6 +2,7 @@ import { CommandLineIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { lightGray, vscForeground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { isJetBrains } from "../../../util"; interface RunInTerminalButtonProps { command: string; @@ -10,16 +11,21 @@ interface RunInTerminalButtonProps { export function RunInTerminalButton({ command }: RunInTerminalButtonProps) { const ideMessenger = useContext(IdeMessengerContext); + if (isJetBrains()) { + // JetBrains plugin doesn't currently have a way to run the command in the terminal for the user + return null; + } + // Extract just the command line (the line after $ or the first line) function extractCommand(cmd: string): string { // If the command contains a $ prompt, extract the line after it - if (cmd.includes('$')) { + if (cmd.includes("$")) { const match = cmd.match(/\$\s*([^\n]+)/); - return match ? match[1].trim() : ''; + return match ? match[1].trim() : ""; } - + // Otherwise, just take the first line - return cmd.split('\n')[0].trim(); + return cmd.split("\n")[0].trim(); } function runInTerminal() { diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index 7f6874aeb..fd174f59c 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -11,9 +11,7 @@ import { useRef, useState, } from "react"; -import { useSelector } from "react-redux"; import { HeaderButton, Input } from ".."; -import { RootState } from "../../redux/store"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { useAppSelector } from "../../redux/hooks"; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 1bcbb3c8c..457aefd44 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -114,7 +114,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) { : {}; return ( -
+
{props.isMainInput && } state.ui.ttsActive); const isStreaming = useAppSelector((state) => state.session.isStreaming); + const jetbrains = isJetBrains(); const toolCallState = useSelector(selectCurrentToolCall); const handleKeyDown = (event: KeyboardEvent) => { if (toolCallState?.status === "generated") { const metaKey = event.metaKey || event.ctrlKey; + const altKey = event.altKey; if (metaKey && event.key === "Enter") { event.preventDefault(); event.stopPropagation(); dispatch(callCurrentTool()); - } else if (metaKey && event.key === "Backspace") { + } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { event.preventDefault(); event.stopPropagation(); dispatch(cancelCurrentToolCall()); @@ -92,7 +99,8 @@ export function LumpToolbar() { dispatch(cancelStream()); }} > - {getMetaKeyLabel()} ⌫ Cancel + {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel ); @@ -109,7 +117,8 @@ export function LumpToolbar() { onClick={() => dispatch(cancelCurrentToolCall())} data-testid="reject-tool-call-button" > - {getMetaKeyLabel()} ⌫ Cancel + {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel -
+
= ({ rule }) => { > {rule.rule} - {rule.if ? ( + {rule.globs ? (
- Applies if + Applies to files - {rule.if.replace(/\${{|}}/g, "")} + {rule.globs}
) : null} diff --git a/gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx b/gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx index dbd72de65..89a243871 100644 --- a/gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx @@ -24,14 +24,11 @@ export function ErrorSection() { }`} > {error.fatal ? ( - + ) : ( - + )} -

- {error.fatal ? "Fatal Error:" : "Warning:"}{" "} - {error.message} -

+

{error.message}

))} diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx index 7ad61abd0..c6e96c16b 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx @@ -59,7 +59,7 @@ export const ToolPoliciesSection = () => { size={10} />
-
+
{tools.map((tool) => ( { excluded={toolGroupSettings[groupName] === "exclude"} /> ))} - {toolGroupSettings[groupName] === "exclude" && ( -
- )}
))} diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx index c19c926af..f7b0a97d1 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx @@ -1,14 +1,17 @@ -import { InformationCircleIcon } from "@heroicons/react/24/outline"; +import { + ChevronRightIcon, + InformationCircleIcon, +} from "@heroicons/react/24/outline"; import { Tool } from "core"; -import { useEffect } from "react"; +import { useEffect, useMemo, useState } from "react"; import { useDispatch } from "react-redux"; import { useAppSelector } from "../../../../../redux/hooks"; import { addTool, toggleToolSetting, } from "../../../../../redux/slices/uiSlice"; -import { fontSize } from "../../../../../util"; import { ToolTip } from "../../../../gui/Tooltip"; +import { useFontSize } from "../../../../ui/font"; interface ToolDropdownItemProps { tool: Tool; @@ -21,6 +24,7 @@ function ToolPolicyItem(props: ToolDropdownItemProps) { const policy = useAppSelector( (state) => state.ui.toolSettings[props.tool.function.name], ); + const [isExpanded, setIsExpanded] = useState(false); useEffect(() => { if (!policy) { @@ -28,74 +32,133 @@ function ToolPolicyItem(props: ToolDropdownItemProps) { } }, [props.tool.function.name, policy]); + const parameters = useMemo(() => { + if (props.tool.function.parameters?.properties) { + return Object.entries(props.tool.function.parameters.properties).map( + ([name, schema]) => + [name, schema] as [string, { description: string; type: string }], + ); + } + return undefined; + }, [props.tool.function.parameters]); + + const fontSize = useFontSize(-2); + if (!policy) { return null; } return (
{ - dispatch(toggleToolSetting(props.tool.function.name)); - e.stopPropagation(); - e.preventDefault(); + fontSize, }} > -
- {props.duplicatesDetected ? ( - <> -
- +
setIsExpanded((val) => !val)} + > +
- {props.excluded ? ( - Excluded - ) : ( -
- {(policy === "allowedWithPermission" || policy === undefined) && ( - Ask First - )} - {policy === "allowedWithoutPermission" && ( - Automatic - )} - {policy === "disabled" && ( - Excluded + )} + + {props.tool.function.name} + +
+
+
{ + dispatch(toggleToolSetting(props.tool.function.name)); + e.stopPropagation(); + e.preventDefault(); + }} + > + {props.excluded || policy === "disabled" ? ( + <> + Off + + Excluded + + + ) : policy === "allowedWithoutPermission" ? ( + <> + Auto + + Automatic + + + ) : ( + // allowedWithPermission + <> + Ask + + Ask First + + )}
- )} +
+
+ Description: + {props.tool.function.description} + {parameters ? ( + <> + Arguments: + {parameters.map((param) => ( +
+ {param[0]} + {`(${param[1].type}):`} + {param[1].description} +
+ ))} + + ) : null} +
+
); } diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index f58a4194a..37ba5d51a 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -34,7 +34,6 @@ import { ProfileDescription } from "core/config/ConfigHandler"; import { useNavigate } from "react-router-dom"; import { vscCommandCenterInactiveBorder } from "../.."; import { ROUTES } from "../../../util/navigation"; -import { ToolTip } from "../../gui/Tooltip"; import { useLump } from "../../mainInput/Lump/LumpContext"; import { useFontSize } from "../../ui/font"; import AssistantIcon from "./AssistantIcon"; @@ -113,42 +112,35 @@ const AssistantSelectOption = ({
- {!profile.errors?.length ? ( - isLocalProfile(profile) ? ( - { - e.stopPropagation(); - e.preventDefault(); - handleConfigure(); - }} - /> - ) : ( - { - e.stopPropagation(); - e.preventDefault(); - handleConfigure(); - }} - /> - ) + {profile.errors && profile.errors?.length > 0 && ( + { + e.preventDefault(); + e.stopPropagation(); + handleClickError(); + }} + /> + )} + {isLocalProfile(profile) ? ( + { + e.stopPropagation(); + e.preventDefault(); + handleConfigure(); + }} + /> ) : ( - <> - { - e.preventDefault(); - e.stopPropagation(); - handleClickError(); - }} - /> - -
Errors
- {JSON.stringify(profile.errors, null, 2)} -
- + { + e.stopPropagation(); + e.preventDefault(); + handleConfigure(); + }} + /> )}
diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.tsx similarity index 96% rename from gui/src/context/IdeMessenger.ts rename to gui/src/context/IdeMessenger.tsx index 4d0258efd..e30f39ccf 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.tsx @@ -264,3 +264,14 @@ export class IdeMessenger implements IIdeMessenger { export const IdeMessengerContext = createContext( new IdeMessenger(), ); + +export const IdeMessengerProvider: React.FC<{ + children: React.ReactNode; + messenger?: IIdeMessenger; +}> = ({ children, messenger = new IdeMessenger() }) => { + return ( + + {children} + + ); +}; diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts new file mode 100644 index 000000000..ac40a0a7f --- /dev/null +++ b/gui/src/context/MockIdeMessenger.ts @@ -0,0 +1,122 @@ +import { IDE, PromptLog } from "core"; +import { + FromWebviewProtocol, + ToCoreProtocol, + ToWebviewProtocol, +} from "core/protocol"; +import { MessageIde } from "core/protocol/messenger/messageIde"; +import { + GeneratorReturnType, + GeneratorYieldType, + WebviewSingleProtocolMessage, +} from "core/protocol/util"; +import { ChatMessage } from "../redux/store"; +import { IIdeMessenger } from "./IdeMessenger"; + +async function defaultMockHandleMessage( + messageType: T, + data: FromWebviewProtocol[T][0], +): Promise { + function returnFor( + _: K, + value: FromWebviewProtocol[K][1], + ): FromWebviewProtocol[T][1] { + return value as unknown as FromWebviewProtocol[T][1]; + } + + switch (messageType) { + case "history/list": + return returnFor("history/list", [ + { + title: "Session 1", + sessionId: "session-1", + dateCreated: new Date().toString(), + workspaceDirectory: "/tmp", + }, + ]); + case "getControlPlaneSessionInfo": + return returnFor("getControlPlaneSessionInfo", { + accessToken: "", + account: { + label: "", + id: "", + }, + }); + case "config/getSerializedProfileInfo": + return returnFor("config/getSerializedProfileInfo", { + organizations: [], + profileId: "test-profile", + result: { + config: undefined, + errors: [], + configLoadInterrupted: false, + }, + selectedOrgId: "local", + }); + default: + throw new Error(`Unknown message type ${messageType}`); + } +} + +export class MockIdeMessenger implements IIdeMessenger { + ide: IDE; + + constructor() { + this.ide = new MessageIde( + (messageType, data) => { + throw new Error("Not implemented"); + }, + (messageType, callback) => {}, + ); + } + + async *llmStreamChat( + msg: ToCoreProtocol["llm/streamChat"][0], + cancelToken: AbortSignal, + ): AsyncGenerator { + yield [ + { + role: "assistant", + content: "This is a test", + }, + ]; + + return undefined; + } + + post( + messageType: T, + data: FromWebviewProtocol[T][0], + messageId?: string, + attempt?: number, + ): void {} + + async request( + messageType: T, + data: FromWebviewProtocol[T][0], + ): Promise> { + const content = await defaultMockHandleMessage(messageType, data); + return { + status: "success", + content, + done: true, + }; + } + + respond( + messageType: T, + data: ToWebviewProtocol[T][1], + messageId: string, + ): void {} + + async *streamRequest( + messageType: T, + data: FromWebviewProtocol[T][0], + cancelToken?: AbortSignal, + ): AsyncGenerator< + GeneratorYieldType[], + GeneratorReturnType | undefined + > { + return undefined; + } +} diff --git a/gui/src/pages/gui/Chat.test.tsx b/gui/src/pages/gui/Chat.test.tsx new file mode 100644 index 000000000..5339f831b --- /dev/null +++ b/gui/src/pages/gui/Chat.test.tsx @@ -0,0 +1,62 @@ +import { renderWithProviders } from "../../util/test/render"; +import { screen, waitFor } from "@testing-library/dom"; +import { act, fireEvent } from "@testing-library/react"; +import { Chat } from "./Chat"; + +describe("Chat page test", () => { + it("should render input box", async () => { + await renderWithProviders(); + expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument(); + }); + + it("should be able to toggle modes", async () => { + await renderWithProviders(); + expect(screen.getByText("Chat")).toBeInTheDocument(); + + // Simulate cmd+. keyboard shortcut to toggle modes + act(() => { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: ".", + metaKey: true, // cmd key on Mac + }), + ); + }); + + // Check that it switched to Edit mode + expect(await screen.findByText("Edit")).toBeInTheDocument(); + + act(() => { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: ".", + metaKey: true, // cmd key on Mac + }), + ); + }); + + // Check that it switched to Agent mode + expect(await screen.findByText("Agent")).toBeInTheDocument(); + }); + + it.skip("should send a message and receive a response", async () => { + const { user, container } = await renderWithProviders(); + const inputBox = await waitFor(() => + container.querySelector(".ProseMirror")!.querySelector("p"), + ); + expect(inputBox).toBeDefined(); + + const sendButton = await screen.findByTestId("submit-input-button"); + + await act(async () => { + // Focus input box + inputBox!.focus(); + + // Type message + await user.type(inputBox!, "Hello, world!"); + + sendButton.click(); + }); + expect(await screen.findByText("Hello, world!")).toBeInTheDocument(); + }); +}); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 284f4f8cc..f8f3eee18 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -48,7 +48,7 @@ import { cancelStream } from "../../redux/thunks/cancelStream"; import { exitEditMode } from "../../redux/thunks/exitEditMode"; import { loadLastSession } from "../../redux/thunks/session"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; -import { isMetaEquivalentKeyPressed } from "../../util"; +import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS, incrementFreeTrialCount, @@ -130,14 +130,15 @@ export function Chat() { const hasDismissedExploreDialog = useAppSelector( (state) => state.ui.hasDismissedExploreDialog, ); + const jetbrains = isJetBrains(); useEffect(() => { // Cmd + Backspace to delete current step const listener = (e: any) => { if ( - e.key === "Backspace" && - isMetaEquivalentKeyPressed(e) && - !e.shiftKey + e.key === "Backspace" && jetbrains + ? e.altKey + : isMetaEquivalentKeyPressed(e) && !e.shiftKey ) { dispatch(cancelStream()); } @@ -339,8 +340,8 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // diff --git a/gui/src/pages/history/history.test.tsx b/gui/src/pages/history/history.test.tsx index 9a9d2772c..8ab4f2862 100644 --- a/gui/src/pages/history/history.test.tsx +++ b/gui/src/pages/history/history.test.tsx @@ -2,19 +2,21 @@ import { screen } from "@testing-library/dom"; import { renderWithProviders } from "../../util/test/render"; import HistoryPage from "./index"; -const navigateFn = vi.fn(); - -vi.mock("react-router-dom", async () => { - const original = await vi.importActual("react-router-dom"); - return { - ...original, - useNavigate: () => navigateFn, - }; -}); - describe("history Page test", () => { - it("History text is existed after render", () => { - renderWithProviders(); + it("History text is existed after render", async () => { + await renderWithProviders(); expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); + + it("History shows the first item in the list", async () => { + await renderWithProviders(); + const sessionElement = await screen.findByText( + "Session 1", + {}, + { + timeout: 3000, // There is a 2000ms timeout before the first call to refreshSessionMetadata is called + }, + ); + expect(sessionElement).toBeInTheDocument(); + }); }); diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index cca27e6e2..bbfea5364 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -47,7 +47,5 @@ export const selectUseActiveFile = createSelector( (defaultContext) => defaultContext?.includes("activeFile" as any), ); -export const selectUseHub = createSelector( - [(state: RootState) => state.config.config.usePlatform], - (usePlatform) => usePlatform, -); +export const selectUseHub = (state: RootState) => + state.config.config.usePlatform; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 4a4d939c0..aa7c2bb5c 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -109,7 +109,9 @@ const persistedReducer = persistReducer>( rootReducer, ); -export function setupStore() { +export function setupStore(options: { ideMessenger?: IIdeMessenger }) { + const ideMessenger = options.ideMessenger ?? new IdeMessenger(); + const logger = createLogger({ // Customize logger options if needed collapsed: true, // Collapse console groups by default @@ -126,7 +128,7 @@ export function setupStore() { serializableCheck: false, thunk: { extraArgument: { - ideMessenger: new IdeMessenger(), + ideMessenger, }, }, }), @@ -148,7 +150,7 @@ export type AppThunkDispatch = ThunkDispatch< UnknownAction >; -export const store = setupStore(); +export const store = setupStore({}); export type RootState = ReturnType; diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 63b5e6189..dd00b86fb 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -89,7 +89,6 @@ export const streamResponseThunk = createAsyncThunk< [...updatedHistory], selectedChatModel?.baseChatSystemMessage, state.config.config.rules, - selectedChatModel.model, ); posthog.capture("step run", { diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 269402bf5..7ff0ee47e 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -69,7 +69,6 @@ export const streamResponseAfterToolCall = createAsyncThunk< [...updatedHistory], selectedChatModel?.baseChatSystemMessage, state.config.config.rules, - selectedChatModel.model, ); unwrapResult(await dispatch(streamNormalInput({ messages }))); diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 95f1cbd2d..2b9ae5b29 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -1,11 +1,17 @@ -import type { RenderOptions } from "@testing-library/react"; +import type { RenderOptions, RenderResult } from "@testing-library/react"; import { render } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { PropsWithChildren } from "react"; import { Provider } from "react-redux"; import { MemoryRouter, RouterProps } from "react-router-dom"; import { AuthProvider } from "../../context/Auth"; +import { IdeMessengerProvider } from "../../context/IdeMessenger"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; import { setupStore } from "../../redux/store"; +import { SetupListeners } from "../../App"; +import { act } from "@testing-library/react"; +import { LumpProvider } from "../../components/mainInput/Lump/LumpContext"; +import { MainEditorProvider } from "../../components/mainInput/TipTapEditor"; // As a basic setup, import your same slice reducers // This type interface extends the default options for render from RTL, as well @@ -15,13 +21,26 @@ type ExtendedRenderOptions = Omit & { routerProps?: RouterProps; }; -export function renderWithProviders( +function setupMocks() { + global.ResizeObserver = vi.fn().mockImplementation(() => ({ + observe: vi.fn(), + unobserve: vi.fn(), + disconnect: vi.fn(), + })); +} + +export async function renderWithProviders( ui: React.ReactElement, extendedRenderOptions: ExtendedRenderOptions = {}, ) { + setupMocks(); + const ideMessenger = new MockIdeMessenger(); + const { // Automatically create a store instance if no store was passed in - store = setupStore(), + store = setupStore({ + ideMessenger, + }), routerProps = {}, ...renderOptions } = extendedRenderOptions; @@ -30,16 +49,30 @@ export function renderWithProviders( const Wrapper = ({ children }: PropsWithChildren) => ( - - {children} - + + + + + + {children} + + + + + + ); + let rendered: RenderResult; + await act(async () => { + rendered = render(ui, { wrapper: Wrapper, ...renderOptions }); + }); + // Return an object with the store and all of RTL's query functions return { user, store, - ...render(ui, { wrapper: Wrapper, ...renderOptions }), + ...rendered!, }; } diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1de41838c..7f8d55531 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -35,16 +35,15 @@ const docSchema = z.object({ }); export type DocsConfig = z.infer; - const ruleObjectSchema = z.object({ name: z.string(), rule: z.string(), - if: z.string().optional(), + globs: z.union([z.string(), z.array(z.string())]).optional(), }); - const ruleSchema = z.union([z.string(), ruleObjectSchema]); export type Rule = z.infer; +export type RuleObject = z.infer; const defaultUsesSchema = z.string(); @@ -168,3 +167,59 @@ export const blockSchema = baseConfigYamlSchema.and( ); export type Block = z.infer; + +export const continueCommandSchema = z.object({ + name: z.string(), + description: z.string().optional(), + prompt: z.string(), + placeholders: z.array(z.string()).optional(), + context: z.string().optional(), + contextWindowSize: z.number().optional(), + model: z.string().optional(), + systemMessage: z.string().optional(), + slashCommand: z.string().optional(), + hideFromCommandPalette: z.boolean().optional(), + hideFromSlashCommands: z.boolean().optional(), + mode: z.enum(["insert", "replace", "diff"]).optional(), + addEnhancedContext: z.boolean().optional(), +}); + +export const languageMarkerSchema = z.object({ + language: z.string(), + markers: z.array(z.string()), +}); + +export const sidebarSchema = z.object({ + enabled: z.boolean().optional(), + defaultOpen: z.boolean().optional(), + defaultWidth: z.number().optional(), + showButtonsThreshold: z.number().optional(), +}); + +const toolSchema = z.object({ + name: z.string(), + description: z.string(), + defaultIcon: z.string().optional(), +}); + +export const autoindentExtensionsSchema = z.array(z.string()); + +export const configSchema = z.object({ + models: z.array(modelSchema).optional(), + defaultModel: z.string().optional(), + defaultRecentMessages: z.number().optional(), + commands: z.array(continueCommandSchema).optional(), + tools: z.array(toolSchema).optional(), + contextProviders: z.array(z.any()).optional(), + langMarkers: z.array(languageMarkerSchema).optional(), + sidebar: sidebarSchema.optional(), + tabAutocompleteModel: z.string().optional(), + rules: z.array(ruleObjectSchema).optional(), + doneWithBannerForever: z.boolean().optional(), + autoindentExtensions: autoindentExtensionsSchema.optional(), + proxy: z.string().optional(), + api_base: z.string().optional(), + api_key: z.string().optional(), +}); + +export type Config = z.infer;