merge main

This commit is contained in:
Dallin Romney 2025-04-25 10:00:51 -07:00
commit 8b8406e8ab
55 changed files with 1079 additions and 367 deletions

View file

@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="Continue" pattern="file[continue-intellij-extension]:*/&amp;&amp;!file[continue-intellij-extension]:binary/bin//*&amp;&amp;!file[continue-intellij-extension]:binary/build//*&amp;&amp;!file[continue-intellij-extension]:binary/out//*&amp;&amp;!file[continue-intellij-extension]:gui/dist//*&amp;&amp;!file[continue-intellij-extension]:extensions/intellij/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/bin//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/out//*" />
<scope name="Continue" pattern="file:*/&amp;&amp;!file:binary/bin//*&amp;&amp;!file:binary/build//*&amp;&amp;!file:binary/out//*&amp;&amp;!file:gui/dist//*&amp;&amp;!file:extensions/intellij/build//*&amp;&amp;!file:extensions/vscode/bin//*&amp;&amp;!file:extensions/vscode/build//*&amp;&amp;!file:extensions/vscode/out//*&amp;&amp;!file:**/*.coverage&amp;&amp;!file:**/*.coveragedata&amp;&amp;!file:**/coverage//*&amp;&amp;!file:**/.coverage//*&amp;&amp;!file:**/assets//**" />
</component>

View file

@ -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,
};
}

View file

@ -117,7 +117,6 @@ export async function* streamDiffLines({
) as UserChatMessage | ToolResultChatMessage | undefined);
const systemMessage = getSystemMessageWithRules({
currentModel: llm.model,
rules,
userMessage: lastUserMessage,
baseSystemMessage: undefined,

8
core/index.d.ts vendored
View file

@ -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;

View file

@ -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 = `\
<important_rules>
@ -58,14 +58,10 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
of changes unless the user specifically asks for code only.
</important_rules>`;
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",

View file

@ -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 = () => <div>Hello</div>;\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 = () => <div>Hello</div>;\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);
});
});

View file

@ -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}`;
}
}

View file

@ -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);
});
});

View file

@ -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;
};

View file

@ -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.

20
docs/docs/blocks/data.md Normal file
View file

@ -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`.

19
docs/docs/blocks/docs.md Normal file
View file

@ -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.

44
docs/docs/blocks/mcp.md Normal file
View file

@ -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.

View file

@ -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.

View file

@ -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).

19
docs/docs/blocks/rules.md Normal file
View file

@ -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.

View file

@ -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).

View file

@ -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

View file

@ -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
<!-- `if` -->
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.
```
---

View file

@ -55,6 +55,16 @@ const sidebars = {
},
],
},
{
type: "category",
label: "Blocks",
items: [
{
type: "autogenerated",
dirName: "blocks",
},
],
},
"telemetry",
"troubleshooting",
{

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

BIN
docs/static/img/data-blocks-overview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

BIN
docs/static/img/docs-blocks-overview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
docs/static/img/mcp-blocks-overview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

View file

@ -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<DiffStreamService>()
if (accepted) {
diffStreamService.accept(editor)
} else {
diffStreamService.reject(editor)
}
}
}
}
}
}
fun deleteAtIndex(index: Int) {
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())
}

View file

@ -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<String>()
// 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<String>()
// 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<Any> {
val commandList = command.split(" ")

View file

@ -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
)

View file

@ -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"

9
gui/package-lock.json generated
View file

@ -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",

View file

@ -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 <></>;
}

View file

@ -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() {

View file

@ -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";

View file

@ -114,7 +114,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
: {};
return (
<div className={`${props.hidden ? "hidden" : ""}`}>
<div
className={`${props.hidden ? "hidden" : ""}`}
data-testid="continue-input-box"
>
<div className={`relative flex flex-col px-2`}>
{props.isMainInput && <Lump />}
<GradientBorder

View file

@ -8,7 +8,12 @@ import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToo
import { callCurrentTool } from "../../../redux/thunks/callCurrentTool";
import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall";
import { cancelStream } from "../../../redux/thunks/cancelStream";
import { getFontSize, getMetaKeyLabel } from "../../../util";
import {
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
isJetBrains,
} from "../../../util";
import { EnterButton } from "../InputToolbar/EnterButton";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
@ -40,18 +45,20 @@ export function LumpToolbar() {
const ideMessenger = useContext(IdeMessengerContext);
const ttsActive = useAppSelector((state) => 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
</StopButton>
</Container>
);
@ -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
</StopButton>
<EnterButton
isPrimary={true}

View file

@ -37,7 +37,7 @@ export function Lump() {
return (
<LumpDiv>
<div className="mt-0.5 px-2">
<div className="xs:px-2 mt-0.5 px-1">
<LumpToolbar />
<ContentDiv

View file

@ -123,16 +123,16 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
>
{rule.rule}
</span>
{rule.if ? (
{rule.globs ? (
<div
style={{
fontSize: tinyFont,
}}
className="mt-1.5 flex flex-col gap-1"
>
<span className="italic">Applies if</span>
<span className="italic">Applies to files</span>
<code className="line-clamp-1 px-1 py-0.5 text-gray-400">
{rule.if.replace(/\${{|}}/g, "")}
{rule.globs}
</code>
</div>
) : null}

View file

@ -24,14 +24,11 @@ export function ErrorSection() {
}`}
>
{error.fatal ? (
<ExclamationCircleIcon className="mr-2 h-5 w-5" />
<ExclamationCircleIcon className="mr-2 mt-1 h-3.5 w-3.5" />
) : (
<ExclamationTriangleIcon className="mr-2 h-5 w-5" />
<ExclamationTriangleIcon className="mr-2 mt-1 h-3.5 w-3.5" />
)}
<p className="m-0 whitespace-pre-wrap">
<strong>{error.fatal ? "Fatal Error:" : "Warning:"}</strong>{" "}
{error.message}
</p>
<p className="m-0 whitespace-pre-wrap text-xs">{error.message}</p>
</li>
))}
</ul>

View file

@ -59,7 +59,7 @@ export const ToolPoliciesSection = () => {
size={10}
/>
</div>
<div className="relative flex flex-col p-1">
<div className={`relative flex flex-col p-1`}>
{tools.map((tool) => (
<ToolPolicyItem
key={tool.uri + tool.function.name}
@ -68,9 +68,6 @@ export const ToolPoliciesSection = () => {
excluded={toolGroupSettings[groupName] === "exclude"}
/>
))}
{toolGroupSettings[groupName] === "exclude" && (
<div className="absolute right-0 top-0 h-full w-full cursor-not-allowed"></div>
)}
</div>
</div>
))}

View file

@ -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 (
<div
className="hover:bg-list-active hover:text-list-active-foreground -mx-2 flex cursor-pointer items-center justify-between gap-2 rounded-md px-2 py-0.5"
className="flex flex-col"
style={{
fontSize: fontSize(-3),
}}
data-testid={`tool-policy-item-${props.tool.function.name}`}
onClick={(e) => {
dispatch(toggleToolSetting(props.tool.function.name));
e.stopPropagation();
e.preventDefault();
fontSize,
}}
>
<div className="flex flex-1 flex-row items-center gap-1">
{props.duplicatesDetected ? (
<>
<div>
<InformationCircleIcon
data-tooltip-id={props.tool.displayTitle + "-duplicate-warning"}
className="h-3 w-3 cursor-help text-yellow-500"
<div className="flex flex-row items-center">
<div
className={`hover:bg-list-active hover:text-list-active-foreground xs:gap-1.5 flex flex-1 cursor-pointer flex-row items-center gap-1 py-0.5 pl-1 pr-2`}
onClick={() => setIsExpanded((val) => !val)}
>
<ChevronRightIcon
className={`xs:flex hidden h-3 w-3 flex-shrink-0 transition-all duration-200 ${isExpanded ? "rotate-90" : ""}`}
/>
<div
className={`flex items-center gap-1 rounded-md`}
style={{
fontSize,
}}
>
{props.duplicatesDetected ? (
<>
<InformationCircleIcon
data-tooltip-id={
props.tool.displayTitle + "-duplicate-warning"
}
className="h-3 w-3 flex-shrink-0 cursor-help text-yellow-500"
/>
<ToolTip
id={props.tool.displayTitle + "-duplicate-warning"}
place="bottom"
className="flex flex-wrap items-center"
>
<p className="m-0 p-0">
<span>Duplicate tool name</span>{" "}
<code>{props.tool.function.name}</code>{" "}
<span>
detected. Permissions will conflict and usage may be
unpredictable
</span>
</p>
</ToolTip>
</>
) : null}
{props.tool.faviconUrl && (
<img
src={props.tool.faviconUrl}
alt={props.tool.displayTitle}
className="h-3 w-3 flex-shrink-0"
/>
</div>
<ToolTip
id={props.tool.displayTitle + "-duplicate-warning"}
place="bottom"
className="flex flex-wrap items-center"
>
<p className="m-0 p-0">
<span>Duplicate tool name</span>{" "}
<code>{props.tool.function.name}</code>{" "}
<span>
detected. Permissions will conflict and usage may be
unpredictable
</span>
</p>
</ToolTip>
</>
) : null}
<span className="line-clamp-1 flex items-center gap-1">
{props.tool.faviconUrl && (
<img
src={props.tool.faviconUrl}
alt={props.tool.displayTitle}
className="h-4 w-4"
/>
)}
<pre className="my-0.5 text-[11px]">{props.tool.function.name}</pre>
</span>
</div>
{props.excluded ? (
<span className="text-lightgray">Excluded</span>
) : (
<div className="flex cursor-pointer gap-2">
{(policy === "allowedWithPermission" || policy === undefined) && (
<span className="text-yellow-500">Ask First</span>
)}
{policy === "allowedWithoutPermission" && (
<span className="text-green-500">Automatic</span>
)}
{policy === "disabled" && (
<span className="text-lightgray">Excluded</span>
)}
<span className="line-clamp-1 break-all">
{props.tool.function.name}
</span>
</div>
</div>
<div
className={`flex w-8 flex-row items-center justify-end gap-2 px-2 py-0.5 sm:w-16 ${props.excluded ? "cursor-not-allowed" : "hover:bg-list-active hover:text-list-active-foreground cursor-pointer"}`}
data-testid={`tool-policy-item-${props.tool.function.name}`}
onClick={(e) => {
dispatch(toggleToolSetting(props.tool.function.name));
e.stopPropagation();
e.preventDefault();
}}
>
{props.excluded || policy === "disabled" ? (
<>
<span className="text-lightgray sm:hidden">Off</span>
<span className="text-lightgray hidden sm:inline-block">
Excluded
</span>
</>
) : policy === "allowedWithoutPermission" ? (
<>
<span className="text-green-500 sm:hidden">Auto</span>
<span className="hidden text-green-500 sm:inline-block">
Automatic
</span>
</>
) : (
// allowedWithPermission
<>
<span className="text-yellow-500 sm:hidden">Ask</span>
<span className="hidden text-yellow-500 sm:inline-block">
Ask First
</span>
</>
)}
</div>
)}
</div>
<div
className={`flex flex-col overflow-hidden ${isExpanded ? "h-min" : "h-0 opacity-0"} gap-x-1 gap-y-2 pl-2 transition-all`}
>
<span className="mt-1.5 text-xs font-bold">Description:</span>
<span className="italic">{props.tool.function.description}</span>
{parameters ? (
<>
<span className="text-xs font-bold">Arguments:</span>
{parameters.map((param) => (
<div className="block">
<code className="">{param[0]}</code>
<span className="ml-1">{`(${param[1].type}):`}</span>
<span className="ml-1 italic">{param[1].description}</span>
</div>
))}
</>
) : null}
<div className="h-1"></div>
</div>
</div>
);
}

View file

@ -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 = ({
</span>
</div>
<div className="flex flex-row items-center gap-1">
{!profile.errors?.length ? (
isLocalProfile(profile) ? (
<Cog6ToothIcon
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
) : (
<ArrowTopRightOnSquareIcon
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
)
{profile.errors && profile.errors?.length > 0 && (
<ExclamationTriangleIcon
data-tooltip-id={`${profile.id}-errors-tooltip`}
className="h-3 w-3 flex-shrink-0 cursor-pointer text-red-500"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleClickError();
}}
/>
)}
{isLocalProfile(profile) ? (
<Cog6ToothIcon
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
) : (
<>
<ExclamationTriangleIcon
data-tooltip-id={`${profile.id}-errors-tooltip`}
className="h-3 w-3 flex-shrink-0 cursor-pointer text-red-500"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleClickError();
}}
/>
<ToolTip id={`${profile.id}-errors-tooltip`}>
<div className="font-semibold">Errors</div>
{JSON.stringify(profile.errors, null, 2)}
</ToolTip>
</>
<ArrowTopRightOnSquareIcon
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
)}
</div>
</div>

View file

@ -264,3 +264,14 @@ export class IdeMessenger implements IIdeMessenger {
export const IdeMessengerContext = createContext<IIdeMessenger>(
new IdeMessenger(),
);
export const IdeMessengerProvider: React.FC<{
children: React.ReactNode;
messenger?: IIdeMessenger;
}> = ({ children, messenger = new IdeMessenger() }) => {
return (
<IdeMessengerContext.Provider value={messenger}>
{children}
</IdeMessengerContext.Provider>
);
};

View file

@ -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<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<FromWebviewProtocol[T][1]> {
function returnFor<K extends keyof FromWebviewProtocol>(
_: 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<ChatMessage[], PromptLog | undefined> {
yield [
{
role: "assistant",
content: "This is a test",
},
];
return undefined;
}
post<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
messageId?: string,
attempt?: number,
): void {}
async request<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<WebviewSingleProtocolMessage<T>> {
const content = await defaultMockHandleMessage(messageType, data);
return {
status: "success",
content,
done: true,
};
}
respond<T extends keyof ToWebviewProtocol>(
messageType: T,
data: ToWebviewProtocol[T][1],
messageId: string,
): void {}
async *streamRequest<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
cancelToken?: AbortSignal,
): AsyncGenerator<
GeneratorYieldType<FromWebviewProtocol[T][1]>[],
GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
> {
return undefined;
}
}

View file

@ -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(<Chat />);
expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument();
});
it("should be able to toggle modes", async () => {
await renderWithProviders(<Chat />);
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(<Chat />);
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();
});
});

View file

@ -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} // <ToolOutput
item.message.role === "assistant" &&
) : item.message.role === "tool" ? null : item.message.role === // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // <ToolOutput
"assistant" &&
item.message.toolCalls &&
item.toolCallState ? (
<div>

View file

@ -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(<HistoryPage />);
it("History text is existed after render", async () => {
await renderWithProviders(<HistoryPage />);
expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument();
});
it("History shows the first item in the list", async () => {
await renderWithProviders(<HistoryPage />);
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();
});
});

View file

@ -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;

View file

@ -109,7 +109,9 @@ const persistedReducer = persistReducer<ReturnType<typeof rootReducer>>(
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<typeof rootReducer>;

View file

@ -89,7 +89,6 @@ export const streamResponseThunk = createAsyncThunk<
[...updatedHistory],
selectedChatModel?.baseChatSystemMessage,
state.config.config.rules,
selectedChatModel.model,
);
posthog.capture("step run", {

View file

@ -69,7 +69,6 @@ export const streamResponseAfterToolCall = createAsyncThunk<
[...updatedHistory],
selectedChatModel?.baseChatSystemMessage,
state.config.config.rules,
selectedChatModel.model,
);
unwrapResult(await dispatch(streamNormalInput({ messages })));

View file

@ -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<RenderOptions, "queries"> & {
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) => (
<MemoryRouter {...routerProps}>
<Provider store={store}>
<AuthProvider>{children}</AuthProvider>
</Provider>
<IdeMessengerProvider messenger={ideMessenger}>
<Provider store={store}>
<AuthProvider>
<MainEditorProvider>
<LumpProvider>
{children}
<SetupListeners />
</LumpProvider>
</MainEditorProvider>
</AuthProvider>
</Provider>
</IdeMessengerProvider>
</MemoryRouter>
);
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!,
};
}

View file

@ -35,16 +35,15 @@ const docSchema = z.object({
});
export type DocsConfig = z.infer<typeof docSchema>;
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<typeof ruleSchema>;
export type RuleObject = z.infer<typeof ruleObjectSchema>;
const defaultUsesSchema = z.string();
@ -168,3 +167,59 @@ export const blockSchema = baseConfigYamlSchema.and(
);
export type Block = z.infer<typeof blockSchema>;
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<typeof configSchema>;