Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into tomasz/rule-colocation
Changeset3e8494ef550fe08438b7bf9871e8b32dbc0a1c999fcb2eaff5541e597ad356b2
AuthorTomasz Stefaniak <tomasz.p.stefaniak@gmail.com> · 2025-06-11 15:20 -07:00
CommitterTomasz Stefaniak <tomasz.p.stefaniak@gmail.com> · 2025-06-11 15:20 -07:00
Parents7c3568e7a662, f257cf52b41d

Browse the files at this changeset

34 files changed

added core/config/markdown/createMarkdownRule.test.ts +157 −0
@@ -0,0 +1,157 @@
1+import {
2+ createMarkdownWithFrontmatter,
3+ createRuleFilePath,
4+ createRuleMarkdown,
5+ sanitizeRuleName,
6+} from "./createMarkdownRule";
7+import { parseMarkdownRule } from "./parseMarkdownRule";
8+
9+describe("sanitizeRuleName", () => {
10+ it("should sanitize rule names for filenames", () => {
11+ expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule");
12+ expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars");
13+ expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces");
14+ expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule");
15+ expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized");
16+ });
17+
18+ it("should handle empty and edge case inputs", () => {
19+ expect(sanitizeRuleName("")).toBe("");
20+ expect(sanitizeRuleName(" ")).toBe("");
21+ expect(sanitizeRuleName("123")).toBe("123");
22+ expect(sanitizeRuleName("rule-with-numbers-123")).toBe(
23+ "rule-with-numbers-123",
24+ );
25+ });
26+});
27+
28+describe("createRuleFilePath", () => {
29+ it("should create correct rule file path", () => {
30+ const result = createRuleFilePath("/workspace", "My Test Rule");
31+ expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
32+ });
33+
34+ it("should handle special characters in rule name", () => {
35+ const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
36+ expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
37+ });
38+
39+ it("should handle edge case rule names", () => {
40+ const result = createRuleFilePath("/test", " Multiple Spaces ");
41+ expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
42+ });
43+});
44+
45+describe("createMarkdownWithFrontmatter", () => {
46+ it("should create properly formatted markdown with frontmatter", () => {
47+ const frontmatter = {
48+ name: "Test Rule",
49+ description: "A test rule",
50+ globs: "*.ts",
51+ };
52+ const markdown = "# Test Rule\n\nThis is a test rule.";
53+
54+ const result = createMarkdownWithFrontmatter(frontmatter, markdown);
55+
56+ // The exact quote style doesn't matter as long as it parses correctly
57+ expect(result).toContain("name: Test Rule");
58+ expect(result).toContain("description: A test rule");
59+ expect(result).toContain("globs:");
60+ expect(result).toContain("*.ts");
61+ expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule.");
62+ });
63+
64+ it("should handle empty frontmatter", () => {
65+ const frontmatter = {};
66+ const markdown = "# Simple Rule\n\nJust markdown content.";
67+
68+ const result = createMarkdownWithFrontmatter(frontmatter, markdown);
69+
70+ const expected = `---
71+{}
72+---
73+
74+# Simple Rule
75+
76+Just markdown content.`;
77+
78+ expect(result).toBe(expected);
79+ });
80+
81+ it("should create content that can be parsed back correctly", () => {
82+ const originalFrontmatter = {
83+ name: "Roundtrip Test",
84+ description: "Testing roundtrip parsing",
85+ globs: ["*.js", "*.ts"],
86+ alwaysApply: true,
87+ };
88+ const originalMarkdown =
89+ "# Roundtrip Test\n\nThis should parse back correctly.";
90+
91+ const created = createMarkdownWithFrontmatter(
92+ originalFrontmatter,
93+ originalMarkdown,
94+ );
95+ const parsed = parseMarkdownRule(created);
96+
97+ expect(parsed.frontmatter).toEqual(originalFrontmatter);
98+ expect(parsed.markdown).toBe(originalMarkdown);
99+ });
100+});
101+
102+describe("createRuleMarkdown", () => {
103+ it("should create rule markdown with all options", () => {
104+ const result = createRuleMarkdown("Test Rule", "This is the rule content", {
105+ description: "Test description",
106+ globs: ["*.ts", "*.js"],
107+ alwaysApply: true,
108+ });
109+
110+ const parsed = parseMarkdownRule(result);
111+
112+ expect(parsed.frontmatter.description).toBe("Test description");
113+ expect(parsed.frontmatter.globs).toEqual(["*.ts", "*.js"]);
114+ expect(parsed.frontmatter.alwaysApply).toBe(true);
115+ expect(parsed.markdown).toBe("# Test Rule\n\nThis is the rule content");
116+ });
117+
118+ it("should create rule markdown with minimal options", () => {
119+ const result = createRuleMarkdown("Simple Rule", "Simple content");
120+
121+ const parsed = parseMarkdownRule(result);
122+
123+ expect(parsed.frontmatter.description).toBeUndefined();
124+ expect(parsed.frontmatter.globs).toBeUndefined();
125+ expect(parsed.frontmatter.alwaysApply).toBeUndefined();
126+ expect(parsed.markdown).toBe("# Simple Rule\n\nSimple content");
127+ });
128+
129+ it("should handle string globs", () => {
130+ const result = createRuleMarkdown("String Glob Rule", "Content", {
131+ globs: "*.py",
132+ });
133+
134+ const parsed = parseMarkdownRule(result);
135+ expect(parsed.frontmatter.globs).toBe("*.py");
136+ });
137+
138+ it("should trim description and globs", () => {
139+ const result = createRuleMarkdown("Trim Test", "Content", {
140+ description: " spaced description ",
141+ globs: " *.ts ",
142+ });
143+
144+ const parsed = parseMarkdownRule(result);
145+ expect(parsed.frontmatter.description).toBe("spaced description");
146+ expect(parsed.frontmatter.globs).toBe("*.ts");
147+ });
148+
149+ it("should handle alwaysApply false explicitly", () => {
150+ const result = createRuleMarkdown("Always Apply False", "Content", {
151+ alwaysApply: false,
152+ });
153+
154+ const parsed = parseMarkdownRule(result);
155+ expect(parsed.frontmatter.alwaysApply).toBe(false);
156+ });
157+});
added core/config/markdown/createMarkdownRule.ts +75 −0
@@ -0,0 +1,75 @@
1+import * as YAML from "yaml";
2+import { joinPathsToUri } from "../../util/uri";
3+import { RuleFrontmatter } from "./parseMarkdownRule";
4+
5+export const RULE_FILE_EXTENSION = "md";
6+
7+/**
8+ * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes)
9+ */
10+export function sanitizeRuleName(name: string): string {
11+ return name
12+ .toLowerCase()
13+ .replace(/[^a-z0-9\s-]/g, "")
14+ .replace(/\s+/g, "-")
15+ .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes
16+}
17+
18+/**
19+ * Creates the file path for a rule in the workspace .continue/rules directory
20+ */
21+export function createRuleFilePath(
22+ workspaceDir: string,
23+ ruleName: string,
24+): string {
25+ const safeRuleName = sanitizeRuleName(ruleName);
26+ return joinPathsToUri(
27+ workspaceDir,
28+ ".continue",
29+ "rules",
30+ `${safeRuleName}.${RULE_FILE_EXTENSION}`,
31+ );
32+}
33+
34+/**
35+ * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule
36+ */
37+export function createMarkdownWithFrontmatter(
38+ frontmatter: RuleFrontmatter,
39+ markdown: string,
40+): string {
41+ const frontmatterStr = YAML.stringify(frontmatter).trim();
42+ return `---\n${frontmatterStr}\n---\n\n${markdown}`;
43+}
44+
45+/**
46+ * Creates a rule markdown file content from rule components
47+ */
48+export function createRuleMarkdown(
49+ name: string,
50+ ruleContent: string,
51+ options: {
52+ description?: string;
53+ globs?: string | string[];
54+ alwaysApply?: boolean;
55+ } = {},
56+): string {
57+ const frontmatter: RuleFrontmatter = {};
58+
59+ if (options.globs) {
60+ frontmatter.globs =
61+ typeof options.globs === "string" ? options.globs.trim() : options.globs;
62+ }
63+
64+ if (options.description) {
65+ frontmatter.description = options.description.trim();
66+ }
67+
68+ if (options.alwaysApply !== undefined) {
69+ frontmatter.alwaysApply = options.alwaysApply;
70+ }
71+
72+ const markdownBody = `# ${name}\n\n${ruleContent}`;
73+
74+ return createMarkdownWithFrontmatter(frontmatter, markdownBody);
75+}
added core/config/markdown/index.ts +3 −0
@@ -0,0 +1,3 @@
1+export * from "./createMarkdownRule";
2+export * from "./loadMarkdownRules";
3+export * from "./parseMarkdownRule";
modified core/config/profile/doLoadConfig.ts +24 −10
@@ -14,12 +14,14 @@
1414 IDE,
1515 IdeSettings,
1616 ILLMLogger,
17+ RuleWithSource,
1718 SerializedContinueConfig,
1819 Tool,
1920 } from "../../";
2021 import { constructMcpSlashCommand } from "../../commands/slash/mcp";
2122 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
2223 import MCPContextProvider from "../../context/providers/MCPContextProvider";
24+import RulesContextProvider from "../../context/providers/RulesContextProvider";
2325 import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
2426 import { ControlPlaneClient } from "../../control-plane/client.js";
2527 import { getControlPlaneEnv } from "../../control-plane/env.js";
@@ -40,6 +42,24 @@
4042 import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
4143 import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
4244
45+async function loadRules(ide: IDE) {
46+ const rules: RuleWithSource[] = [];
47+ const errors = [];
48+
49+ // Add rules from .continuerules files
50+ const { rules: yamlRules, errors: continueRulesErrors } =
51+ await getWorkspaceContinueRuleDotFiles(ide);
52+ rules.unshift(...yamlRules);
53+ errors.push(...continueRulesErrors);
54+
55+ // Add rules from markdown files in .continue/rules
56+ const { rules: markdownRules, errors: markdownRulesErrors } =
57+ await loadMarkdownRules(ide);
58+ rules.unshift(...markdownRules);
59+ errors.push(...markdownRulesErrors);
60+
61+ return { rules, errors };
62+}
4363 export default async function doLoadConfig(options: {
4464 ide: IDE;
4565 ideSettingsPromise: Promise<IdeSettings>;
@@ -126,17 +146,11 @@
126146 // Remove ability have undefined errors, just have an array
127147 errors = [...(errors ?? [])];
128148
129- // Add rules from .continuerules files
130- const { rules, errors: continueRulesErrors } =
131- await getWorkspaceContinueRuleDotFiles(ide);
149+ // Load rules and always include the RulesContextProvider
150+ const { rules, errors: rulesErrors } = await loadRules(ide);
151+ errors.push(...rulesErrors);
132152 newConfig.rules.unshift(...rules);
133- errors.push(...continueRulesErrors);
134-
135- // Add rules from markdown files in .continue/rules
136- const { rules: markdownRules, errors: markdownRulesErrors } =
137- await loadMarkdownRules(ide);
138- newConfig.rules.unshift(...markdownRules);
139- errors.push(...markdownRulesErrors);
153+ newConfig.contextProviders.push(new RulesContextProvider({}));
140154
141155 // Add rules from colocated rules.md files in the codebase
142156 const { rules: codebaseRules, errors: codebaseRulesErrors } =
added core/config/workspace/workspaceBlocks.test.ts +170 −0
@@ -0,0 +1,170 @@
1+import { BlockType } from "@continuedev/config-yaml";
2+import { describe, expect, test } from "@jest/globals";
3+import { RULE_FILE_EXTENSION } from "../markdown";
4+import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
5+
6+describe("getFileContent", () => {
7+ test("returns markdown content for rules block type", () => {
8+ const result = getFileContent("rules");
9+ expect(result).toContain("# New Rule");
10+ expect(result).toContain("Your rule content");
11+ expect(result).toContain("A description of your rule");
12+ });
13+
14+ test("returns YAML content for non-rules block types", () => {
15+ const result = getFileContent("models");
16+ expect(result).toContain("name: New model");
17+ expect(result).toContain("version: 0.0.1");
18+ expect(result).toContain("schema: v1");
19+ expect(result).toContain("models:");
20+ expect(result).toContain("provider: anthropic");
21+ });
22+
23+ test("generates correct YAML for different block types", () => {
24+ const contextResult = getFileContent("context");
25+ expect(contextResult).toContain("name: New context");
26+ expect(contextResult).toContain("context:");
27+ expect(contextResult).toContain("provider: file");
28+
29+ const docsResult = getFileContent("docs");
30+ expect(docsResult).toContain("name: New doc");
31+ expect(docsResult).toContain("docs:");
32+ expect(docsResult).toContain("startUrl: https://docs.continue.dev");
33+
34+ const promptsResult = getFileContent("prompts");
35+ expect(promptsResult).toContain("name: New prompt");
36+ expect(promptsResult).toContain("prompts:");
37+ expect(promptsResult).toContain("thorough suite of unit tests");
38+
39+ const mcpResult = getFileContent("mcpServers");
40+ expect(mcpResult).toContain("name: New MCP server");
41+ expect(mcpResult).toContain("mcpServers:");
42+ expect(mcpResult).toContain("command: npx");
43+ });
44+});
45+
46+describe("findAvailableFilename", () => {
47+ test("returns base filename when it doesn't exist", async () => {
48+ const mockFileExists = async (uri: string) => false;
49+
50+ const result = await findAvailableFilename(
51+ "/workspace/.continue/models",
52+ "models",
53+ mockFileExists,
54+ );
55+
56+ expect(result).toBe("/workspace/.continue/models/new-model.yaml");
57+ });
58+
59+ test("returns filename with counter when base exists", async () => {
60+ const mockFileExists = async (uri: string) => {
61+ return uri === "/workspace/.continue/models/new-model.yaml";
62+ };
63+
64+ const result = await findAvailableFilename(
65+ "/workspace/.continue/models",
66+ "models",
67+ mockFileExists,
68+ );
69+
70+ expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
71+ });
72+
73+ test("increments counter until available filename is found", async () => {
74+ const existingFiles = new Set([
75+ "/workspace/.continue/context/new-context.yaml",
76+ "/workspace/.continue/context/new-context-1.yaml",
77+ "/workspace/.continue/context/new-context-2.yaml",
78+ ]);
79+
80+ const mockFileExists = async (uri: string) => {
81+ return existingFiles.has(uri);
82+ };
83+
84+ const result = await findAvailableFilename(
85+ "/workspace/.continue/context",
86+ "context",
87+ mockFileExists,
88+ );
89+
90+ expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
91+ });
92+
93+ test("handles different block types correctly with proper extensions", async () => {
94+ const mockFileExists = async (uri: string) => false;
95+
96+ const testCases: Array<{ blockType: BlockType; expected: string }> = [
97+ { blockType: "models", expected: "/test/new-model.yaml" },
98+ { blockType: "context", expected: "/test/new-context.yaml" },
99+ { blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
100+ { blockType: "docs", expected: "/test/new-doc.yaml" },
101+ { blockType: "prompts", expected: "/test/new-prompt.yaml" },
102+ { blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
103+ ];
104+
105+ for (const { blockType, expected } of testCases) {
106+ const result = await findAvailableFilename(
107+ "/test",
108+ blockType,
109+ mockFileExists,
110+ );
111+ expect(result).toBe(expected);
112+ }
113+ });
114+
115+ test("respects custom extension parameter", async () => {
116+ const mockFileExists = async (uri: string) => false;
117+
118+ const result = await findAvailableFilename(
119+ "/test",
120+ "models",
121+ mockFileExists,
122+ "json",
123+ );
124+
125+ expect(result).toBe("/test/new-model.json");
126+ });
127+
128+ test("handles rules markdown files with counter", async () => {
129+ const existingFiles = new Set([
130+ `/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
131+ `/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
132+ ]);
133+
134+ const mockFileExists = async (uri: string) => {
135+ return existingFiles.has(uri);
136+ };
137+
138+ const result = await findAvailableFilename(
139+ "/workspace/.continue/rules",
140+ "rules",
141+ mockFileExists,
142+ );
143+
144+ expect(result).toBe(
145+ `/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
146+ );
147+ });
148+
149+ test("handles large counter values", async () => {
150+ const existingFiles = new Set(
151+ Array.from({ length: 100 }, (_, i) =>
152+ i === 0
153+ ? "/workspace/.continue/prompts/new-prompt.yaml"
154+ : `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
155+ ),
156+ );
157+
158+ const mockFileExists = async (uri: string) => {
159+ return existingFiles.has(uri);
160+ };
161+
162+ const result = await findAvailableFilename(
163+ "/workspace/.continue/prompts",
164+ "prompts",
165+ mockFileExists,
166+ );
167+
168+ expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
169+ });
170+});
modified core/config/workspace/workspaceBlocks.ts +60 −16
@@ -2,10 +2,24 @@
22 import * as YAML from "yaml";
33 import { IDE } from "../..";
44 import { joinPathsToUri } from "../../util/uri";
5+import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown";
6+
7+const BLOCK_TYPE_CONFIG: Record<
8+ BlockType,
9+ { singular: string; filename: string }
10+> = {
11+ context: { singular: "context", filename: "context" },
12+ models: { singular: "model", filename: "model" },
13+ rules: { singular: "rule", filename: "rule" },
14+ docs: { singular: "doc", filename: "doc" },
15+ prompts: { singular: "prompt", filename: "prompt" },
16+ mcpServers: { singular: "MCP server", filename: "mcp-server" },
17+ data: { singular: "data", filename: "data" },
18+};
519
620 function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
721 const configYaml: ConfigYaml = {
8- name: `New ${blockType.slice(0, -1)}`,
22+ name: `New ${BLOCK_TYPE_CONFIG[blockType]?.singular}`,
923 version: "0.0.1",
1024 schema: "v1",
1125 };
@@ -64,6 +78,43 @@
6478 return configYaml;
6579 }
6680
81+function getFileExtension(blockType: BlockType): string {
82+ return blockType === "rules" ? RULE_FILE_EXTENSION : "yaml";
83+}
84+
85+export function getFileContent(blockType: BlockType): string {
86+ if (blockType === "rules") {
87+ return createRuleMarkdown("New Rule", "Your rule content", {
88+ description: "A description of your rule",
89+ });
90+ } else {
91+ return YAML.stringify(getContentsForNewBlock(blockType));
92+ }
93+}
94+
95+export async function findAvailableFilename(
96+ baseDirUri: string,
97+ blockType: BlockType,
98+ fileExists: (uri: string) => Promise<boolean>,
99+ extension?: string,
100+): Promise<string> {
101+ const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
102+ const fileExtension = extension ?? getFileExtension(blockType);
103+ let counter = 0;
104+ let fileUri: string;
105+
106+ do {
107+ const suffix = counter === 0 ? "" : `-${counter}`;
108+ fileUri = joinPathsToUri(
109+ baseDirUri,
110+ `${baseFilename}${suffix}.${fileExtension}`,
111+ );
112+ counter++;
113+ } while (await fileExists(fileUri));
114+
115+ return fileUri;
116+}
117+
67118 export async function createNewWorkspaceBlockFile(
68119 ide: IDE,
69120 blockType: BlockType,
@@ -77,21 +128,14 @@
77128
78129 const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`);
79130
80- // Find the first available filename
81- let counter = 0;
82- let fileUri: string;
83- do {
84- const suffix = counter === 0 ? "" : `-${counter}`;
85- fileUri = joinPathsToUri(
86- baseDirUri,
87- `new-${blockType.slice(0, -1)}${suffix}.yaml`,
88- );
89- counter++;
90- } while (await ide.fileExists(fileUri));
91-
92- await ide.writeFile(
93- fileUri,
94- YAML.stringify(getContentsForNewBlock(blockType)),
131+ const fileUri = await findAvailableFilename(
132+ baseDirUri,
133+ blockType,
134+ ide.fileExists.bind(ide),
95135 );
136+
137+ const fileContent = getFileContent(blockType);
138+
139+ await ide.writeFile(fileUri, fileContent);
96140 await ide.openFile(fileUri);
97141 }
added core/context/providers/RulesContextProvider.ts +91 −0
@@ -0,0 +1,91 @@
1+import { BaseContextProvider } from "..";
2+import {
3+ ContextItem,
4+ ContextItemUri,
5+ ContextProviderDescription,
6+ ContextProviderExtras,
7+ ContextSubmenuItem,
8+ LoadSubmenuItemsArgs,
9+ RuleWithSource,
10+} from "../..";
11+import { getControlPlaneEnv } from "../../control-plane/env";
12+
13+class RulesContextProvider extends BaseContextProvider {
14+ static description: ContextProviderDescription = {
15+ title: "rules",
16+ displayTitle: "Rules",
17+ description: "Mention rules files",
18+ type: "submenu",
19+ renderInlineAs: "",
20+ };
21+
22+ // This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case
23+ // Can eventually pull in more metadata, but this is experimental
24+ private getIdFromRule(rule: RuleWithSource): string {
25+ return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule;
26+ }
27+
28+ private getNameFromRule(rule: RuleWithSource): string {
29+ return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source;
30+ }
31+
32+ private getDescriptionFromRule(rule: RuleWithSource): string {
33+ return rule.description ?? rule.name ?? "";
34+ }
35+
36+ private getUriFromRule(
37+ rule: RuleWithSource,
38+ appUrl: string,
39+ ): ContextItemUri | undefined {
40+ if (rule.ruleFile) {
41+ return {
42+ type: "file",
43+ value: rule.ruleFile,
44+ };
45+ }
46+
47+ if (rule.slug) {
48+ let url = `${appUrl}${rule.slug}`;
49+ return {
50+ type: "url",
51+ value: url,
52+ };
53+ }
54+
55+ return undefined;
56+ }
57+
58+ async getContextItems(
59+ query: string,
60+ extras: ContextProviderExtras,
61+ ): Promise<ContextItem[]> {
62+ const rule = extras.config.rules.find(
63+ (rule) => this.getIdFromRule(rule) === query,
64+ );
65+ if (!rule) {
66+ return [];
67+ }
68+
69+ const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
70+ return [
71+ {
72+ name: this.getNameFromRule(rule),
73+ content: rule.rule,
74+ description: this.getDescriptionFromRule(rule),
75+ uri: this.getUriFromRule(rule, env.APP_URL),
76+ },
77+ ];
78+ }
79+
80+ async loadSubmenuItems(
81+ args: LoadSubmenuItemsArgs,
82+ ): Promise<ContextSubmenuItem[]> {
83+ return args.config.rules.map((rule) => ({
84+ id: this.getIdFromRule(rule),
85+ description: this.getDescriptionFromRule(rule),
86+ title: this.getNameFromRule(rule),
87+ }));
88+ }
89+}
90+
91+export default RulesContextProvider;
modified core/context/providers/index.ts +2 −0
@@ -25,6 +25,7 @@
2525 import PostgresContextProvider from "./PostgresContextProvider";
2626 import ProblemsContextProvider from "./ProblemsContextProvider";
2727 import RepoMapContextProvider from "./RepoMapContextProvider";
28+import RulesContextProvider from "./RulesContextProvider";
2829 import SearchContextProvider from "./SearchContextProvider";
2930 import TerminalContextProvider from "./TerminalContextProvider";
3031 import URLContextProvider from "./URLContextProvider";
@@ -66,6 +67,7 @@
6667 MCPContextProvider,
6768 GitCommitContextProvider,
6869 ClipboardContextProvider,
70+ RulesContextProvider,
6971 ];
7072
7173 export function contextProviderClassFromName(
modified core/core.ts +1 −0
@@ -730,6 +730,7 @@
730730 tool,
731731 toolCallId: toolCall.id,
732732 onPartialOutput,
733+ codeBaseIndexer: this.codeBaseIndexer,
733734 });
734735 });
735736
modified core/index.d.ts +2 −0
@@ -4,6 +4,7 @@
44 PromptTemplates,
55 } from "@continuedev/config-yaml";
66 import Parser from "web-tree-sitter";
7+import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
78 import { LLMConfigurationStatuses } from "./llm/constants";
89
910 declare global {
@@ -972,6 +973,7 @@
972973 contextItems: ContextItem[];
973974 }) => void;
974975 config: ContinueConfig;
976+ codeBaseIndexer?: CodebaseIndexer;
975977 }
976978
977979 export interface Tool {
modified core/indexing/CodebaseIndexer.test.ts +1 −1
@@ -278,7 +278,7 @@
278278 expect.anything(),
279279 );
280280 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
281- providers: "dependsOnIndexing",
281+ providers: "all",
282282 });
283283 });
284284
modified core/indexing/CodebaseIndexer.ts +10 −9
@@ -1,7 +1,6 @@
11 import * as fs from "fs/promises";
22
33 import { ConfigHandler } from "../config/ConfigHandler.js";
4-import { IContinueServerClient } from "../continueServer/interface.js";
54 import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
65 import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
76 import type { IMessenger } from "../protocol/messenger";
@@ -549,10 +548,10 @@
549548
550549 // New methods using messenger directly
551550
552- private async updateProgress(update: IndexingProgressUpdate) {
551+ private updateProgress(update: IndexingProgressUpdate) {
553552 this.codebaseIndexingState = update;
554553 if (this.messenger) {
555- await this.messenger.request("indexProgress", update);
554+ void this.messenger.request("indexProgress", update);
556555 }
557556 }
558557
@@ -582,7 +581,7 @@
582581 paths,
583582 this.indexingCancellationController.signal,
584583 )) {
585- await this.updateProgress(update);
584+ this.updateProgress(update);
586585
587586 if (update.status === "failed") {
588587 await this.sendIndexingErrorTelemetry(update);
@@ -596,7 +595,7 @@
596595 // Directly refresh submenu items
597596 if (this.messenger) {
598597 this.messenger.send("refreshSubmenuItems", {
599- providers: "dependsOnIndexing",
598+ providers: "all",
600599 });
601600 }
602601 this.indexingCancellationController = undefined;
@@ -613,7 +612,7 @@
613612 this.indexingCancellationController = new AbortController();
614613 try {
615614 for await (const update of this.refreshFiles(files)) {
616- await this.updateProgress(update);
615+ this.updateProgress(update);
617616
618617 if (update.status === "failed") {
619618 await this.sendIndexingErrorTelemetry(update);
@@ -626,7 +625,9 @@
626625
627626 // Directly refresh submenu items
628627 if (this.messenger) {
629- this.messenger.send("refreshSubmenuItems", { providers: "all" });
628+ this.messenger.send("refreshSubmenuItems", {
629+ providers: "all",
630+ });
630631 }
631632 this.indexingCancellationController = undefined;
632633 }
@@ -634,7 +635,7 @@
634635 public async handleIndexingError(e: any) {
635636 if (e instanceof LLMError && this.messenger) {
636637 // Need to report this specific error to the IDE for special handling
637- await this.messenger.request("reportError", e);
638+ void this.messenger.request("reportError", e);
638639 }
639640
640641 // broadcast indexing error
@@ -644,7 +645,7 @@
644645 desc: e.message,
645646 };
646647
647- await this.updateProgress(updateToSend);
648+ this.updateProgress(updateToSend);
648649 void this.sendIndexingErrorTelemetry(updateToSend);
649650 }
650651
modified core/llm/llms/Scaleway.ts +3 −3
@@ -13,10 +13,10 @@
1313
1414 private static MODEL_IDS: { [name: string]: string } = {
1515 "llama3.1-8b": "llama-3.1-8b-instruct",
16- "llama3.1-70b": "llama-3.1-70b-instruct",
17- "mistral-nemo": "mistral-nemo-instruct-2407",
16+ "llama3.3-70b": "llama-3.3-70b-instruct",
17+ "mistral-small3.1": "mistral-small-3.1-24b-instruct-2503",
18+ "deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b",
1819 "qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
19- pixtral: "pixtral-12b-2409",
2020 };
2121
2222 protected _convertModelName(model: string) {
modified core/llm/llms/stubs/ContinueProxy.ts +4 −0
@@ -34,6 +34,10 @@
3434 constructor(options: LLMOptions) {
3535 super(options);
3636 this.configEnv = options.env;
37+ // This it set to `undefined` to handle the case where we are proxying requests to Azure. We pass the correct env vars
38+ // needed to do this in `extraBodyProperties` below, but if we don't set `apiType` to `undefined`, we end up proxying to
39+ // `/openai/deployments/` which is invalid since that URL construction happens on the proxy.
40+ this.apiType = undefined;
3741 this.actualApiBase = options.apiBase;
3842 this.apiKeyLocation = options.apiKeyLocation;
3943 this.orgScopeId = options.orgScopeId;
modified core/tools/definitions/createRuleBlock.ts +0 −5
@@ -37,11 +37,6 @@
3737 description:
3838 "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
3939 },
40- alwaysApply: {
41- type: "boolean",
42- description:
43- "Whether this rule should always be applied regardless of file pattern matching",
44- },
4540 },
4641 },
4742 },
modified core/tools/implementations/createNewFile.ts +4 −0
@@ -17,6 +17,10 @@
1717 }
1818 await extras.ide.writeFile(resolvedFileUri, args.contents);
1919 await extras.ide.openFile(resolvedFileUri);
20+ await extras.ide.saveFile(resolvedFileUri);
21+ if (extras.codeBaseIndexer) {
22+ void extras.codeBaseIndexer?.refreshCodebaseIndexFiles([resolvedFileUri]);
23+ }
2024 return [
2125 {
2226 name: getUriPathBasename(resolvedFileUri),
modified core/tools/implementations/createRuleBlock.test.ts +85 −75
@@ -1,114 +1,124 @@
1-import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
1+import { jest } from "@jest/globals";
2+import { parseMarkdownRule } from "../../config/markdown";
23 import { createRuleBlockImpl } from "./createRuleBlock";
34
4-// Mock the extras parameter with necessary functions
55 const mockIde = {
6- getWorkspaceDirs: jest.fn().mockResolvedValue(["/"]),
7- writeFile: jest.fn().mockResolvedValue(undefined),
8- openFile: jest.fn().mockResolvedValue(undefined),
6+ getWorkspaceDirs: jest.fn<() => Promise<string[]>>().mockResolvedValue(["/"]),
7+ writeFile: jest
8+ .fn<(path: string, content: string) => Promise<void>>()
9+ .mockResolvedValue(undefined),
10+ openFile: jest
11+ .fn<(path: string) => Promise<void>>()
12+ .mockResolvedValue(undefined),
913 };
1014
1115 const mockExtras = {
1216 ide: mockIde,
1317 };
1418
15-describe("createRuleBlockImpl", () => {
16- beforeEach(() => {
17- jest.clearAllMocks();
18- });
19-
20- it("should create a rule with glob pattern", async () => {
21- const args = {
22- name: "TypeScript Rule",
23- rule: "Use interfaces for object shapes",
24- globs: "**/*.{ts,tsx}",
25- };
19+beforeEach(() => {
20+ jest.clearAllMocks();
21+});
2622
27- await createRuleBlockImpl(args, mockExtras as any);
23+test("createRuleBlockImpl should create a rule with glob pattern", async () => {
24+ const args = {
25+ name: "TypeScript Rule",
26+ rule: "Use interfaces for object shapes",
27+ description: "Always use interfaces",
28+ alwaysApply: true,
29+ globs: "**/*.{ts,tsx}",
30+ };
2831
29- const fileContent = mockIde.writeFile.mock.calls[0][1];
32+ await createRuleBlockImpl(args, mockExtras as any);
3033
31- const { frontmatter, markdown } = parseMarkdownRule(fileContent);
34+ const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
3235
33- expect(frontmatter).toEqual({
34- globs: "**/*.{ts,tsx}",
35- });
36+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
3637
37- expect(markdown).toContain("# TypeScript Rule");
38- expect(markdown).toContain("Use interfaces for object shapes");
38+ expect(frontmatter).toEqual({
39+ description: "Always use interfaces",
40+ globs: "**/*.{ts,tsx}",
3941 });
4042
41- it("should create a filename based on sanitized rule name", async () => {
42- const args = {
43- name: "Special Ch@racters & Spaces",
44- rule: "Handle special characters",
45- };
43+ expect(markdown).toContain("# TypeScript Rule");
44+ expect(markdown).toContain("Use interfaces for object shapes");
45+});
4646
47- await createRuleBlockImpl(args, mockExtras as any);
47+test("createRuleBlockImpl should create a filename based on sanitized rule name using shared path function", async () => {
48+ const args = {
49+ name: "Special Ch@racters & Spaces",
50+ rule: "Handle special characters",
51+ description: "Test rule",
52+ alwaysApply: false,
53+ };
4854
49- const fileUri = mockIde.writeFile.mock.calls[0][0];
50- expect(fileUri).toContain("special-chracters-spaces.md");
51- });
55+ await createRuleBlockImpl(args, mockExtras as any);
5256
53- it("should create a rule with description pattern", async () => {
54- const args = {
55- name: "Description Test",
56- rule: "This is the rule content",
57- description: "This is a detailed explanation of the rule",
58- };
57+ const fileUri = mockIde.writeFile.mock.calls[0][0];
58+ expect(fileUri).toBe("/.continue/rules/special-chracters-spaces.md");
59+});
5960
60- await createRuleBlockImpl(args, mockExtras as any);
61+test("createRuleBlockImpl should create a rule with description pattern", async () => {
62+ const args = {
63+ name: "Description Test",
64+ rule: "This is the rule content",
65+ description: "This is a detailed explanation of the rule",
66+ alwaysApply: true,
67+ };
6168
62- const fileContent = mockIde.writeFile.mock.calls[0][1];
69+ await createRuleBlockImpl(args, mockExtras as any);
6370
64- const { frontmatter, markdown } = parseMarkdownRule(fileContent);
71+ const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
6572
66- expect(frontmatter).toEqual({
67- description: "This is a detailed explanation of the rule",
68- });
73+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
6974
70- expect(markdown).toContain("# Description Test");
71- expect(markdown).toContain("This is the rule content");
75+ expect(frontmatter).toEqual({
76+ description: "This is a detailed explanation of the rule",
7277 });
7378
74- it("should include both globs and description in frontmatter", async () => {
75- const args = {
76- name: "Complete Rule",
77- rule: "Follow this standard",
78- description: "This rule enforces our team standards",
79- globs: "**/*.js",
80- };
79+ expect(markdown).toContain("# Description Test");
80+ expect(markdown).toContain("This is the rule content");
81+});
8182
82- await createRuleBlockImpl(args, mockExtras as any);
83+test("createRuleBlockImpl should include both globs and description in frontmatter", async () => {
84+ const args = {
85+ name: "Complete Rule",
86+ rule: "Follow this standard",
87+ description: "This rule enforces our team standards",
88+ alwaysApply: false,
89+ globs: "**/*.js",
90+ };
8391
84- const fileContent = mockIde.writeFile.mock.calls[0][1];
92+ await createRuleBlockImpl(args, mockExtras as any);
8593
86- const { frontmatter, markdown } = parseMarkdownRule(fileContent);
94+ const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
8795
88- expect(frontmatter).toEqual({
89- description: "This rule enforces our team standards",
90- globs: "**/*.js",
91- });
96+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
9297
93- expect(markdown).toContain("# Complete Rule");
94- expect(markdown).toContain("Follow this standard");
98+ expect(frontmatter).toEqual({
99+ description: "This rule enforces our team standards",
100+ globs: "**/*.js",
95101 });
96102
97- it("should create a rule with alwaysApply set to false", async () => {
98- const args = {
99- name: "Conditional Rule",
100- rule: "This rule should not always be applied",
101- alwaysApply: false,
102- };
103+ expect(markdown).toContain("# Complete Rule");
104+ expect(markdown).toContain("Follow this standard");
105+});
106+
107+test("createRuleBlockImpl should create a rule with alwaysApply set to false", async () => {
108+ const args = {
109+ name: "Conditional Rule",
110+ rule: "This rule should not always be applied",
111+ description: "Optional rule",
112+ alwaysApply: false,
113+ };
103114
104- await createRuleBlockImpl(args, mockExtras as any);
115+ await createRuleBlockImpl(args, mockExtras as any);
105116
106- const fileContent = mockIde.writeFile.mock.calls[0][1];
117+ const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
107118
108- const { frontmatter } = parseMarkdownRule(fileContent);
119+ const { frontmatter } = parseMarkdownRule(fileContent);
109120
110- expect(frontmatter).toEqual({
111- alwaysApply: false,
112- });
121+ expect(frontmatter).toEqual({
122+ description: "Optional rule",
113123 });
114124 });
modified core/tools/implementations/createRuleBlock.ts +9 −44
@@ -1,8 +1,6 @@
1-import * as YAML from "yaml";
21 import { ToolImpl } from ".";
32 import { RuleWithSource } from "../..";
4-import { RuleFrontmatter } from "../../config/markdown/parseMarkdownRule";
5-import { joinPathsToUri, pathToUriPathSegment } from "../../util/uri";
3+import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown";
64
75 export type CreateRuleBlockArgs = Pick<
86 Required<RuleWithSource>,
@@ -14,49 +12,16 @@
1412 args: CreateRuleBlockArgs,
1513 extras,
1614 ) => {
17- // Use the pathToUriPathSegment utility for sanitizing the name
18- const safeRuleName = pathToUriPathSegment(args.name)
19- .toLowerCase()
20- .replace(/[^a-z0-9-]/g, "") // Further sanitize to remove any remaining special chars
21- .replace(/-+/g, "-") // Replace multiple dashes with a single dash
22- .replace(/^-|-$/g, ""); // Remove leading/trailing dashes
15+ const fileContent = createRuleMarkdown(args.name, args.rule, {
16+ description: args.description,
17+ globs: args.globs,
18+ });
2319
24- const fileExtension = "md";
25-
26- const frontmatter: RuleFrontmatter = {};
27-
28- if (args.globs) {
29- frontmatter.globs =
30- typeof args.globs === "string" ? args.globs.trim() : args.globs;
31- }
32-
33- if (args.description) {
34- frontmatter.description = args.description.trim();
35- }
36-
37- if (args.alwaysApply !== undefined) {
38- frontmatter.alwaysApply = args.alwaysApply;
39- }
40-
41- const frontmatterYaml = YAML.stringify(frontmatter).trim();
42- let fileContent = `---
43-${frontmatterYaml}
44----
45-
46-# ${args.name}
47-
48-${args.rule}
49-`;
5020 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
51- const rulesDirUri = joinPathsToUri(
52- localContinueDir,
53- ".continue",
54- "rules",
55- `${safeRuleName}.${fileExtension}`,
56- );
21+ const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
5722
58- await extras.ide.writeFile(rulesDirUri, fileContent);
59- await extras.ide.openFile(rulesDirUri);
23+ await extras.ide.writeFile(ruleFilePath, fileContent);
24+ await extras.ide.openFile(ruleFilePath);
6025
6126 return [
6227 {
@@ -64,7 +29,7 @@
6429 description: args.description || "",
6530 uri: {
6631 type: "file",
67- value: rulesDirUri,
32+ value: ruleFilePath,
6833 },
6934 content: `Rule created successfully`,
7035 },
modified docs/docs/customize/model-providers/top-level/bedrock.mdx +35 −5
@@ -10,15 +10,15 @@
1010
1111 ## Chat model
1212
13-We recommend configuring **Claude 3.5 Sonnet** as your chat model.
13+We recommend configuring **Claude 3.7 Sonnet** as your chat model.
1414
1515 <Tabs groupId="config-example">
1616 <TabItem value="yaml" label="YAML">
1717 ```yaml title="config.yaml"
1818 models:
19- - name: Claude 3.5 Sonnet
19+ - name: Claude 3.7 Sonnet
2020 provider: bedrock
21- model: anthropic.claude-3-5-sonnet-20240620-v1:0
21+ model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
2222 env:
2323 region: us-east-1
2424 profile: bedrock
@@ -31,9 +31,9 @@
3131 {
3232 "models": [
3333 {
34- "title": "Claude 3.5 Sonnet",
34+ "title": "Claude 3.7 Sonnet",
3535 "provider": "bedrock",
36- "model": "anthropic.claude-3-5-sonnet-20240620-v1:0",
36+ "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
3737 "region": "us-east-1",
3838 "profile": "bedrock"
3939 }
@@ -147,6 +147,36 @@
147147 </TabItem>
148148 </Tabs>
149149
150+## Prompt caching
151+
152+Bedrock allows Claude models to cache tool payloads, system messages, and chat
153+messages between requests. Enable this behavior by adding
154+`promptCaching: true` under `defaultCompletionOptions` in your model
155+configuration.
156+
157+Prompt caching is generally available for:
158+
159+- Claude 3.7 Sonnet
160+- Claude 3.5 Haiku
161+- Amazon Nova Micro
162+- Amazon Nova Lite
163+- Amazon Nova Pro
164+
165+Customers who were granted access to Claude 3.5 Sonnet v2 during the prompt
166+caching preview will retain that access, but it cannot be enabled for new users
167+on that model.
168+
169+```yaml title="config.yaml"
170+models:
171+ - name: Claude 3.7 Sonnet
172+ provider: bedrock
173+ model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
174+ defaultCompletionOptions:
175+ promptCaching: true
176+```
177+
178+Prompt caching is not supported in JSON configuration files, so use the YAML syntax above to enable it.
179+
150180 ## Authentication
151181
152182 Authentication will be through temporary or long-term credentials in
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md +29 −3
@@ -5,15 +5,15 @@
55
66 ## 聊天模型
77
8-我们推荐配置 **Claude 3.5 Sonnet** 作为你的聊天模型。
8+我们推荐配置 **Claude 3.7 Sonnet** 作为你的聊天模型。
99
1010 ```json title="config.json"
1111 {
1212 "models": [
1313 {
14- "title": "Claude 3.5 Sonnet",
14+ "title": "Claude 3.7 Sonnet",
1515 "provider": "bedrock",
16- "model": "anthropic.claude-3-5-sonnet-20240620-v1:0",
16+ "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
1717 "region": "us-east-1",
1818 "profile": "bedrock"
1919 }
@@ -48,6 +48,32 @@
4848
4949 [点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。
5050
51+## 提示词缓存
52+
53+Bedrock 支持 Claude 模型的提示词缓存。 在 `defaultCompletionOptions`
54+中设置 `promptCaching: true` 即可缓存工具调用、系统消息和聊天消息。
55+
56+提示词缓存目前适用于以下模型:
57+
58+- Claude 3.7 Sonnet
59+- Claude 3.5 Haiku
60+- Amazon Nova Micro
61+- Amazon Nova Lite
62+- Amazon Nova Pro
63+
64+在预览期间获准使用 Claude 3.5 Sonnet v2 的用户仍可继续使用提示词缓存,但该模型不会再向新的用户开放此功能。
65+
66+```yaml title="config.yaml"
67+models:
68+ - name: Claude 3.7 Sonnet
69+ provider: bedrock
70+ model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
71+ defaultCompletionOptions:
72+ promptCaching: true
73+```
74+
75+提示词缓存不支持 JSON 配置文件,只能在 YAML 中启用。
76+
5177 ## 认证
5278
5379 认证可以通过 `~/.aws/credentials` 配置属性中临时的或长期的证书,(例如 "bedrock") 。
modified extensions/vscode/package.json +2 −2
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.46",
5+ "version": "1.1.47",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -18,7 +18,7 @@
1818 "homepage": "https://continue.dev",
1919 "qna": "https://github.com/continuedev/continue/issues/new/choose",
2020 "license": "Apache-2.0",
21- "displayName": "Continue",
21+ "displayName": "Continue - open-source AI code assistant",
2222 "pricing": "Free",
2323 "description": "The leading open-source AI code assistant",
2424 "publisher": "Continue",
modified gui/src/components/AcceptRejectDiffButtons.tsx +2 −4
@@ -51,8 +51,7 @@
5151 >
5252 <div className="flex flex-row items-center gap-1">
5353 <XMarkIcon className="text-error h-4 w-4" />
54- <span>Reject</span>
55- <span className="xs:inline-block hidden">All</span>
54+ <span className="hidden sm:inline">Reject</span>
5655 </div>
5756 </button>
5857 <ToolTip id="reject-shortcut" />
@@ -66,8 +65,7 @@
6665 >
6766 <div className="flex flex-row items-center gap-1">
6867 <CheckIcon className="text-success h-4 w-4" />
69- <span>Accept</span>
70- <span className="xs:inline-block hidden">All</span>
68+ <span className="hidden sm:inline">Accept</span>
7169 </div>
7270 </button>
7371 <ToolTip id="accept-shortcut" />
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +4 −4
@@ -31,8 +31,8 @@
3131 );
3232 case "done":
3333 return (
34- <div className="flex select-none items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
35- <span className="max-xs:hidden text-lightgray text-center text-xs">
34+ <div className="flex select-none items-center rounded bg-zinc-700 sm:gap-1 md:px-1.5">
35+ <span className="text-lightgray text-center text-xs max-md:hidden">
3636 {`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
3737 </span>
3838
@@ -42,7 +42,7 @@
4242 onClick={onClickReject}
4343 tooltipContent={`Reject all (${getMetaKeyLabel()}⇧⌫)`}
4444 >
45- <XMarkIcon className="h-3.5 w-3.5 text-red-600 hover:brightness-125" />
45+ <XMarkIcon className="text-error h-3.5 w-3.5 hover:brightness-125" />
4646 </ToolbarButtonWithTooltip>
4747
4848 <ToolbarButtonWithTooltip
@@ -50,7 +50,7 @@
5050 onClick={props.onClickAccept}
5151 tooltipContent={`Accept all (${getMetaKeyLabel()}⇧⏎)`}
5252 >
53- <CheckIcon className="h-3.5 w-3.5 text-green-600 hover:brightness-125" />
53+ <CheckIcon className="text-success h-3.5 w-3.5 hover:brightness-125" />
5454 </ToolbarButtonWithTooltip>
5555 </div>
5656 </div>
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +1 −1
@@ -291,7 +291,7 @@
291291 return (
292292 <TopDiv>
293293 <ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
294- <div className="flex max-w-72 flex-row items-center">
294+ <div className="max-w-[50% flex flex-row items-center">
295295 <ChevronDownIcon
296296 onClick={() => setIsExpanded(!isExpanded)}
297297 className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${
modified gui/src/components/mainInput/AtMentionDropdown/index.tsx +20 −0
@@ -292,6 +292,26 @@
292292 },
293293 description: "Create a new .prompt file",
294294 });
295+ } else if (subMenuTitle === "Mention rules files") {
296+ items.push({
297+ title: "Add new rule",
298+ type: "action",
299+ action: () => {
300+ void ideMessenger.request("config/addLocalWorkspaceBlock", {
301+ blockType: "rules",
302+ });
303+ const { tr } = props.editor.view.state;
304+ const text = tr.doc.textBetween(0, tr.selection.from);
305+ const start = text.lastIndexOf("@");
306+ if (start !== -1) {
307+ props.editor.view.dispatch(
308+ tr.delete(start, tr.selection.from).scrollIntoView(),
309+ );
310+ }
311+ props.onClose(); // Escape the mention list after creating a new rule
312+ },
313+ description: "Creates a rule file",
314+ });
295315 }
296316 setLoadingSubmenuItem(items.find((item) => item.id === "loading"));
297317 setAllItems(items.filter((item) => item.id !== "loading"));
modified gui/src/components/mainInput/Lump/LumpToolbar/PendingApplyStatesToolbar.tsx +2 −2
@@ -28,9 +28,9 @@
2828 {Object.entries(applyStatesByFilepath).map(([filepath, states]) => (
2929 <div key={filepath} className="flex justify-between gap-3">
3030 {filepath && (
31- <span className="bg-badge flex items-center gap-1 rounded px-0.5">
31+ <span className="bg-badge flex min-w-0 max-w-[75%] items-center gap-1 truncate rounded pr-1 text-xs">
3232 <FileIcon filename={filepath} height="18px" width="18px" />
33- {getUriPathBasename(filepath)}
33+ <span className="truncate">{getUriPathBasename(filepath)}</span>
3434 </span>
3535 )}
3636 <AcceptRejectDiffButtons
modified gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +2 −14
@@ -7,13 +7,11 @@
77 import { GhostButton } from "../../..";
88 import { useAuth } from "../../../../context/Auth";
99 import { IdeMessengerContext } from "../../../../context/IdeMessenger";
10-import { useAppDispatch } from "../../../../redux/hooks";
1110 import { fontSize } from "../../../../util";
1211
1312 export function ExploreBlocksButton(props: { blockType: string }) {
1413 const { selectedProfile } = useAuth();
1514 const ideMessenger = useContext(IdeMessengerContext);
16- const dispatch = useAppDispatch();
1715
1816 const isLocal = selectedProfile?.profileType === "local";
1917
@@ -26,21 +24,11 @@
2624
2725 const handleClick = () => {
2826 if (isLocal) {
29- ideMessenger.request("config/addLocalWorkspaceBlock", {
27+ void ideMessenger.request("config/addLocalWorkspaceBlock", {
3028 blockType: props.blockType as BlockType,
3129 });
32- // switch (props.blockType) {
33- // case "docs":
34- // dispatch(setShowDialog(true));
35- // dispatch(setDialogMessage(<AddDocsDialog />));
36- // break;
37- // default:
38- // ideMessenger.request("config/openProfile", {
39- // profileId: selectedProfile.id,
40- // });
41- // }
4230 } else {
43- ideMessenger.request("controlPlane/openUrl", {
31+ void ideMessenger.request("controlPlane/openUrl", {
4432 path: `new?type=block&blockType=${props.blockType}`,
4533 orgSlug: undefined,
4634 });
modified gui/src/components/mainInput/Lump/sections/RulesSection.tsx +1 −1
@@ -34,7 +34,7 @@
3434
3535 const handleOpen = async () => {
3636 if (rule.slug) {
37- ideMessenger.request("controlPlane/openUrl", {
37+ void ideMessenger.request("controlPlane/openUrl", {
3838 path: `${rule.slug}/new-version`,
3939 orgSlug: undefined,
4040 });
modified gui/src/components/mainInput/icons.ts +2 −0
@@ -14,6 +14,7 @@
1414 GlobeAltIcon,
1515 MagnifyingGlassIcon,
1616 PaperClipIcon,
17+ PencilIcon,
1718 PlusIcon,
1819 SparklesIcon,
1920 TrashIcon,
@@ -42,6 +43,7 @@
4243 debugger: BugAntIcon,
4344 os: CpuChipIcon,
4445 tree: Bars3BottomLeftIcon,
46+ rules: PencilIcon,
4547 "prompt-files": DocumentTextIcon,
4648 "repo-map": FolderIcon,
4749 "/clear": TrashIcon,
modified gui/src/pages/gui/StreamError.tsx +51 −2
@@ -1,4 +1,5 @@
11 import {
2+ ArrowPathIcon,
23 ArrowTopRightOnSquareIcon,
34 ClipboardIcon,
45 Cog6ToothIcon,
@@ -7,6 +8,7 @@
78 import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
89 import { useContext, useMemo } from "react";
910 import { GhostButton, SecondaryButton } from "../../components";
11+import { useMainEditor } from "../../components/mainInput/TipTapEditor";
1012 import { DiscordIcon } from "../../components/svg/DiscordIcon";
1113 import { GithubIcon } from "../../components/svg/GithubIcon";
1214 import ToggleDiv from "../../components/ToggleDiv";
@@ -16,6 +18,7 @@
1618 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
1719 import { selectSelectedChatModel } from "../../redux/slices/configSlice";
1820 import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
21+import { streamResponseThunk } from "../../redux/thunks";
1922 import { isLocalProfile } from "../../util";
2023 import { providers } from "../AddNewModel/configs/providers";
2124 import { ModelsAddOnLimitDialog } from "./ModelsAddOnLimitDialog";
@@ -44,6 +47,7 @@
4447 const selectedModel = useAppSelector(selectSelectedChatModel);
4548 const selectedProfile = useAppSelector(selectSelectedProfile);
4649 const { session, refreshProfiles } = useAuth();
50+ const { mainEditor } = useMainEditor();
4751
4852 const parsedError = useMemo<string>(
4953 () => parseErrorMessage((error as any)?.message || ""),
@@ -60,6 +64,8 @@
6064 void navigator.clipboard.writeText(parsedError);
6165 };
6266
67+ const history = useAppSelector((store) => store.session.history);
68+
6369 // Collect model information to display useful error info
6470 let modelTitle = "Chat model";
6571 let providerName = "the model provider";
@@ -131,6 +137,48 @@
131137 </GhostButton>
132138 );
133139
140+ const resubmitButton = (
141+ <GhostButton
142+ className="flex items-center"
143+ onClick={() => {
144+ let index = -1;
145+ for (let i = history.length - 1; i >= 0; i--) {
146+ if (
147+ history[i].message.role === "user" ||
148+ history[i].message.role === "tool"
149+ ) {
150+ index = i;
151+ break;
152+ }
153+ }
154+
155+ if (!mainEditor) {
156+ console.error("Main editor not found, cannot resubmit message.");
157+ return;
158+ }
159+
160+ const editorState =
161+ index === -1 ? mainEditor.getJSON() : history[index].editorState;
162+
163+ void dispatch(
164+ streamResponseThunk({
165+ editorState,
166+ modifiers: {
167+ noContext: true,
168+ useCodebase: false,
169+ },
170+ index: index === -1 ? 0 : index,
171+ }),
172+ );
173+ dispatch(setShowDialog(false));
174+ dispatch(setDialogMessage(undefined));
175+ }}
176+ >
177+ <ArrowPathIcon className="mr-1.5 h-3.5 w-3.5" />
178+ <span>Resubmit last message</span>
179+ </GhostButton>
180+ );
181+
134182 if (
135183 parsedError === "You have exceeded the chat limit for the Models Add-On."
136184 ) {
@@ -138,7 +186,7 @@
138186 }
139187
140188 let errorContent = (
141- <div className="mb-3 mt-1">
189+ <div className="mb-1 mt-3">
142190 <div className="m-0 p-0">
143191 <p className="m-0 mb-2 p-0">
144192 There was an error handling the response from{" "}
@@ -148,6 +196,7 @@
148196 Please try to submit your message again, and if the error persists,
149197 let us know by reporting the issue using the buttons below.
150198 </p>
199+ <div className="mt-3">{resubmitButton}</div>
151200 </div>
152201 </div>
153202 );
@@ -233,7 +282,7 @@
233282 if (
234283 message &&
235284 (message.toLowerCase().includes("overloaded") ||
236- message.toLowerCase().includes("malformed"))
285+ message.toLowerCase().includes("malformed json"))
237286 ) {
238287 errorContent = (
239288 <div className="flex flex-col gap-2">
modified packages/config-yaml/jest.config.mjs +1 −0
@@ -17,4 +17,5 @@
1717 __dirname: path.dirname(fileURLToPath(import.meta.url)),
1818 __filename: path.resolve(fileURLToPath(import.meta.url)),
1919 },
20+ modulePathIgnorePatterns: ["<rootDir>/dist"],
2021 };
modified packages/fetch/src/stream.ts +23 −2
@@ -24,6 +24,7 @@
2424
2525 // Get the major version of Node.js
2626 const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
27+ let chunks = 0;
2728
2829 try {
2930 if (nodeMajorVersion >= 20) {
@@ -33,6 +34,7 @@
3334 new TextDecoderStream("utf-8"),
3435 )) {
3536 yield chunk;
37+ chunks++;
3638 }
3739 } else {
3840 // Fallback for Node versions below 20
@@ -41,11 +43,30 @@
4143 const nodeStream = response.body as unknown as NodeJS.ReadableStream;
4244 for await (const chunk of toAsyncIterable(nodeStream)) {
4345 yield decoder.decode(chunk, { stream: true });
46+ chunks++;
4447 }
4548 }
4649 } catch (e) {
47- if (e instanceof Error && e.name.startsWith("AbortError")) {
48- return; // In case of client-side cancellation, just return
50+ if (e instanceof Error) {
51+ if (e.name.startsWith("AbortError")) {
52+ return; // In case of client-side cancellation, just return
53+ }
54+ if (e.message.toLowerCase().includes("premature close")) {
55+ // Premature close can happen for various reasons, including:
56+ // - Malformed chunks of data received from the server
57+ // - The server closed the connection before sending the complete response
58+ // - Long delays from the server during streaming
59+ // - 'Keep alive' header being used in combination with an http agent and a set, low number of maxSockets
60+ if (chunks === 0) {
61+ throw new Error(
62+ "Stream was closed before any data was received. Try again. (Premature Close)",
63+ );
64+ } else {
65+ throw new Error(
66+ "The response was cancelled mid-stream. Try again. (Premature Close).",
67+ );
68+ }
69+ }
4970 }
5071 throw e;
5172 }
modified packages/openai-adapters/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.36",
3+ "version": "1.0.38",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/openai-adapters/src/apis/Azure.ts +8 −5
@@ -19,9 +19,6 @@
1919 this.openai = new OpenAI({
2020 apiKey: azureConfig.apiKey,
2121 baseURL: this._getAzureBaseURL(azureConfig),
22- defaultQuery: azureConfig.env?.apiVersion
23- ? { "api-version": azureConfig.env.apiVersion }
24- : {},
2522 fetch: customFetch(azureConfig.requestOptions),
2623 });
2724 }
@@ -42,11 +39,17 @@
4239 if (this._isAzureOpenAI(config.env?.apiType)) {
4340 if (!config.env?.deployment) {
4441 throw new Error(
45- "Azure deployment is required if `apiType` is `azure-openai` or `azure`",
42+ "`env.deployment` is a required configuration property for Azure OpenAI",
4643 );
4744 }
4845
49- return `${baseURL}/openai/deployments/${config.env.deployment}`;
46+ if (!config.env?.apiVersion) {
47+ throw new Error(
48+ "`env.apiVersion` is a required configuration property for Azure OpenAI",
49+ );
50+ }
51+
52+ return `${baseURL}/openai/deployments/${config.env.deployment}?api-version=${config.env.apiVersion}`;
5053 }
5154
5255 return baseURL;