Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into main
Changeset1f089284a1911f089c6cdbd7100dd69a019aeccda3b70d12ab1e9a67d7cfb949
Authorcmmoran1130 <cmmoran@mitre.org> · 2025-05-22 15:44 -04:00
CommitterGitHub <noreply@github.com> · 2025-05-22 15:44 -04:00
Parents7858b9cfb75e, fdbd0b629223

Browse the files at this changeset

67 files changed

modified core/config/ConfigHandler.ts +2 −2
@@ -19,7 +19,7 @@
1919 import { logger } from "../util/logger.js";
2020 import {
2121 ASSISTANTS,
22- getAllDotContinueYamlFiles,
22+ getAllDotContinueDefinitionFiles,
2323 LoadAssistantFilesOptions,
2424 } from "./loadLocalAssistants.js";
2525 import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@@ -284,7 +284,7 @@
284284 }
285285
286286 if (options.includeWorkspace) {
287- const assistantFiles = await getAllDotContinueYamlFiles(
287+ const assistantFiles = await getAllDotContinueDefinitionFiles(
288288 this.ide,
289289 options,
290290 ASSISTANTS,
modified core/config/load.ts +9 −3
@@ -101,7 +101,14 @@
101101
102102 const configMergeKeys = {
103103 models: (a: any, b: any) => a.title === b.title,
104- contextProviders: (a: any, b: any) => a.name === b.name,
104+ contextProviders: (a: any, b: any) => {
105+ // If not HTTP providers, use the name only
106+ if (a.name !== "http" || b.name !== "http") {
107+ return a.name === b.name;
108+ }
109+ // For HTTP providers, consider them different if they have different URLs
110+ return a.name === b.name && a.params?.url === b.params?.url;
111+ },
105112 slashCommands: (a: any, b: any) => a.name === b.name,
106113 customCommands: (a: any, b: any) => a.name === b.name,
107114 };
@@ -970,6 +977,5 @@
970977 finalToBrowserConfig,
971978 intermediateToFinalConfig,
972979 loadContinueConfigFromJson,
973- type BrowserSerializedContinueConfig
980+ type BrowserSerializedContinueConfig,
974981 };
975-
modified core/config/loadLocalAssistants.ts +5 −5
@@ -13,7 +13,7 @@
1313 export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
1414
1515 export function isLocalAssistantFile(uri: string): boolean {
16- if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
16+ if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
1717 return false;
1818 }
1919
@@ -21,7 +21,7 @@
2121 return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
2222 }
2323
24-export async function listYamlFilesInDir(
24+async function getDefinitionFilesInDir(
2525 ide: IDE,
2626 dir: string,
2727 ): Promise<{ path: string; content: string }[]> {
@@ -41,7 +41,7 @@
4141 source: "get assistant files",
4242 });
4343 const assistantFilePaths = uris.filter(
44- (p) => p.endsWith(".yaml") || p.endsWith(".yml"),
44+ (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
4545 );
4646 const results = assistantFilePaths.map(async (uri) => {
4747 const content = await ide.readFile(uri); // make a try catch
@@ -86,7 +86,7 @@
8686 * This method searches in both ~/.continue and workspace .continue
8787 * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
8888 */
89-export async function getAllDotContinueYamlFiles(
89+export async function getAllDotContinueDefinitionFiles(
9090 ide: IDE,
9191 options: LoadAssistantFilesOptions,
9292 subDirName: string,
@@ -103,7 +103,7 @@
103103
104104 // Get all assistant files from the directories
105105 const assistantFiles = (
106- await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
106+ await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
107107 ).flat();
108108
109109 return await Promise.all(
added core/config/markdown/loadMarkdownRules.ts +47 −0
@@ -0,0 +1,47 @@
1+import { ConfigValidationError } from "@continuedev/config-yaml";
2+import { IDE, RuleWithSource } from "../..";
3+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4+import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
5+
6+/**
7+ * Loads rules from markdown files in the .continue/rules directory
8+ */
9+export async function loadMarkdownRules(ide: IDE): Promise<{
10+ rules: RuleWithSource[];
11+ errors: ConfigValidationError[];
12+}> {
13+ const errors: ConfigValidationError[] = [];
14+ const rules: RuleWithSource[] = [];
15+
16+ try {
17+ // Get all .md files from .continue/rules
18+ const markdownFiles = await getAllDotContinueDefinitionFiles(
19+ ide,
20+ { includeGlobal: true, includeWorkspace: true },
21+ "rules",
22+ );
23+
24+ // Filter to just .md files
25+ const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
26+
27+ // Process each markdown file
28+ for (const file of mdFiles) {
29+ try {
30+ const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
31+ rules.push(rule);
32+ } catch (e) {
33+ errors.push({
34+ fatal: false,
35+ message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
36+ });
37+ }
38+ }
39+ } catch (e) {
40+ errors.push({
41+ fatal: false,
42+ message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
43+ });
44+ }
45+
46+ return { rules, errors };
47+}
added core/config/markdown/parseMarkdownRule.test.ts +154 −0
@@ -0,0 +1,154 @@
1+import {
2+ convertMarkdownRuleToContinueRule,
3+ parseMarkdownRule,
4+} from "./parseMarkdownRule";
5+
6+describe("parseMarkdownRule", () => {
7+ it("should correctly parse markdown with YAML frontmatter", () => {
8+ const content = `---
9+globs: "**/test/**/*.kt"
10+---
11+
12+# Test Rule
13+
14+This is a test rule.`;
15+
16+ const result = parseMarkdownRule(content);
17+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
18+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
19+ });
20+
21+ it("should handle missing frontmatter", () => {
22+ const content = `# Test Rule
23+
24+This is a test rule without frontmatter.`;
25+
26+ const result = parseMarkdownRule(content);
27+ expect(result.frontmatter).toEqual({});
28+ expect(result.markdown).toBe(content);
29+ });
30+
31+ it("should handle empty frontmatter", () => {
32+ const content = `---
33+---
34+
35+# Test Rule
36+
37+This is a test rule with empty frontmatter.`;
38+
39+ const result = parseMarkdownRule(content);
40+
41+ // Log exact strings for debugging
42+ console.log("Actual:", JSON.stringify(result.markdown));
43+ console.log(
44+ "Expected:",
45+ JSON.stringify(
46+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
47+ ),
48+ );
49+
50+ expect(result.frontmatter).toEqual({});
51+ expect(result.markdown).toBe(
52+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
53+ );
54+ });
55+
56+ it("should handle frontmatter with whitespace", () => {
57+ const content = `---
58+globs: "**/test/**/*.kt"
59+---
60+
61+# Test Rule
62+
63+This is a test rule.`;
64+
65+ const result = parseMarkdownRule(content);
66+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
67+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
68+ });
69+
70+ it("should handle Windows line endings (CRLF)", () => {
71+ // Using \r\n for CRLF line endings
72+ const content = `---\r
73+globs: "**/test/**/*.kt"\r
74+---\r
75+\r
76+# Test Rule\r
77+\r
78+This is a test rule.`;
79+
80+ const result = parseMarkdownRule(content);
81+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
82+ // The result should be normalized to \n
83+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
84+ });
85+
86+ it("should handle malformed frontmatter", () => {
87+ const content = `---
88+globs: - "**/test/**/*.kt"
89+invalid: yaml: content
90+---
91+
92+# Test Rule
93+
94+This is a test rule.`;
95+
96+ // Should treat as only markdown when frontmatter is malformed
97+ const result = parseMarkdownRule(content);
98+ expect(result.frontmatter).toEqual({});
99+ expect(result.markdown).toBe(content);
100+ });
101+});
102+
103+describe("convertMarkdownRuleToContinueRule", () => {
104+ it("should convert markdown with frontmatter to a rule", () => {
105+ const content = `---
106+globs: "**/test/**/*.kt"
107+name: Custom Name
108+---
109+
110+# Test Rule
111+
112+This is a test rule.`;
113+
114+ const result = convertMarkdownRuleToContinueRule(
115+ "/path/to/rule.md",
116+ content,
117+ );
118+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
119+ expect(result.globs).toBe("**/test/**/*.kt");
120+ expect(result.name).toBe("Custom Name");
121+ expect(result.source).toBe("rules-block");
122+ expect(result.ruleFile).toBe("/path/to/rule.md");
123+ });
124+
125+ it("should use the first heading as name if not in frontmatter", () => {
126+ const content = `---
127+globs: "**/test/**/*.kt"
128+---
129+
130+# Test Rule Title
131+
132+This is a test rule.`;
133+
134+ const result = convertMarkdownRuleToContinueRule(
135+ "/path/to/rule.md",
136+ content,
137+ );
138+ expect(result.name).toBe("Test Rule Title");
139+ });
140+
141+ it("should use filename as name if no heading or frontmatter name", () => {
142+ const content = `---
143+globs: "**/test/**/*.kt"
144+---
145+
146+This is a test rule without a heading.`;
147+
148+ const result = convertMarkdownRuleToContinueRule(
149+ "/path/to/custom-rule.md",
150+ content,
151+ );
152+ expect(result.name).toBe("custom-rule");
153+ });
154+});
added core/config/markdown/parseMarkdownRule.ts +68 −0
@@ -0,0 +1,68 @@
1+import { basename } from "path";
2+import * as YAML from "yaml";
3+import { RuleWithSource } from "../..";
4+
5+/**
6+ * Parses markdown content with YAML frontmatter
7+ */
8+export function parseMarkdownRule(content: string): {
9+ frontmatter: Record<string, any>;
10+ markdown: string;
11+} {
12+ // Normalize line endings to \n
13+ const normalizedContent = content.replace(/\r\n/g, "\n");
14+
15+ // More reliable frontmatter detection
16+ const parts = normalizedContent.split(/^---\s*$/m);
17+
18+ // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
19+ if (parts.length >= 3) {
20+ const frontmatterStr = parts[1];
21+ // Join the remaining parts back together (in case there are more --- in the markdown)
22+ const markdownContent = parts.slice(2).join("---");
23+
24+ try {
25+ // Parse YAML frontmatter
26+ const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
27+ return { frontmatter, markdown: markdownContent.trim() };
28+ } catch (e) {
29+ // Error parsing frontmatter, treat as markdown only
30+ console.warn("Error parsing markdown frontmatter:", e);
31+ return { frontmatter: {}, markdown: normalizedContent };
32+ }
33+ }
34+
35+ // No frontmatter found
36+ return { frontmatter: {}, markdown: normalizedContent };
37+}
38+
39+/**
40+ * Converts a markdown file with YAML frontmatter to a RuleWithSource object
41+ */
42+export function convertMarkdownRuleToContinueRule(
43+ path: string,
44+ content: string,
45+): RuleWithSource {
46+ const { frontmatter, markdown } = parseMarkdownRule(content);
47+
48+ // Try to extract title from first heading if no name in frontmatter
49+ let name = frontmatter.name;
50+ if (!name) {
51+ // Look for a heading in the markdown
52+ const headingMatch = markdown.match(/^#\s+(.+)$/m);
53+ if (headingMatch) {
54+ name = headingMatch[1].trim();
55+ } else {
56+ // Fall back to filename
57+ name = basename(path).replace(/\.md$/, "");
58+ }
59+ }
60+
61+ return {
62+ rule: markdown,
63+ globs: frontmatter.globs,
64+ name,
65+ source: "rules-block",
66+ ruleFile: path,
67+ };
68+}
modified core/config/profile/doLoadConfig.ts +7 −0
@@ -32,6 +32,7 @@
3232 import { TTS } from "../../util/tts";
3333 import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
3434 import { loadContinueConfigFromJson } from "../load";
35+import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
3536 import { migrateJsonSharedConfig } from "../migrateSharedConfig";
3637 import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
3738 import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
@@ -128,6 +129,12 @@
128129 newConfig.rules.unshift(...rules);
129130 errors.push(...continueRulesErrors);
130131
132+ // Add rules from markdown files in .continue/rules
133+ const { rules: markdownRules, errors: markdownRulesErrors } =
134+ await loadMarkdownRules(ide);
135+ newConfig.rules.unshift(...markdownRules);
136+ errors.push(...markdownRulesErrors);
137+
131138 // Rectify model selections for each role
132139 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
133140
modified core/config/yaml/loadYaml.ts +5 −6
@@ -41,9 +41,8 @@
4141 import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
4242
4343 import { getControlPlaneEnvSync } from "../../control-plane/env";
44-import { logger } from "../../util/logger";
4544 import { getCleanUriPath } from "../../util/uri";
46-import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
45+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4746 import { LocalPlatformClient } from "./LocalPlatformClient";
4847 import { llmsFromModelConfig } from "./models";
4948
@@ -97,7 +96,7 @@
9796 // Add local .continue blocks
9897 const allLocalBlocks: PackageIdentifier[] = [];
9998 for (const blockType of BLOCK_TYPES) {
100- const localBlocks = await getAllDotContinueYamlFiles(
99+ const localBlocks = await getAllDotContinueDefinitionFiles(
101100 ide,
102101 { includeGlobal: true, includeWorkspace: true },
103102 blockType,
@@ -115,9 +114,9 @@
115114 ? dirname(getCleanUriPath(packageIdentifier.filePath))
116115 : undefined;
117116
118- logger.info(
119- `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
120- );
117+ // logger.info(
118+ // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
119+ // );
121120
122121 let config =
123122 overrideConfigYaml ??
modified core/control-plane/client.ts +4 −4
@@ -38,7 +38,7 @@
3838 fqsns: FQSN[],
3939 orgScopeId: string | null,
4040 ): Promise<(SecretResult | undefined)[]> {
41- if (!this.isSignedIn()) {
41+ if (!(await this.isSignedIn())) {
4242 return fqsns.map((fqsn) => ({
4343 found: false,
4444 fqsn,
@@ -105,7 +105,7 @@
105105 rawYaml: string;
106106 }[]
107107 > {
108- if (!this.isSignedIn()) {
108+ if (!(await this.isSignedIn())) {
109109 return [];
110110 }
111111
@@ -124,7 +124,7 @@
124124 }
125125
126126 public async listOrganizations(): Promise<Array<OrganizationDescription>> {
127- if (!this.isSignedIn()) {
127+ if (!(await this.isSignedIn())) {
128128 return [];
129129 }
130130
@@ -142,7 +142,7 @@
142142 public async listAssistantFullSlugs(
143143 organizationId: string | null,
144144 ): Promise<FullSlug[] | null> {
145- if (!this.isSignedIn()) {
145+ if (!(await this.isSignedIn())) {
146146 return null;
147147 }
148148
modified core/edit/streamDiffLines.ts +1 −0
@@ -122,6 +122,7 @@
122122 (msg) => msg.role === "user" || msg.role === "tool",
123123 ) as UserChatMessage | ToolResultChatMessage | undefined),
124124 baseSystemMessage: undefined,
125+ contextItems: [],
125126 })
126127 : undefined;
127128
modified core/index.d.ts +5 −1
@@ -842,7 +842,7 @@
842842 description: string;
843843 prompt?: string;
844844 params?: { [key: string]: any };
845- promptFile?: string
845+ promptFile?: string;
846846 run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
847847 }
848848
@@ -1253,6 +1253,10 @@
12531253 streamId?: string;
12541254 }
12551255
1256+export interface ShowFilePayload {
1257+ filepath: string;
1258+}
1259+
12561260 export interface RangeInFileWithContents {
12571261 filepath: string;
12581262 range: {
modified core/llm/constructMessages.ts +35 −2
@@ -1,6 +1,7 @@
11 import {
22 ChatHistoryItem,
33 ChatMessage,
4+ ContextItemWithId,
45 RuleWithSource,
56 TextMessagePart,
67 ToolResultChatMessage,
@@ -58,7 +59,7 @@
5859 at the beginning, middle, or end of files using these "lazy" comments. Only
5960 provide the complete file when explicitly requested. Include a concise explanation
6061 of changes unless the user specifically asks for code only.
61-`
62+`;
6263
6364 export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
6465 <important_rules>
@@ -77,6 +78,31 @@
7778 ${EDIT_MESSAGE}
7879 </important_rules>`;
7980
81+/**
82+ * Helper function to get the context items for a user message
83+ */
84+function getUserContextItems(
85+ userMsg: UserChatMessage | ToolResultChatMessage | undefined,
86+ history: ChatHistoryItem[],
87+): ContextItemWithId[] {
88+ if (!userMsg) return [];
89+
90+ // Find the history item that contains the userMsg
91+ const historyItem = history.find((item) => {
92+ // Check if the message ID matches
93+ if ("id" in userMsg && "id" in item.message) {
94+ return (item.message as any).id === (userMsg as any).id;
95+ }
96+ // Fallback to content comparison
97+ return (
98+ item.message.content === userMsg.content &&
99+ item.message.role === userMsg.role
100+ );
101+ });
102+
103+ return historyItem?.contextItems || [];
104+}
105+
80106 export function constructMessages(
81107 messageMode: string,
82108 history: ChatHistoryItem[],
@@ -92,7 +118,8 @@
92118 const historyItem = filteredHistory[i];
93119
94120 if (messageMode === "chat") {
95- const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage;
121+ const toolMessage: ToolResultChatMessage =
122+ historyItem.message as ToolResultChatMessage;
96123 if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
97124 // remove all tool calls from the history
98125 continue;
@@ -127,10 +154,16 @@
127154 | ToolResultChatMessage
128155 | undefined;
129156
157+ // Get context items for the last user message
158+ const lastUserContextItems = getUserContextItems(
159+ lastUserMsg,
160+ filteredHistory,
161+ );
130162 const systemMessage = getSystemMessageWithRules({
131163 baseSystemMessage: baseChatOrAgentSystemMessage,
132164 rules,
133165 userMessage: lastUserMsg,
166+ contextItems: lastUserContextItems,
134167 });
135168
136169 if (systemMessage.trim()) {
added core/llm/llms/OpenAI.test.ts +34 −0
@@ -0,0 +1,34 @@
1+import OpenAI from "./OpenAI";
2+
3+describe("OpenAI", () => {
4+ test("should identify correct o-series models", () => {
5+ const openai = new OpenAI({
6+ model: "o3-mini",
7+ });
8+ expect(openai.isOSeriesModel("o4-mini")).toBeTruthy();
9+ expect(openai.isOSeriesModel("o3-mini")).toBeTruthy();
10+ expect(openai.isOSeriesModel("o1-mini")).toBeTruthy();
11+ expect(openai.isOSeriesModel("o1")).toBeTruthy();
12+ expect(openai.isOSeriesModel("o3")).toBeTruthy();
13+
14+ // artificially correct samples for future models
15+ expect(openai.isOSeriesModel("o5-mini")).toBeTruthy();
16+ expect(openai.isOSeriesModel("o6")).toBeTruthy();
17+ expect(openai.isOSeriesModel("o77")).toBeTruthy();
18+ expect(openai.isOSeriesModel("o54-mini")).toBeTruthy();
19+ });
20+ test("should identify incorrect o-series models", () => {
21+ const openai = new OpenAI({
22+ model: "o3-mini",
23+ });
24+ expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy();
25+ expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy();
26+ expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy();
27+
28+ // artificially wrong samples
29+ expect(openai.isOSeriesModel("os1")).toBeFalsy();
30+ expect(openai.isOSeriesModel("so1")).toBeFalsy();
31+ expect(openai.isOSeriesModel("ao31")).toBeFalsy();
32+ expect(openai.isOSeriesModel("1os")).toBeFalsy();
33+ });
34+});
modified core/llm/llms/OpenAI.ts +4 −4
@@ -77,8 +77,8 @@
7777 return model;
7878 }
7979
80- private isO3orO1Model(model?: string): boolean {
81- return !!model && (model.startsWith("o1") || model.startsWith("o3"));
80+ public isOSeriesModel(model?: string): boolean {
81+ return !!model && !!model.match(/^o[0-9]+/);
8282 }
8383
8484 private isFireworksAiModel(model?: string): boolean {
@@ -139,7 +139,7 @@
139139 finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
140140
141141 // OpenAI o1-preview and o1-mini or o3-mini:
142- if (this.isO3orO1Model(options.model)) {
142+ if (this.isOSeriesModel(options.model)) {
143143 // a) use max_completion_tokens instead of max_tokens
144144 finalOptions.max_completion_tokens = options.maxTokens;
145145 finalOptions.max_tokens = undefined;
@@ -241,7 +241,7 @@
241241 body.stop = body.stop?.slice(0, this.getMaxStopWords());
242242
243243 // OpenAI o1-preview and o1-mini or o3-mini:
244- if (this.isO3orO1Model(body.model)) {
244+ if (this.isOSeriesModel(body.model)) {
245245 // a) use max_completion_tokens instead of max_tokens
246246 body.max_completion_tokens = body.max_tokens;
247247 body.max_tokens = undefined;
modified core/llm/rules/getSystemMessageWithRules.test.ts +207 −3
@@ -1,4 +1,4 @@
1-import { RuleWithSource, UserChatMessage } from "../..";
1+import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
22 import { getSystemMessageWithRules } from "./getSystemMessageWithRules";
33
44 describe("getSystemMessageWithRules", () => {
@@ -25,11 +25,48 @@
2525 source: "rules-block",
2626 };
2727
28+ // JavaScript rule
29+ const jsRule: RuleWithSource = {
30+ name: "JavaScript Rule",
31+ rule: "Follow JavaScript best practices",
32+ globs: "**/*.js",
33+ source: "rules-block",
34+ };
35+
36+ // Empty context items
37+ const emptyContextItems: ContextItemWithId[] = [];
38+
39+ // Context items with file paths
40+ const tsContextItem: ContextItemWithId = {
41+ content: "TypeScript file content",
42+ name: "Component.tsx",
43+ description: "A TypeScript component",
44+ id: { providerTitle: "file", itemId: "src/Component.tsx" },
45+ uri: { type: "file", value: "src/Component.tsx" },
46+ };
47+
48+ const pyContextItem: ContextItemWithId = {
49+ content: "Python file content",
50+ name: "utils.py",
51+ description: "A Python utility file",
52+ id: { providerTitle: "file", itemId: "utils.py" },
53+ uri: { type: "file", value: "utils.py" },
54+ };
55+
56+ const jsContextItem: ContextItemWithId = {
57+ content: "JavaScript file content",
58+ name: "utils.js",
59+ description: "A JavaScript utility file",
60+ id: { providerTitle: "file", itemId: "src/utils.js" },
61+ uri: { type: "file", value: "src/utils.js" },
62+ };
63+
2864 it("should not include pattern-matched rules when no file paths are mentioned", () => {
2965 const result = getSystemMessageWithRules({
3066 baseSystemMessage,
3167 userMessage: undefined,
3268 rules: [tsRule],
69+ contextItems: emptyContextItems,
3370 });
3471
3572 expect(result).toBe(baseSystemMessage);
@@ -40,12 +77,13 @@
4077 baseSystemMessage,
4178 userMessage: undefined,
4279 rules: [generalRule],
80+ contextItems: emptyContextItems,
4381 });
4482
4583 expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`);
4684 });
4785
48- it("should include only matching rules based on file paths", () => {
86+ it("should include only matching rules based on file paths in message", () => {
4987 const userMessage: UserChatMessage = {
5088 role: "user",
5189 content:
@@ -56,6 +94,20 @@
5694 baseSystemMessage,
5795 userMessage,
5896 rules: [tsRule, pythonRule, generalRule],
97+ contextItems: emptyContextItems,
98+ });
99+
100+ // Should include TS rule and general rule, but not Python rule
101+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
102+ expect(result).toBe(expected);
103+ });
104+
105+ it("should include matching rules based on file paths in context items", () => {
106+ const result = getSystemMessageWithRules({
107+ baseSystemMessage,
108+ userMessage: undefined,
109+ rules: [tsRule, pythonRule, generalRule],
110+ contextItems: [tsContextItem],
59111 });
60112
61113 // Should include TS rule and general rule, but not Python rule
@@ -63,7 +115,25 @@
63115 expect(result).toBe(expected);
64116 });
65117
66- it("should include multiple matching rules", () => {
118+ it("should include matching rules from both message and context items", () => {
119+ const userMessage: UserChatMessage = {
120+ role: "user",
121+ content: "```python test.py\nprint('hello')\n```",
122+ };
123+
124+ const result = getSystemMessageWithRules({
125+ baseSystemMessage,
126+ userMessage,
127+ rules: [tsRule, pythonRule, generalRule],
128+ contextItems: [tsContextItem],
129+ });
130+
131+ // Should include TS rule, Python rule, and general rule
132+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
133+ expect(result).toBe(expected);
134+ });
135+
136+ it("should include multiple matching rules from message", () => {
67137 const userMessage: UserChatMessage = {
68138 role: "user",
69139 content:
@@ -74,6 +144,20 @@
74144 baseSystemMessage,
75145 userMessage,
76146 rules: [tsRule, pythonRule, generalRule],
147+ contextItems: emptyContextItems,
148+ });
149+
150+ // Should include all rules
151+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
152+ expect(result).toBe(expected);
153+ });
154+
155+ it("should include multiple matching rules from context items", () => {
156+ const result = getSystemMessageWithRules({
157+ baseSystemMessage,
158+ userMessage: undefined,
159+ rules: [tsRule, pythonRule, generalRule],
160+ contextItems: [tsContextItem, pyContextItem],
77161 });
78162
79163 // Should include all rules
@@ -91,6 +175,7 @@
91175 baseSystemMessage,
92176 userMessage,
93177 rules: [tsRule, pythonRule, generalRule],
178+ contextItems: emptyContextItems,
94179 });
95180
96181 // Should only include the general rule
@@ -117,6 +202,7 @@
117202 baseSystemMessage,
118203 userMessage,
119204 rules: [commaRule],
205+ contextItems: emptyContextItems,
120206 });
121207
122208 // With the current implementation, the comma-separated pattern is treated as a single string,
@@ -143,6 +229,7 @@
143229 baseSystemMessage,
144230 userMessage,
145231 rules: [arrayGlobRule],
232+ contextItems: emptyContextItems,
146233 });
147234
148235 // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts
@@ -168,6 +255,7 @@
168255 baseSystemMessage,
169256 userMessage,
170257 rules: [arrayGlobRule],
258+ contextItems: emptyContextItems,
171259 });
172260
173261 // Should match src/main.ts but not config/settings.ts
@@ -193,9 +281,125 @@
193281 baseSystemMessage,
194282 userMessage,
195283 rules: [arrayGlobRule],
284+ contextItems: emptyContextItems,
196285 });
197286
198287 // Should not match any file paths
199288 expect(result).toBe(baseSystemMessage);
200289 });
290+
291+ // New test for code block with filename only (no language)
292+ it("should handle code blocks with filename only (no language identifier)", () => {
293+ const userMessage: UserChatMessage = {
294+ role: "user",
295+ content: "```test.js\nclass Calculator { /* code */ }\n```",
296+ };
297+
298+ const result = getSystemMessageWithRules({
299+ baseSystemMessage,
300+ userMessage,
301+ rules: [jsRule, tsRule, generalRule],
302+ contextItems: emptyContextItems,
303+ });
304+
305+ // Should include JS rule and general rule
306+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
307+ expect(result).toBe(expected);
308+ });
309+
310+ // New test for code blocks with line ranges
311+ it("should handle code blocks with line ranges", () => {
312+ const userMessage: UserChatMessage = {
313+ role: "user",
314+ content: "```js test.js (19-25)\ndivide(number) { /* code */ }\n```",
315+ };
316+
317+ const result = getSystemMessageWithRules({
318+ baseSystemMessage,
319+ userMessage,
320+ rules: [jsRule, tsRule, generalRule],
321+ contextItems: emptyContextItems,
322+ });
323+
324+ // Should include JS rule and general rule
325+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
326+ expect(result).toBe(expected);
327+ });
328+
329+ // New test for mixed code block formats
330+ it("should handle mixed code block formats in the same message", () => {
331+ const userMessage: UserChatMessage = {
332+ role: "user",
333+ content:
334+ "```test.js\nclass Calculator { /* code */ }\n```\n" +
335+ "```js utils.js (19-25)\ndivide(number) { /* code */ }\n```\n" +
336+ "```ts config/settings.ts\nconst config = {};\n```",
337+ };
338+
339+ const result = getSystemMessageWithRules({
340+ baseSystemMessage,
341+ userMessage,
342+ rules: [jsRule, tsRule, generalRule],
343+ contextItems: emptyContextItems,
344+ });
345+
346+ // Should include JS rule, TS rule, and general rule
347+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
348+ expect(result).toBe(expected);
349+ });
350+
351+ // Test for context items when there's no message
352+ it("should apply rules based on context items only when no message is present", () => {
353+ const result = getSystemMessageWithRules({
354+ baseSystemMessage,
355+ userMessage: undefined,
356+ rules: [jsRule, tsRule, generalRule],
357+ contextItems: [jsContextItem],
358+ });
359+
360+ // Should include JS rule and general rule
361+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
362+ expect(result).toBe(expected);
363+ });
364+
365+ // Test for non-file context items
366+ it("should ignore non-file context items", () => {
367+ const nonFileContextItem: ContextItemWithId = {
368+ content: "Some search result",
369+ name: "Search result",
370+ description: "A search result",
371+ id: { providerTitle: "search", itemId: "search-result" },
372+ // No uri with type "file"
373+ };
374+
375+ const result = getSystemMessageWithRules({
376+ baseSystemMessage,
377+ userMessage: undefined,
378+ rules: [jsRule, tsRule, generalRule],
379+ contextItems: [nonFileContextItem],
380+ });
381+
382+ // Should only include general rule
383+ const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
384+ expect(result).toBe(expected);
385+ });
386+
387+ // Test combining context items with message
388+ it("should match rules from both message code blocks and context items", () => {
389+ const userMessage: UserChatMessage = {
390+ role: "user",
391+ content: "```ts src/main.ts\nconsole.log('hello');\n```",
392+ };
393+
394+ const result = getSystemMessageWithRules({
395+ baseSystemMessage,
396+ userMessage,
397+ rules: [jsRule, tsRule, pythonRule, generalRule],
398+ contextItems: [jsContextItem, pyContextItem],
399+ });
400+
401+ // Should include JS, TS, Python rules and general rule
402+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
403+ expect(result).toBe(expected);
404+ });
201405 });
modified core/llm/rules/getSystemMessageWithRules.ts +33 −4
@@ -1,5 +1,10 @@
11 import { minimatch } from "minimatch";
2-import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
2+import {
3+ ContextItemWithId,
4+ RuleWithSource,
5+ ToolResultChatMessage,
6+ UserChatMessage,
7+} from "../..";
38 import { renderChatMessage } from "../../util/messageContent";
49 import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
510
@@ -24,21 +29,34 @@
2429 };
2530
2631 /**
27- * Filters rules that apply to the given message
32+ * Filters rules that apply to the given message and/or context items
33+ *
34+ * @param userMessage - The user or tool message to check for file paths in code blocks
35+ * @param rules - The list of rules to filter
36+ * @param contextItems - Context items to check for file paths
37+ * @returns List of applicable rules
2838 */
2939 export const getApplicableRules = (
3040 userMessage: UserChatMessage | ToolResultChatMessage | undefined,
3141 rules: RuleWithSource[],
42+ contextItems: ContextItemWithId[],
3243 ): RuleWithSource[] => {
3344 const filePathsFromMessage = userMessage
3445 ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
3546 : [];
3647
48+ // Extract file paths from context items
49+ const filePathsFromContextItems = contextItems
50+ .filter((item) => item.uri?.type === "file" && item.uri?.value)
51+ .map((item) => item.uri!.value);
52+ // Combine file paths from both sources
53+ const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
54+
3755 return rules.filter((rule) => {
3856 // A rule is active if it has no globs (applies to all files)
3957 // or if at least one file path matches its globs
4058 const hasNoGlobs = !rule.globs;
41- const matchesAnyFilePath = filePathsFromMessage.some((path) =>
59+ const matchesAnyFilePath = allFilePaths.some((path) =>
4260 matchesGlobs(path, rule.globs),
4361 );
4462
@@ -46,16 +64,27 @@
4664 });
4765 };
4866
67+/**
68+ * Creates a system message string with applicable rules appended
69+ *
70+ * @param baseSystemMessage - The base system message to start with
71+ * @param userMessage - The user message to check for file paths
72+ * @param rules - The list of rules to filter
73+ * @param contextItems - Context items to check for file paths
74+ * @returns System message with applicable rules appended
75+ */
4976 export const getSystemMessageWithRules = ({
5077 baseSystemMessage,
5178 userMessage,
5279 rules,
80+ contextItems,
5381 }: {
5482 baseSystemMessage?: string;
5583 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
5684 rules: RuleWithSource[];
85+ contextItems: ContextItemWithId[];
5786 }) => {
58- const applicableRules = getApplicableRules(userMessage, rules);
87+ const applicableRules = getApplicableRules(userMessage, rules, contextItems);
5988 let systemMessage = baseSystemMessage ?? "";
6089
6190 for (const rule of applicableRules) {
modified core/llm/toolSupport.test.ts +3 −0
@@ -155,6 +155,7 @@
155155 expect(supportsFn("pixtral-12b-2409")).toBe(true);
156156 expect(supportsFn("pixtral-large-latest")).toBe(true);
157157 expect(supportsFn("open-mistral-nemo")).toBe(true);
158+ expect(supportsFn("devstral-latest")).toBe(true);
158159 });
159160
160161 it("should return false for other unsupported models", () => {
@@ -170,6 +171,7 @@
170171 expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
171172 expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
172173 expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
174+ expect(supportsFn("DEVSTRAL-LATEST")).toBe(true);
173175 });
174176 });
175177
@@ -192,6 +194,7 @@
192194 expect(supportsFn("aya-expanse")).toBe(true);
193195 expect(supportsFn("firefunction-v2")).toBe(true);
194196 expect(supportsFn("mistral-7b")).toBe(true);
197+ expect(supportsFn("devstral-24b")).toBe(true);
195198 });
196199
197200 it("should return false for explicitly unsupported models", () => {
modified core/llm/toolSupport.ts +2 −0
@@ -88,6 +88,7 @@
8888 return (
8989 !model.toLowerCase().includes("mamba") &&
9090 [
91+ "devstral",
9192 "codestral",
9293 "mistral-large",
9394 "mistral-small",
@@ -136,6 +137,7 @@
136137 "aya-expanse",
137138 "firefunction-v2",
138139 "mistral",
140+ "devstral",
139141 ].some((part) => modelName.toLowerCase().includes(part))
140142 ) {
141143 return true;
added core/llm/utils/extractPathsFromCodeBlocks.test.ts +35 −0
@@ -0,0 +1,35 @@
1+import { extractPathsFromCodeBlocks } from "./extractPathsFromCodeBlocks";
2+
3+describe("extractPathsFromCodeBlocks", () => {
4+ it("should extract paths from code blocks with language and filepath", () => {
5+ const content = "```typescript src/main.ts\nconst x = 1;\n```";
6+ expect(extractPathsFromCodeBlocks(content)).toEqual(["src/main.ts"]);
7+ });
8+
9+ it("should extract paths from code blocks with filepath only (no language)", () => {
10+ const content = "```test.js\nclass Calculator { }\n```";
11+ expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
12+ });
13+
14+ it("should extract paths from code blocks with line ranges", () => {
15+ const content = "```js test.js (19-25)\nfunction test() {}\n```";
16+ expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
17+ });
18+
19+ it("should handle multiple code blocks with different formats", () => {
20+ const content =
21+ "```typescript src/main.ts\nconst x = 1;\n```\n" +
22+ "```test.js\nclass Calculator { }\n```\n" +
23+ "```js utils.js (19-25)\nfunction test() {}\n```";
24+ const result = extractPathsFromCodeBlocks(content);
25+ expect(result).toContain("src/main.ts");
26+ expect(result).toContain("test.js");
27+ expect(result).toContain("utils.js");
28+ expect(result.length).toBe(3);
29+ });
30+
31+ it("should not extract paths from code blocks without file paths", () => {
32+ const content = "```typescript\nconst x = 1;\n```";
33+ expect(extractPathsFromCodeBlocks(content)).toEqual([]);
34+ });
35+});
No newline at the end of the file
modified core/llm/utils/extractPathsFromCodeBlocks.ts +29 −13
@@ -2,21 +2,37 @@
22 * Extracts file paths from markdown code blocks
33 */
44 export function extractPathsFromCodeBlocks(content: string): string[] {
5- // Match:
6- // 1. Starting ```
7- // 2. Optional language identifier
8- // 3. Required whitespace
9- // 4. File path (captured) that must contain a dot and extension
10- const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
5+ console.log("CONTENT", content);
6+
117 const paths: string[] = [];
12- let match;
13-
14- while ((match = codeBlockRegex.exec(content)) !== null) {
15- const path = match[1];
16- if (path && !path.startsWith("```")) {
17- paths.push(path);
8+
9+ // Match code block opening patterns:
10+ // 1. ```language filepath
11+ // 2. ```filepath
12+ // 3. ```language filepath (range)
13+
14+ // First match all code block starts
15+ const codeBlockStarts = content.match(/```[^\n]+/g) || [];
16+
17+ for (const blockStart of codeBlockStarts) {
18+ // Try to extract a valid filename with extension
19+ const filenameMatches = blockStart.match(/([^\s()```]+\.[a-zA-Z0-9]+)/);
20+
21+ if (filenameMatches && filenameMatches[1]) {
22+ const filename = filenameMatches[1];
23+
24+ // Verify this is a legitimate filename (not part of something else)
25+ if (
26+ // Check if valid extension
27+ /\.[a-zA-Z0-9]+$/.test(filename) &&
28+ // Make sure it's not a URL
29+ !filename.includes("://") &&
30+ // Avoid duplicates
31+ !paths.includes(filename)
32+ ) {
33+ paths.push(filename);
34+ }
1835 }
1936 }
20-
2137 return paths;
2238 }
modified core/protocol/ideWebview.ts +5 −4
@@ -2,12 +2,13 @@
22 import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
33
44 import {
5+ AcceptOrRejectDiffPayload,
56 ApplyState,
6- SetCodeToEditPayload,
77 HighlightedCodePayload,
88 MessageContent,
99 RangeInFileWithContents,
10- AcceptOrRejectDiffPayload,
10+ SetCodeToEditPayload,
11+ ShowFilePayload,
1112 } from "../";
1213
1314 export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
@@ -23,7 +24,7 @@
2324 ];
2425 overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
2526 showTutorial: [undefined, void];
26- showFile: [{ filepath: string }, void];
27+ showFile: [ShowFilePayload, void];
2728 toggleDevTools: [undefined, void];
2829 reloadWindow: [undefined, void];
2930 focusEditor: [undefined, void];
@@ -41,7 +42,7 @@
4142 vscMediaUrl: string;
4243 },
4344 ];
44- "jetbrains/getColors": [undefined, Record<string, string>];
45+ "jetbrains/getColors": [undefined, Record<string, string | null | undefined>];
4546 "vscode/openMoveRightMarkdown": [undefined, void];
4647 setGitHubAuthToken: [{ token: string }, void];
4748 acceptDiff: [AcceptOrRejectDiffPayload, void];
modified core/protocol/webview.ts +1 −1
@@ -40,7 +40,7 @@
4040 setTTSActive: [boolean, void];
4141 getWebviewHistoryLength: [undefined, number];
4242 getCurrentSessionId: [undefined, string];
43- "jetbrains/setColors": [Record<string, string>, void];
43+ "jetbrains/setColors": [Record<string, string | null | undefined>, void];
4444 sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
4545 toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
4646 };
modified core/tools/implementations/createRuleBlock.ts +35 −10
@@ -7,6 +7,7 @@
77 name: string;
88 rule: string;
99 globs?: string;
10+ format?: "yaml" | "markdown"; // Add format option with yaml as default
1011 }
1112
1213 export const createRuleBlockImpl: ToolImpl = async (
@@ -19,30 +20,54 @@
1920 .replace(/[^a-z0-9\s-]/g, "")
2021 .replace(/\s+/g, "-");
2122
23+ // Default to YAML format
24+ const format = args.format ?? "yaml";
25+ const fileExtension = format === "markdown" ? "md" : "yaml";
26+
2227 const ruleObject = {
2328 name: args.name,
2429 rule: args.rule,
2530 ...(args.globs ? { globs: args.globs.trim() } : {}),
2631 };
2732
28- const ruleBlock: ConfigYaml = {
29- name: args.name,
30- version: "0.0.1",
31- schema: "v1",
32- rules: [ruleObject],
33- };
33+ let fileContent: string;
34+
35+ if (format === "markdown") {
36+ // Generate markdown format with frontmatter
37+ const frontmatter = {
38+ ...(args.globs ? { globs: args.globs.trim() } : {}),
39+ };
40+
41+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
42+ fileContent = `---
43+${frontmatterYaml}
44+---
45+
46+# ${args.name}
47+
48+${args.rule}
49+`;
50+ } else {
51+ // Generate YAML format
52+ const ruleBlock: ConfigYaml = {
53+ name: args.name,
54+ version: "0.0.1",
55+ schema: "v1",
56+ rules: [ruleObject],
57+ };
3458
35- const ruleYaml = YAML.stringify(ruleBlock);
59+ fileContent = YAML.stringify(ruleBlock);
60+ }
3661
3762 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
3863 const rulesDirUri = joinPathsToUri(
3964 localContinueDir,
4065 ".continue",
4166 "rules",
42- `${safeRuleName}.yaml`,
67+ `${safeRuleName}.${fileExtension}`,
4368 );
4469
45- await extras.ide.writeFile(rulesDirUri, ruleYaml);
70+ await extras.ide.writeFile(rulesDirUri, fileContent);
4671 await extras.ide.openFile(rulesDirUri);
4772
4873 return [
@@ -53,7 +78,7 @@
5378 type: "file",
5479 value: rulesDirUri,
5580 },
56- content: "Rule created successfully",
81+ content: `Rule created successfully in ${format} format`,
5782 },
5883 ];
5984 };
modified docs/docs/troubleshooting.mdx +2 −0
@@ -120,6 +120,8 @@
120120
121121 You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
122122
123+***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
124+
123125 #### VS Code Proxy Settings
124126
125127 If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +11 −7
@@ -11,15 +11,19 @@
1111 class ContinueActionPromote : ActionPromoter {
1212
1313 override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
14-
15- if (actions.none { it is AcceptAutocompleteAction }) {
16- return null
17- } else {
14+ // For autocomplete actions
15+ if (actions.any { it is AcceptAutocompleteAction }) {
1816 val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
19- if (!settings.continueState.showIDECompletionSideBySide) {
20- return null;
17+ if (settings.continueState.showIDECompletionSideBySide) {
18+ return actions.filterIsInstance<AcceptAutocompleteAction>()
2119 }
22- return actions.filterIsInstance<AcceptAutocompleteAction>()
2320 }
21+
22+ val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
23+ if (rejectDiffActions.isNotEmpty()) {
24+ return rejectDiffActions
25+ }
26+
27+ return null
2428 }
2529 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +6 −38
@@ -1,25 +1,12 @@
11 package com.github.continuedev.continueintellijextension.actions
22
33 import com.github.continuedev.continueintellijextension.editor.DiffStreamService
4-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
54 import com.intellij.openapi.actionSystem.AnAction
65 import com.intellij.openapi.actionSystem.AnActionEvent
76 import com.intellij.openapi.actionSystem.PlatformDataKeys
8-import com.intellij.openapi.components.ServiceManager
97 import com.intellij.openapi.components.service
108 import com.intellij.openapi.fileEditor.FileEditorManager
11-import com.intellij.openapi.project.Project
12-import com.intellij.openapi.wm.ToolWindowManager
13-
14-fun getPluginService(project: Project?): ContinuePluginService? {
15- if (project == null) {
16- return null
17- }
18- return ServiceManager.getService(
19- project,
20- ContinuePluginService::class.java
21- )
22-}
9+
2310
2411 class AcceptDiffAction : AnAction() {
2512 override fun actionPerformed(e: AnActionEvent) {
@@ -29,7 +16,7 @@
2916
3017 private fun acceptHorizontalDiff(e: AnActionEvent) {
3118 val continuePluginService = getPluginService(e.project) ?: return
32- continuePluginService?.diffManager?.acceptDiff(null)
19+ continuePluginService.diffManager?.acceptDiff(null)
3320 }
3421
3522 private fun acceptVerticalDiff(e: AnActionEvent) {
@@ -61,28 +48,6 @@
6148 }
6249 }
6350
64-fun getContinuePluginService(project: Project?): ContinuePluginService? {
65- if (project != null) {
66- val toolWindowManager = ToolWindowManager.getInstance(project)
67- val toolWindow = toolWindowManager.getToolWindow("Continue")
68-
69- if (toolWindow != null) {
70- if (!toolWindow.isVisible) {
71- toolWindow.activate(null)
72- }
73- }
74- }
75-
76- return getPluginService(project)
77-}
78-
79-fun focusContinueInput(project: Project?) {
80- val continuePluginService = getContinuePluginService(project) ?: return
81- continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
82- continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
83-
84- continuePluginService.ideProtocolClient?.sendHighlightedCode()
85-}
8651
8752 class FocusContinueInputWithoutClearAction : AnAction() {
8853 override fun actionPerformed(e: AnActionEvent) {
@@ -134,8 +99,11 @@
13499 if (logFile.exists()) {
135100 val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
136101 if (virtualFile != null) {
137- com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
102+ FileEditorManager.getInstance(project).openFile(virtualFile, true)
138103 }
139104 }
140105 }
141106 }
107+
108+
109+
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +39 −0
@@ -0,0 +1,39 @@
1+package com.github.continuedev.continueintellijextension.actions
2+
3+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
4+import com.intellij.openapi.components.ServiceManager
5+import com.intellij.openapi.project.Project
6+import com.intellij.openapi.wm.ToolWindowManager
7+
8+fun getContinuePluginService(project: Project?): ContinuePluginService? {
9+ if (project != null) {
10+ val toolWindowManager = ToolWindowManager.getInstance(project)
11+ val toolWindow = toolWindowManager.getToolWindow("Continue")
12+
13+ if (toolWindow != null) {
14+ if (!toolWindow.isVisible) {
15+ toolWindow.activate(null)
16+ }
17+ }
18+ }
19+
20+ return getPluginService(project)
21+}
22+
23+fun focusContinueInput(project: Project?) {
24+ val continuePluginService = getContinuePluginService(project) ?: return
25+ continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
26+ continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
27+
28+ continuePluginService.ideProtocolClient?.sendHighlightedCode()
29+}
30+
31+fun getPluginService(project: Project?): ContinuePluginService? {
32+ if (project == null) {
33+ return null
34+ }
35+ return ServiceManager.getService(
36+ project,
37+ ContinuePluginService::class.java
38+ )
39+}
No newline at the end of the file
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt +0 −29
@@ -1,29 +0,0 @@
1-package com.github.continuedev.continueintellijextension.autocomplete
2-
3-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
4-import com.intellij.openapi.actionSystem.ActionUpdateThread
5-import com.intellij.openapi.actionSystem.AnActionEvent
6-import com.intellij.openapi.actionSystem.DefaultActionGroup
7-import com.intellij.openapi.components.service
8-
9-class AutocompleteActionGroup : DefaultActionGroup() {
10- override fun getActionUpdateThread(): ActionUpdateThread {
11- return ActionUpdateThread.EDT
12- }
13-
14- override fun update(e: AnActionEvent) {
15- super.update(e)
16- removeAll()
17-
18- val continueSettingsService = service<ContinueExtensionSettings>()
19- if (continueSettingsService.continueState.enableTabAutocomplete) {
20- addAll(
21- DisableTabAutocompleteAction(),
22- )
23- } else {
24- addAll(
25- EnableTabAutocompleteAction(),
26- )
27- }
28- }
29-}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +2 −2
@@ -121,10 +121,10 @@
121121 val prompt = buildApplyPrompt()
122122
123123 // Extract the code ranges (highlighted or full document)
124- val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges()
124+ val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
125125
126126 // Get the line range for the diff stream
127- val rif = editorUtils.getHighlightedCode()
127+ val rif = editorUtils.getHighlightedRIF()
128128 val startLine = rif?.range?.start?.line ?: 0
129129 val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)
130130
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +146 −35
@@ -2,11 +2,13 @@
22
33 import com.intellij.openapi.editor.colors.EditorColors
44 import com.intellij.openapi.editor.colors.EditorColorsManager
5+import com.intellij.openapi.editor.colors.CodeInsightColors
56 import java.awt.Color
67 import kotlin.math.max
78 import kotlin.math.min
89 import com.intellij.ui.JBColor
910 import com.intellij.ui.ColorUtil
11+import kotlin.math.roundToInt
1012
1113 class GetTheme {
1214 fun getSecondaryDark(): Color {
@@ -38,64 +40,173 @@
3840 return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground
3941 }
4042
41- fun getTheme(): Map<String, String> {
42- fun toHex(color: Color): String {
43- return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
43+ fun toHex(color: Color?): String? {
44+ if(color == null) {
45+ return null
4446 }
47+ return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
48+ }
49+
50+ fun namedColor(name: String): Color? {
51+ // JB Color named color will fall back to a default unless we give it a fallback
52+ // We want defaults to be handled on the GUI side, so we give it this filler color
53+ // Which has a very low chance of conflicting with a real one
54+ // And return undefined if it gets the skip color
55+ val SKIP_COLOR = Color (18, 52, 86) // Hex #123456
56+ val color = JBColor.namedColor(name, SKIP_COLOR)
57+ if(toHex(color) == "#123456") {
58+ return null
59+ }
60+ return color
61+ }
62+
63+ fun lighten(color: Color, percentage: Int = 5): Color {
64+ // Increase each RGB component slightly
65+ val factor = 1 + percentage / 100f;
66+ fun lightenInt(value: Int): Int {
67+ return (value * factor).roundToInt().coerceAtMost(255)
68+ }
69+ return Color(
70+ lightenInt(color.red),
71+ lightenInt (color.green),
72+ lightenInt(color.blue),
73+ color.alpha
74+ )
75+ }
76+
77+ fun darken(color: Color, percentage: Int = 5): Color {
78+ // Decrease each RGB component slightly
79+ val factor = 1 - percentage / 100f;
80+ fun darkenInt(value: Int): Int {
81+ return (value * factor).roundToInt().coerceAtLeast(0)
82+ }
83+ return Color(
84+ darkenInt(color.red),
85+ darkenInt(color.green),
86+ darkenInt(color.blue),
87+ color.alpha
88+ )
89+ }
90+
91+ fun slightChange(color: Color?, percentage: Int = 5): Color? {
92+ if(color == null){
93+ return null
94+ }
95+ // If dark, make slightly lighter. If light, make slightly darker
96+ val averageRgb = (color.red + color.green + color.blue) / 3
97+ return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage)
98+ }
99+
100+ fun getTheme(): Map<String, String?> {
45101 try {
102+ val editorScheme = EditorColorsManager.getInstance().globalScheme
103+
46104 val background = JBColor.background()
47105 val foreground = JBColor.foreground()
48106
49- val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230))
50- val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0))
107+ val border = JBColor.border()
108+ val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor")
51109
52- val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150))
53- val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0))
110+ val buttonBackground = namedColor("Button.default.startBackground")
111+ ?: namedColor("Button.default.background")
54112
55- val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255))
113+ val buttonForeground = namedColor("Button.default.startForeground")
114+ ?: namedColor("Button.default.foreground")
56115
57- val border = JBColor.border()
58- val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255))
59- val editorScheme = EditorColorsManager.getInstance().globalScheme
116+ val buttonHoverBackground = namedColor("Button.default.hoverStartBackground")
117+ ?: namedColor("Button.default.hoverBackground")
118+ ?: namedColor("Button.default.startHoverBackground")
119+ ?: slightChange(buttonBackground)
60120
61- val editorBackground = editorScheme.defaultBackground
62- val editorForeground = editorScheme.defaultForeground
121+ val secondaryBackground = namedColor("Button.background") ?: background
122+ val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground)
63123
64- val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220))
124+ val badgeBackground = namedColor("Badge.background")
125+ val badgeForeground = namedColor("Badge.foreground")
65126
66- val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0)
127+ val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background")
128+ val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground")
67129
68- val theme = mapOf(
69- "--vscode-editor-foreground" to toHex(editorForeground),
70- "--vscode-editor-background" to toHex(editorBackground),
130+ val inputBackground = namedColor("TextField.background")
131+ val inputForeground = namedColor("TextField.foreground")
132+ val inputPlaceholder = namedColor("TextField.inactiveForeground")
133+
134+ val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background)
135+ val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground")
136+
137+ val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
138+ val listSelectionForeground = namedColor("List.selectionForeground")
71139
72- "--vscode-button-background" to toHex(buttonBackground),
73- "--vscode-button-foreground" to toHex(buttonForeground),
140+ val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground")
74141
75- "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50",
142+ val mutedDescription = namedColor("Component.infoForeground")
143+ ?: namedColor("ContextHelp.foreground")
144+ ?: namedColor("TextField.placeholderForeground")
145+ ?: namedColor("Label.disabledForeground")
146+ ?: namedColor("ToolTip.foreground")
76147
77- "--vscode-quickInputList-focusForeground" to toHex(foreground),
78- "--vscode-quickInput-background" to toHex(inputBackground),
148+ val link = namedColor("Link.activeForeground")
79149
80- "--vscode-badge-background" to toHex(badgeBackground),
81- "--vscode-badge-foreground" to toHex(badgeForeground),
150+ val successColor = namedColor("ValidationSuccess.successColor")
151+ ?: namedColor("Component.successForeground")
152+ ?: namedColor("Label.successForeground")
153+ val warningColor = namedColor("ValidationWarning.warningColor")
154+ ?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor
155+ ?: namedColor("Component.warningForeground")
156+ ?: namedColor("Label.warningForeground")
157+ val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground")
82158
83- "--vscode-input-background" to toHex(inputBackground),
84- "--vscode-input-border" to toHex(border),
85- "--vscode-sideBar-background" to toHex(background),
86- "--vscode-sideBar-border" to toHex(border),
87- "--vscode-focusBorder" to toHex(focusBorder),
159+ val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor")
88160
89- "--vscode-commandCenter-activeBorder" to toHex(focusBorder),
90- "--vscode-commandCenter-inactiveBorder" to toHex(border),
161+ val editorBackground = editorScheme.defaultBackground
162+ val editorForeground = editorScheme.defaultForeground
91163
92- "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40"
93- )
164+ val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
94165
166+ val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?:
167+ editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
168+
169+ // These should match the keys in GUI's theme.ts
170+ val theme = mapOf(
171+ "background" to background,
172+ "foreground" to foreground,
173+ "editor-background" to editorBackground,
174+ "editor-foreground" to editorForeground,
175+ "primary-background" to buttonBackground,
176+ "primary-foreground" to buttonForeground,
177+ "primary-hover" to buttonHoverBackground,
178+ "secondary-background" to secondaryBackground,
179+ "secondary-foreground" to foreground,
180+ "secondary-hover" to secondaryHoverBackground,
181+ "border" to border,
182+ "border-focus" to focusBorder,
183+ "command-background" to commandBackground,
184+ "command-foreground" to commandForeground,
185+ "command-border" to border,
186+ "command-border-focus" to focusBorder,
187+ "description" to description,
188+ "description-muted" to mutedDescription,
189+ "input-background" to inputBackground,
190+ "input-foreground" to inputForeground,
191+ "input-border" to border,
192+ "input-placeholder" to inputPlaceholder,
193+ "table-oddRow" to tableOddRow,
194+ "badge-background" to badgeBackground,
195+ "badge-foreground" to badgeForeground,
196+ "success" to successColor,
197+ "warning" to warningColor,
198+ "error" to errorColor,
199+ "link" to link,
200+ "accent" to accentColor,
201+ "find-match" to findMatchBackground,
202+ "find-match-selected" to findMatchSelectedBackground,
203+ "list-hover" to listHoverBackground,
204+ "list-active" to actionHoverBackground,
205+ "list-active-foreground" to listSelectionForeground
206+ ).mapValues { toHex(it.value) }
95207 return theme
96208 } catch (error: Error) {
97209 return mapOf()
98210 }
99-
100211 }
101212 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +12 −3
@@ -91,6 +91,15 @@
9191 respond(jsonData)
9292 }
9393
94+ "showFile" -> {
95+ val params = Gson().fromJson(
96+ dataElement.toString(),
97+ ShowFilePayload::class.java
98+ )
99+ ide.openFile(params.filepath)
100+ respond(null)
101+ }
102+
94103 "getIdeSettings" -> {
95104 val settings = ide.getIdeSettings()
96105 respond(settings)
@@ -438,7 +447,7 @@
438447 "acceptDiff" -> {
439448 val params = Gson().fromJson(
440449 dataElement.toString(),
441- AcceptDiffParams::class.java
450+ AcceptOrRejectDiffPayload::class.java
442451 )
443452 val filepath = params.filepath;
444453
@@ -454,7 +463,7 @@
454463 "rejectDiff" -> {
455464 val params = Gson().fromJson(
456465 dataElement.toString(),
457- RejectDiffParams::class.java
466+ AcceptOrRejectDiffPayload::class.java
458467 )
459468 val filepath = params.filepath;
460469
@@ -493,7 +502,7 @@
493502
494503 fun sendHighlightedCode(edit: Boolean = false) {
495504 val editor = EditorUtils.getEditor(project)
496- val rif = editor?.getHighlightedCode() ?: return
505+ val rif = editor?.getHighlightedRIF() ?: return
497506
498507 continuePluginService.sendToWebview(
499508 "highlightedCode",
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +0 −1
@@ -337,6 +337,5 @@
337337 private fun setClosed() {
338338 sendUpdate(ApplyStateStatus.CLOSED)
339339 resetState()
340- onClose()
341340 }
342341 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +14 −11
@@ -1,7 +1,5 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3-import com.github.continuedev.continueintellijextension.Position
4-import com.github.continuedev.continueintellijextension.Range
53 import com.github.continuedev.continueintellijextension.utils.toUriOrNull
64 import com.intellij.openapi.application.ApplicationManager
75 import com.intellij.openapi.command.WriteCommandAction
@@ -72,28 +70,33 @@
7270 editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
7371 }
7472
73+ /**
74+ * Remove the selected range in a thread-safe manner
75+ */
76+ fun removeSelection() {
77+ ApplicationManager.getApplication().invokeLater {
78+ editor.selectionModel.removeSelection()
79+ }
80+ }
7581
7682 /**
7783 * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
7884 */
79- fun extractCodeRanges(): Triple<String, String, String> {
80- val rif = getHighlightedCode()
85+ fun getHighlightedRangeTriplet(): Triple<String, String, String> {
86+ val rif = getHighlightedRIF()
8187
8288 return if (rif == null) {
8389 // If no highlight, use the whole document as highlighted
8490 Triple("", editor.document.text, "")
8591 } else {
8692 // Use the RangeInFileWithContents to get absolute offsets
87- val startOffset = rif.getStartOffset(editor.document)
88- val endOffset = rif.getEndOffset(editor.document)
93+ val (startOffset, endOffset) = rif.offsets
94+
8995 val prefix = editor.document.getText(TextRange(0, startOffset))
9096 val highlighted = rif.contents
9197 val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
9298
93- // Remove the selection after processing
94- ApplicationManager.getApplication().invokeLater {
95- editor.selectionModel.removeSelection()
96- }
99+ removeSelection()
97100
98101 Triple(prefix, highlighted, suffix)
99102 }
@@ -103,7 +106,7 @@
103106 * Gets the selected code from the current editor.
104107 * Returns null if there is no selection.
105108 */
106- fun getHighlightedCode(): RangeInFileWithContents? {
109+ fun getHighlightedRIF(): RangeInFileWithContents? {
107110 return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
108111 val virtualFile =
109112 FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +1 −740
@@ -1,337 +1,11 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3-import com.github.continuedev.continueintellijextension.`continue`.GetTheme
4-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
5-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6-import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
7-import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
8-import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
9-import com.intellij.openapi.Disposable
103 import com.intellij.openapi.actionSystem.ActionUpdateThread
114 import com.intellij.openapi.actionSystem.AnAction
125 import com.intellij.openapi.actionSystem.AnActionEvent
136 import com.intellij.openapi.actionSystem.PlatformDataKeys
14-import com.intellij.openapi.components.service
15-import com.intellij.openapi.editor.Editor
16-import com.intellij.openapi.editor.colors.EditorColorsManager
17-import com.intellij.openapi.editor.colors.EditorFontType
18-import com.intellij.openapi.editor.impl.EditorImpl
197 import com.intellij.openapi.project.DumbAware
20-import com.intellij.openapi.project.Project
21-import com.intellij.openapi.util.IconLoader
22-import com.intellij.openapi.util.Ref
23-import com.intellij.openapi.util.TextRange
24-import com.intellij.ui.JBColor
25-import com.intellij.util.ui.JBUI
26-import com.intellij.util.ui.UIUtil
27-import java.awt.*
28-import java.awt.event.*
29-import java.awt.geom.AffineTransform
30-import java.awt.geom.Path2D
31-import java.awt.geom.RoundRectangle2D
32-import javax.swing.*
33-import javax.swing.event.DocumentEvent
34-import javax.swing.event.DocumentListener
35-import javax.swing.event.ListDataListener
36-import javax.swing.plaf.basic.BasicComboBoxUI
37-import kotlin.math.max
38-import net.miginfocom.swing.MigLayout
39-import org.jdesktop.swingx.JXPanel
40-import org.jdesktop.swingx.JXTextArea
418
42-const val MAIN_FONT_SIZE = 13
43-
44-const val DOWN_ARROW = " ▾"
45-
46-fun makeTextArea(): JTextArea {
47- val textArea =
48- CustomTextArea(1, 40).apply {
49- lineWrap = true
50- wrapStyleWord = true
51- isOpaque = false
52- background = GetTheme().getSecondaryDark()
53- maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
54- margin = JBUI.insets(6, 8, 2, 4)
55- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
56- preferredSize = Dimension(400, 75)
57- }
58- textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
59- return textArea
60-}
61-
62-fun makePanel(
63- project: Project,
64- customPanelRef: Ref<CustomPanel>,
65- textArea: JTextArea,
66- inlayRef: Ref<Disposable>,
67- comboBoxRef: Ref<JComboBox<String>>,
68- leftInset: Int,
69- modelTitles: List<String>,
70- onEnter: () -> Unit,
71- onCancel: () -> Unit,
72- onAccept: () -> Unit,
73- onReject: () -> Unit
74-): JPanel {
75- val topPanel =
76- ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
77- background = JBColor(0x20888888, 0x20888888)
78- isOpaque = false
79- }
80-
81- val panel =
82- CustomPanel(
83- MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
84- project,
85- modelTitles,
86- comboBoxRef,
87- onEnter,
88- onCancel,
89- onAccept,
90- onReject,
91- textArea
92- )
93- .apply {
94- val globalScheme = EditorColorsManager.getInstance().globalScheme
95- val defaultBackground = globalScheme.defaultBackground
96- background = defaultBackground
97- add(textArea, "grow, gap 0!, height 100%")
98-
99- putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
100- preferredSize = textArea.preferredSize
101- setup()
102- }
103-
104- customPanelRef.set(panel)
105-
106- textArea.addComponentListener(
107- object : ComponentAdapter() {
108- override fun componentResized(e: ComponentEvent?) {
109- panel.revalidate()
110- panel.repaint()
111- }
112- })
113-
114- topPanel.add(panel, "grow, gap 0!")
115-
116- return topPanel
117-}
118-
119-fun openInlineEdit(project: Project?, editor: Editor) {
120- if (project == null) return
121-
122- // Don't open in terminal
123- if (EditorUtils(editor).isTerminal()) {
124- return
125- }
126-
127- val manager = EditorComponentInlaysManager.from(editor, true)
128-
129- // Get list of model titles
130- val continuePluginService = project.service<ContinuePluginService>()
131- val modelTitles = mutableListOf<String>()
132-
133- continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
134- val modelsByRole =
135- response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
136- val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
137- modelsByRole.castNestedOrNull<List<*>>(role)
138- ?.mapNotNull { it.castNestedOrNull<String>("title") }
139- ?.let(modelTitles::addAll)
140- }
141-
142- // This is a hacky way to not complicate getting model titles with coroutines
143- // 1500 feels like way upper limit of "would be weird if panel showed up after that long"
144- // And should always allow enough time to load config
145- val maxWaitTime = 1500
146- val startTime = System.currentTimeMillis()
147- while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
148- Thread.sleep(20)
149- }
150-
151- // Get highlighted range
152- val selectionModel = editor.selectionModel
153- val startOffset = selectionModel.selectionStart
154- val endOffset = selectionModel.selectionEnd
155- val startLineNumber = editor.document.getLineNumber(startOffset)
156- var endLineNumber = editor.document.getLineNumber(endOffset)
157-
158- // Doesn't seem to be any built-in methods to check for a line selection that contains trailing
159- // newlines.
160- // The only case this matters is when a user double-clicks to highlight a full line. Without this
161- // check.
162- // the highlighted range will continue to the following line.
163- val isSingleLineSelection =
164- endLineNumber > startLineNumber &&
165- endLineNumber < editor.document.lineCount &&
166- editor.document.getLineStartOffset(endLineNumber) == endOffset
167-
168- if (isSingleLineSelection) {
169- endLineNumber--
170- }
171-
172- val prefix = editor.document.getText(TextRange(0, startOffset))
173- val highlighted = editor.document.getText(TextRange(startOffset, endOffset))
174- val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
175- val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
176-
177- // Un-highlight the selected text
178- selectionModel.removeSelection()
179-
180- // Get indentation width in pixels
181- val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
182- val lineStart = editor.document.getLineStartOffset(indentationLineNum)
183- val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
184- val text = editor.document.getText(TextRange(lineStart, lineEnd))
185- val indentation = text.takeWhile { it == ' ' }.length
186- val charWidth =
187- editor.contentComponent
188- .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
189- .charWidth(' ')
190- val leftInset = indentation * charWidth * 2 / 3
191-
192- val inlayRef = Ref<Disposable>()
193- val customPanelRef = Ref<CustomPanel>()
194-
195- // Create text area, attach key listener
196- val textArea = makeTextArea()
197-
198- // Create diff stream handler
199- val diffStreamHandler =
200- DiffStreamHandler(
201- project,
202- editor,
203- startLineNumber,
204- endLineNumber,
205- {
206- inlayRef.get()?.dispose()
207- },
208- {
209- textArea.document.insertString(textArea.caretPosition, ", ", null)
210- textArea.requestFocus()
211- customPanelRef.get().finish()
212- },
213- null,
214- null
215- )
216-
217- val diffStreamService = project.service<DiffStreamService>()
218- diffStreamService.register(diffStreamHandler, editor)
219-
220- val comboBoxRef = Ref<JComboBox<String>>()
221-
222- fun onEnter() {
223- val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
224- customPanelRef.get().enter()
225- diffStreamHandler.streamDiffLinesToEditor(
226- textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
227- )
228- }
229-
230- val panel =
231- makePanel(
232- project,
233- customPanelRef,
234- textArea,
235- inlayRef,
236- comboBoxRef,
237- leftInset,
238- modelTitles,
239- { onEnter() },
240- {
241- diffStreamService.reject(editor)
242- selectionModel.setSelection(startOffset, endOffset)
243- },
244- {
245- diffStreamService.accept(editor)
246- inlayRef.get().dispose()
247- },
248- {
249- diffStreamService.reject(editor)
250- inlayRef.get().dispose()
251- })
252-
253- val inlay = manager.insert(startLineNumber, panel, true)
254-
255- panel.revalidate()
256- inlayRef.set(inlay)
257- val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
258- viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
259-
260- // Add key listener to text area
261- textArea.addKeyListener(
262- object : KeyAdapter() {
263- override fun keyTyped(e: KeyEvent) {
264- if (customPanelRef.get().isFinished) {
265- customPanelRef.get().setup()
266- }
267- }
268-
269- override fun keyPressed(e: KeyEvent) {
270- when (e.keyCode) {
271- KeyEvent.VK_ESCAPE -> {
272- diffStreamService.reject(editor)
273- selectionModel.setSelection(startOffset, endOffset)
274- }
275-
276- KeyEvent.VK_ENTER -> {
277- when (e.modifiersEx) {
278- KeyEvent.SHIFT_DOWN_MASK -> {
279- textArea.document.insertString(textArea.caretPosition, "\n", null)
280- }
281-
282- 0 -> {
283- onEnter()
284- e.consume()
285- }
286- }
287- }
288- }
289- }
290-
291- // We need this because backspace/delete is not registering properly on keyPressed for an
292- // unknown reason
293- override fun keyReleased(e: KeyEvent) {
294- if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
295- if (customPanelRef.get().isFinished) {
296- customPanelRef.get().setup()
297- }
298- }
299- }
300- })
301-
302- // Listen for changes to textarea line count
303- textArea.document.addDocumentListener(
304- object : DocumentListener {
305- private var lastNumLines: Int = 0
306-
307- private fun updateSize() {
308- val numLines = textArea.text.lines().size
309- if (numLines != lastNumLines) {
310- lastNumLines = numLines
311- viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
312- }
313- }
314-
315- override fun insertUpdate(e: DocumentEvent?) {
316- updateSize()
317- }
318-
319- override fun removeUpdate(e: DocumentEvent?) {
320- updateSize()
321- }
322-
323- override fun changedUpdate(e: DocumentEvent?) {
324- updateSize()
325- }
326- })
327-
328- textArea.requestFocus()
329-}
330-
331-/**
332- * Adapted from
333- * https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
334- */
3359 class InlineEditAction : AnAction(), DumbAware {
33610 override fun update(e: AnActionEvent) {
33711 e.presentation.isEnabled = true
@@ -347,417 +21,4 @@
34721 val project = e.getData(PlatformDataKeys.PROJECT) ?: return
34822 openInlineEdit(project, editor)
34923 }
350-}
351-
352-class CustomPanel(
353- layout: MigLayout,
354- project: Project,
355- modelTitles: List<String>,
356- comboBoxRef: Ref<JComboBox<String>>,
357- private val onEnter: () -> Unit,
358- private val onCancel: () -> Unit,
359- private val onAccept: () -> Unit,
360- private val onReject: () -> Unit,
361- private val textArea: JTextArea
362-) : JPanel(layout) {
363- private val shadowSize = 5
364- private val cornerRadius = 8
365- private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
366- private val borderColor = Color(128, 128, 128, 128)
367- private val borderThickness = 1
368- private val triangleSize = 6
369- private val rightMargin = 3.0
370- private val closeButton: JComponent = createCloseButton()
371- private val originalTextColor: Color = textArea.foreground
372- private val greyTextColor: Color = Color(128, 128, 128, 200)
373- var isFinished = false
374-
375- init {
376- isOpaque = false
377- add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
378- }
379-
380- private fun createCloseButton(): JComponent {
381- val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
382- return JLabel(closeIcon).apply {
383- background = Color(0, 0, 0, 0)
384- border = JBUI.Borders.empty(2, 6, 2, 0)
385- toolTipText = "`esc` to cancel"
386- isOpaque = false
387- addMouseListener(
388- object : MouseAdapter() {
389- override fun mouseEntered(e: MouseEvent) {
390- cursor = Cursor(Cursor.HAND_CURSOR)
391- }
392-
393- override fun mouseExited(e: MouseEvent) {
394- cursor = Cursor.getDefaultCursor()
395- }
396-
397- override fun mouseClicked(e: MouseEvent) {
398- onCancel()
399- }
400- })
401- }
402- }
403-
404- private val subPanelA: JPanel =
405- JPanel(MigLayout("insets 0, fillx")).apply {
406- val globalScheme = EditorColorsManager.getInstance().globalScheme
407- val defaultBackground = globalScheme.defaultBackground
408- val continueSettingsService = service<ContinueExtensionSettings>()
409- val dropdown =
410- JComboBox(modelTitles.toTypedArray()).apply {
411- setUI(TransparentArrowButtonUI())
412- isEditable = true
413- background = defaultBackground
414- foreground = Color(128, 128, 128, 200)
415- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
416- border = JBUI.Borders.empty(8)
417- isOpaque = false
418- isEditable = false
419- cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
420- preferredSize = Dimension(200, 30)
421-
422- renderer = object : DefaultListCellRenderer() {
423- override fun getListCellRendererComponent(
424- list: JList<*>?,
425- value: Any?,
426- index: Int,
427- isSelected: Boolean,
428- cellHasFocus: Boolean
429- ): Component {
430- val component =
431- super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
432- if (component is JLabel) {
433- component.border = JBUI.Borders.empty(4, 6)
434- }
435- return component
436- }
437- }.apply {
438- horizontalAlignment = SwingConstants.LEFT
439- }
440-
441- selectedIndex =
442- if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
443- if (modelTitles.isEmpty()) -1
444- else {
445- val index = modelTitles.indexOf(it)
446- if (index != -1) index else 0
447- }
448- } ?: 0
449-
450- addActionListener {
451- continueSettingsService.continueState.lastSelectedInlineEditModel =
452- (selectedItem as String).removeSuffix(DOWN_ARROW)
453- }
454- }
455-
456- comboBoxRef.set(dropdown)
457-
458- val rightButton =
459- CustomButton("⏎ Enter") { onEnter() }
460- .apply {
461- background = globalScheme.defaultForeground
462- foreground = globalScheme.defaultBackground
463- border = JBUI.Borders.empty(2, 6)
464- }
465-
466- val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
467- isOpaque = false
468- add(rightButton, "align right")
469- }
470-
471- border = JBUI.Borders.empty(0, 0, 16, 12)
472- isOpaque = false
473-
474- add(dropdown, "align left")
475- add(rightPanel, "align right")
476-
477- cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
478- }
479-
480- private val subPanelB: JPanel =
481- JPanel(BorderLayout()).apply {
482- isOpaque = false
483-
484- val progressBar = JProgressBar().apply { isIndeterminate = true }
485-
486- add(progressBar, BorderLayout.CENTER)
487- border = JBUI.Borders.empty(0, 0, 16, 12)
488- }
489-
490- private val subPanelC: JPanel =
491- JPanel(MigLayout("insets 0, fillx")).apply {
492- val leftLabel =
493- JLabel("Type to re-prompt").apply {
494- foreground = Color(156, 163, 175) // text-gray-400
495- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
496- border = JBUI.Borders.emptyLeft(4)
497- }
498-
499- val leftButton =
500- CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
501- .apply {
502- background = JBColor(0x30FF0000, 0x30FF0000)
503- }
504-
505- val rightButton =
506- CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
507- .apply {
508- background = JBColor(0x3000FF00, 0x3000FF00)
509- }
510-
511- val rightPanel =
512- JPanel(MigLayout("insets 0, fillx")).apply {
513- isOpaque = false
514- add(leftButton, "align right")
515- add(rightButton, "align right")
516- border = JBUI.Borders.empty()
517- }
518-
519- add(leftLabel, "align left")
520- add(rightPanel, "align right")
521- border = JBUI.Borders.empty(0, 0, 16, 12)
522- isOpaque = false
523- }
524-
525- fun setup() {
526- remove(subPanelB)
527- remove(subPanelC)
528- add(subPanelA, "grow, gap 0!")
529- isFinished = false
530- revalidate()
531- repaint()
532- textArea.foreground = originalTextColor
533- }
534-
535- fun enter() {
536- remove(subPanelA)
537- remove(subPanelC)
538- add(subPanelB, "grow, gap 0!")
539- revalidate()
540- repaint()
541- }
542-
543- fun finish() {
544- remove(subPanelB)
545- add(subPanelC, "grow, gap 0!")
546- revalidate()
547- repaint()
548- isFinished = true
549- textArea.foreground = greyTextColor
550- }
551-
552- override fun paintComponent(g: Graphics) {
553- super.paintComponent(g)
554-
555- val g2 = g as Graphics2D
556- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
557-
558- val w = width - shadowSize
559- val h = height - shadowSize
560-
561- // Create the shape for the tooltip/triangle
562- val shape = Path2D.Double()
563- shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
564- shape.quadTo(
565- borderThickness / 2.0,
566- borderThickness / 2.0,
567- cornerRadius.toDouble(),
568- borderThickness / 2.0
569- )
570- shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
571- shape.quadTo(
572- w - borderThickness / 2.0 - rightMargin,
573- borderThickness / 2.0,
574- w - borderThickness / 2.0 - rightMargin,
575- cornerRadius.toDouble()
576- )
577- shape.lineTo(
578- w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
579- )
580- shape.quadTo(
581- w - borderThickness / 2.0 - rightMargin,
582- h - triangleSize.toDouble(),
583- w - cornerRadius.toDouble() - rightMargin,
584- h - triangleSize.toDouble()
585- )
586- shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
587- shape.lineTo(borderThickness / 2.0, h.toDouble())
588- shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
589-
590- // Draw shadow
591- g2.color = shadowColor
592- g2.fill(
593- shape.createTransformedShape(
594- AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
595- )
596- )
597-
598- // Draw main shape
599- g2.color = background
600- g2.fill(shape)
601-
602- // Draw border
603- g2.color = borderColor
604- g2.stroke = BasicStroke(borderThickness.toFloat())
605- g2.draw(shape)
606- }
607-}
608-
609-class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
610- private var isHovered = false
611-
612- init {
613- isOpaque = false
614- cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
615- addMouseListener(
616- object : MouseAdapter() {
617- override fun mouseEntered(e: MouseEvent?) {
618- isHovered = true
619- repaint()
620- }
621-
622- override fun mouseExited(e: MouseEvent?) {
623- isHovered = false
624- repaint()
625- }
626-
627- override fun mouseClicked(e: MouseEvent?) {
628- onClick()
629- }
630- })
631-
632- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
633- border = JBUI.Borders.empty(2, 6)
634- }
635-
636- override fun paintComponent(g: Graphics) {
637- val g2 = g as Graphics2D
638- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
639-
640- val cornerRadius = 8
641- val rect = Rectangle(0, 0, width, height)
642- val roundRect =
643- RoundRectangle2D.Float(
644- rect.x.toFloat(),
645- rect.y.toFloat(),
646- rect.width.toFloat(),
647- rect.height.toFloat(),
648- cornerRadius.toFloat(),
649- cornerRadius.toFloat()
650- )
651- g2.color = background
652- g2.fill(roundRect)
653- g2.color = foreground
654- g2.drawString(
655- text,
656- (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
657- (height / 2 + g.fontMetrics.ascent / 2).toFloat()
658- )
659- }
660-}
661-
662-class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
663- init {
664- setRows(rows)
665- setColumns(columns)
666- }
667-
668- override fun paintComponent(g: Graphics) {
669- // Draw placeholder
670- if (text.isEmpty()) {
671- g.color = Color(128, 128, 128, 255)
672- g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
673- g.drawString("Enter instructions...", 8, 20)
674- }
675-
676- super.paintComponent(g)
677- }
678-}
679-
680-class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
681- override fun getPreferredSize(): Dimension {
682- val prefSize = super.getPreferredSize()
683- val insets = getInsets()
684- prefSize.width += insets.left + insets.right
685- prefSize.height += insets.top + insets.bottom
686- return prefSize
687- }
688-
689- override fun paintComponent(g: Graphics) {
690- super.paintComponent(g)
691- }
692-}
693-
694-class TransparentArrowButtonUI : BasicComboBoxUI() {
695- override fun createArrowButton() =
696- JButton().apply {
697- isVisible = false
698- preferredSize = Dimension(0, 0)
699- }
700-
701- override fun getInsets(): Insets {
702- return JBUI.insetsLeft(6)
703- }
704-
705- override fun installUI(c: JComponent?) {
706- super.installUI(c)
707- comboBox.isOpaque = false
708- val globalScheme = EditorColorsManager.getInstance().globalScheme
709- val defaultBackground = globalScheme.defaultBackground
710- comboBox.background = defaultBackground
711-
712- // Modify the ComboBoxModel to include the down symbol
713- val originalModel = comboBox.model
714- comboBox.model =
715- object : ComboBoxModel<Any> {
716- override fun getSize(): Int = originalModel.size
717-
718- override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
719-
720- override fun setSelectedItem(anItem: Any?) {
721- originalModel.selectedItem = anItem
722- }
723-
724- override fun getSelectedItem(): Any? {
725- val item = originalModel.selectedItem
726- return "$item$DOWN_ARROW"
727- }
728-
729- override fun addListDataListener(l: ListDataListener?) {
730- originalModel.addListDataListener(l)
731- }
732-
733- override fun removeListDataListener(l: ListDataListener?) {
734- originalModel.removeListDataListener(l)
735- }
736- }
737- }
738-
739- override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
740- // Do nothing to prevent painting the background
741- }
742-
743- override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
744- val renderer = comboBox.renderer
745- val item = comboBox.selectedItem
746-
747- if (item != null) {
748- val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
749- c.font = comboBox.font
750- c.foreground = Color(156, 163, 175) // text-gray-400
751- c.background = comboBox.background
752-
753- if (c is JComponent) {
754- c.isOpaque = false
755- }
756-
757- val currentValuePane = currentValuePane
758- currentValuePane.paintComponent(
759- g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
760- )
761- }
762- }
763-}
24+}
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +746 −0
@@ -0,0 +1,746 @@
1+package com.github.continuedev.continueintellijextension.editor
2+
3+import com.github.continuedev.continueintellijextension.`continue`.GetTheme
4+import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
5+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
7+import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
8+import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
9+import com.intellij.openapi.Disposable
10+import com.intellij.openapi.components.service
11+import com.intellij.openapi.editor.Editor
12+import com.intellij.openapi.editor.colors.EditorColorsManager
13+import com.intellij.openapi.editor.colors.EditorFontType
14+import com.intellij.openapi.editor.impl.EditorImpl
15+import com.intellij.openapi.project.Project
16+import com.intellij.openapi.util.IconLoader
17+import com.intellij.openapi.util.Ref
18+import com.intellij.openapi.util.TextRange
19+import com.intellij.ui.JBColor
20+import com.intellij.util.ui.JBUI
21+import com.intellij.util.ui.UIUtil
22+import java.awt.*
23+import java.awt.event.*
24+import java.awt.geom.AffineTransform
25+import java.awt.geom.Path2D
26+import java.awt.geom.RoundRectangle2D
27+import javax.swing.*
28+import javax.swing.event.DocumentEvent
29+import javax.swing.event.DocumentListener
30+import javax.swing.event.ListDataListener
31+import javax.swing.plaf.basic.BasicComboBoxUI
32+import kotlin.math.max
33+import net.miginfocom.swing.MigLayout
34+import org.jdesktop.swingx.JXPanel
35+import org.jdesktop.swingx.JXTextArea
36+
37+const val MAIN_FONT_SIZE = 13
38+const val DOWN_ARROW = " ▾"
39+const val MAX_MODEL_WAIT_TIME = 1500
40+
41+/**
42+ * Fetches and combines available model titles from both "edit" and "chat" roles.
43+ * Edit models are prioritized and appear first in the returned list.
44+ * Handles duplicate models by only including them once (prioritizing edit role).
45+ *
46+ * @param continuePluginService The service used to fetch config information
47+ * @return List of model titles with edit models first, duplicates removed
48+ * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds
49+ */
50+fun getModelTitles(continuePluginService: ContinuePluginService): List<String> {
51+ val modelTitles = mutableListOf<String>()
52+
53+ continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
54+ val modelsByRole =
55+ response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
56+
57+ // Get edit models first
58+ val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
59+ ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
60+
61+ // Then get chat models
62+ val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
63+ ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
64+
65+ // Add edit models first, then chat models (avoiding duplicates)
66+ modelTitles.addAll(editModels)
67+ modelTitles.addAll(chatModels.filter { it !in editModels })
68+ }
69+
70+ val startTime = System.currentTimeMillis()
71+ while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) {
72+ Thread.sleep(20)
73+ }
74+
75+ return modelTitles
76+}
77+
78+fun makeTextArea(): JTextArea {
79+ val textArea =
80+ CustomTextArea(1, 40).apply {
81+ lineWrap = true
82+ wrapStyleWord = true
83+ isOpaque = false
84+ background = GetTheme().getSecondaryDark()
85+ maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
86+ margin = JBUI.insets(6, 8, 2, 4)
87+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
88+ preferredSize = Dimension(400, 75)
89+ }
90+ textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
91+ return textArea
92+}
93+
94+fun makePanel(
95+ project: Project,
96+ customPanelRef: Ref<CustomPanel>,
97+ textArea: JTextArea,
98+ inlayRef: Ref<Disposable>,
99+ comboBoxRef: Ref<JComboBox<String>>,
100+ leftInset: Int,
101+ modelTitles: List<String>,
102+ onEnter: () -> Unit,
103+ onCancel: () -> Unit,
104+ onAccept: () -> Unit,
105+ onReject: () -> Unit
106+): JPanel {
107+ val topPanel =
108+ ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
109+ background = JBColor(0x20888888, 0x20888888)
110+ isOpaque = false
111+ }
112+
113+ val panel =
114+ CustomPanel(
115+ MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
116+ project,
117+ modelTitles,
118+ comboBoxRef,
119+ onEnter,
120+ onCancel,
121+ onAccept,
122+ onReject,
123+ textArea
124+ )
125+ .apply {
126+ val globalScheme = EditorColorsManager.getInstance().globalScheme
127+ val defaultBackground = globalScheme.defaultBackground
128+ background = defaultBackground
129+ add(textArea, "grow, gap 0!, height 100%")
130+
131+ putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
132+ preferredSize = textArea.preferredSize
133+ setup()
134+ }
135+
136+ customPanelRef.set(panel)
137+
138+ textArea.addComponentListener(
139+ object : ComponentAdapter() {
140+ override fun componentResized(e: ComponentEvent?) {
141+ panel.revalidate()
142+ panel.repaint()
143+ }
144+ })
145+
146+ topPanel.add(panel, "grow, gap 0!")
147+
148+ return topPanel
149+}
150+
151+fun openInlineEdit(project: Project?, editor: Editor) {
152+ if (project == null) return
153+
154+ val editorUtils = EditorUtils(editor)
155+
156+ // Don't open in terminal
157+ if (editorUtils.isTerminal()) {
158+ return
159+ }
160+
161+ val manager = EditorComponentInlaysManager.from(editor, true)
162+
163+ val continuePluginService = project.service<ContinuePluginService>()
164+ val modelTitles = getModelTitles(continuePluginService)
165+
166+ val highlightedRIF = editorUtils.getHighlightedRIF() ?: return
167+ val (startLineNumber, endLineNumber) = highlightedRIF.lines
168+ val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets
169+
170+
171+ val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
172+ val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
173+
174+ editorUtils.removeSelection()
175+
176+ // Get indentation width in pixels
177+ val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
178+ val lineStart = editor.document.getLineStartOffset(indentationLineNum)
179+ val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
180+ val text = editor.document.getText(TextRange(lineStart, lineEnd))
181+ val indentation = text.takeWhile { it == ' ' }.length
182+ val charWidth =
183+ editor.contentComponent
184+ .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
185+ .charWidth(' ')
186+ val leftInset = indentation * charWidth * 2 / 3
187+
188+ val inlayRef = Ref<Disposable>()
189+ val customPanelRef = Ref<CustomPanel>()
190+
191+ // Create text area, attach key listener
192+ val textArea = makeTextArea()
193+
194+ // Create diff stream handler
195+ val diffStreamHandler =
196+ DiffStreamHandler(
197+ project,
198+ editor,
199+ startLineNumber,
200+ endLineNumber,
201+ {
202+ inlayRef.get()?.dispose()
203+ },
204+ {
205+ textArea.document.insertString(textArea.caretPosition, ", ", null)
206+ textArea.requestFocus()
207+ customPanelRef.get().finish()
208+ },
209+ null,
210+ null
211+ )
212+
213+ val diffStreamService = project.service<DiffStreamService>()
214+ diffStreamService.register(diffStreamHandler, editor)
215+
216+ val comboBoxRef = Ref<JComboBox<String>>()
217+
218+ fun onEnter() {
219+ val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
220+ customPanelRef.get().enter()
221+ diffStreamHandler.streamDiffLinesToEditor(
222+ textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
223+ )
224+ }
225+
226+ val panel =
227+ makePanel(
228+ project,
229+ customPanelRef,
230+ textArea,
231+ inlayRef,
232+ comboBoxRef,
233+ leftInset,
234+ modelTitles,
235+ { onEnter() },
236+ {
237+ diffStreamService.reject(editor)
238+ editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset)
239+ },
240+ {
241+ diffStreamService.accept(editor)
242+ inlayRef.get().dispose()
243+ },
244+ {
245+ diffStreamService.reject(editor)
246+ inlayRef.get().dispose()
247+ })
248+
249+ val inlay = manager.insert(startLineNumber, panel, true)
250+
251+ panel.revalidate()
252+ inlayRef.set(inlay)
253+ val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
254+ viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
255+
256+ // Add key listener to text area
257+ textArea.addKeyListener(
258+ object : KeyAdapter() {
259+ override fun keyTyped(e: KeyEvent) {
260+ if (customPanelRef.get().isFinished) {
261+ customPanelRef.get().setup()
262+ }
263+ }
264+
265+ override fun keyPressed(e: KeyEvent) {
266+ when (e.keyCode) {
267+ KeyEvent.VK_ESCAPE -> {
268+ diffStreamService.reject(editor)
269+ editorUtils.editor.selectionModel.setSelection(
270+ highlightedStartOffset,
271+ highlightedEndOffset
272+ )
273+ }
274+
275+ KeyEvent.VK_ENTER -> {
276+ when (e.modifiersEx) {
277+ KeyEvent.SHIFT_DOWN_MASK -> {
278+ textArea.document.insertString(textArea.caretPosition, "\n", null)
279+ }
280+
281+ 0 -> {
282+ onEnter()
283+ e.consume()
284+ }
285+ }
286+ }
287+ }
288+ }
289+
290+ // We need this because backspace/delete is not registering properly on keyPressed for an
291+ // unknown reason
292+ override fun keyReleased(e: KeyEvent) {
293+ if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
294+ if (customPanelRef.get().isFinished) {
295+ customPanelRef.get().setup()
296+ }
297+ }
298+ }
299+ })
300+
301+ // Listen for changes to textarea line count
302+ textArea.document.addDocumentListener(
303+ object : DocumentListener {
304+ private var lastNumLines: Int = 0
305+
306+ private fun updateSize() {
307+ val numLines = textArea.text.lines().size
308+ if (numLines != lastNumLines) {
309+ lastNumLines = numLines
310+ viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
311+ }
312+ }
313+
314+ override fun insertUpdate(e: DocumentEvent?) {
315+ updateSize()
316+ }
317+
318+ override fun removeUpdate(e: DocumentEvent?) {
319+ updateSize()
320+ }
321+
322+ override fun changedUpdate(e: DocumentEvent?) {
323+ updateSize()
324+ }
325+ })
326+
327+ textArea.requestFocus()
328+}
329+
330+
331+class CustomPanel(
332+ layout: MigLayout,
333+ project: Project,
334+ modelTitles: List<String>,
335+ comboBoxRef: Ref<JComboBox<String>>,
336+ private val onEnter: () -> Unit,
337+ private val onCancel: () -> Unit,
338+ private val onAccept: () -> Unit,
339+ private val onReject: () -> Unit,
340+ private val textArea: JTextArea
341+) : JPanel(layout) {
342+ private val shadowSize = 5
343+ private val cornerRadius = 8
344+ private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
345+ private val borderColor = Color(128, 128, 128, 128)
346+ private val borderThickness = 1
347+ private val triangleSize = 6
348+ private val rightMargin = 3.0
349+ private val closeButton: JComponent = createCloseButton()
350+ private val originalTextColor: Color = textArea.foreground
351+ private val greyTextColor: Color = Color(128, 128, 128, 200)
352+ var isFinished = false
353+
354+ init {
355+ isOpaque = false
356+ add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
357+ }
358+
359+ private fun createCloseButton(): JComponent {
360+ val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
361+ return JLabel(closeIcon).apply {
362+ background = Color(0, 0, 0, 0)
363+ border = JBUI.Borders.empty(2, 6, 2, 0)
364+ toolTipText = "`esc` to cancel"
365+ isOpaque = false
366+ addMouseListener(
367+ object : MouseAdapter() {
368+ override fun mouseEntered(e: MouseEvent) {
369+ cursor = Cursor(Cursor.HAND_CURSOR)
370+ }
371+
372+ override fun mouseExited(e: MouseEvent) {
373+ cursor = Cursor.getDefaultCursor()
374+ }
375+
376+ override fun mouseClicked(e: MouseEvent) {
377+ onCancel()
378+ }
379+ })
380+ }
381+ }
382+
383+ private val subPanelA: JPanel =
384+ JPanel(MigLayout("insets 0, fillx")).apply {
385+ val globalScheme = EditorColorsManager.getInstance().globalScheme
386+ val defaultBackground = globalScheme.defaultBackground
387+ val continueSettingsService = service<ContinueExtensionSettings>()
388+ val dropdown =
389+ JComboBox(modelTitles.toTypedArray()).apply {
390+ setUI(TransparentArrowButtonUI())
391+ isEditable = true
392+ background = defaultBackground
393+ foreground = Color(128, 128, 128, 200)
394+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
395+ border = JBUI.Borders.empty(8)
396+ isOpaque = false
397+ isEditable = false
398+ cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
399+ preferredSize = Dimension(200, 30)
400+
401+ renderer = object : DefaultListCellRenderer() {
402+ override fun getListCellRendererComponent(
403+ list: JList<*>?,
404+ value: Any?,
405+ index: Int,
406+ isSelected: Boolean,
407+ cellHasFocus: Boolean
408+ ): Component {
409+ val component =
410+ super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
411+ if (component is JLabel) {
412+ component.border = JBUI.Borders.empty(4, 6)
413+ }
414+ return component
415+ }
416+ }.apply {
417+ horizontalAlignment = SwingConstants.LEFT
418+ }
419+
420+ selectedIndex =
421+ if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
422+ if (modelTitles.isEmpty()) -1
423+ else {
424+ val index = modelTitles.indexOf(it)
425+ if (index != -1) index else 0
426+ }
427+ } ?: 0
428+
429+ addActionListener {
430+ continueSettingsService.continueState.lastSelectedInlineEditModel =
431+ (selectedItem as String).removeSuffix(DOWN_ARROW)
432+ }
433+ }
434+
435+ comboBoxRef.set(dropdown)
436+
437+ val rightButton =
438+ CustomButton("⏎ Enter") { onEnter() }
439+ .apply {
440+ background = JBColor.namedColor("Button.startBackground")
441+ foreground = JBColor.namedColor("Button.foreground")
442+ border = JBUI.Borders.empty(2, 6)
443+ }
444+
445+ val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
446+ isOpaque = false
447+ add(rightButton, "align right")
448+ }
449+
450+ border = JBUI.Borders.empty(0, 0, 16, 12)
451+ isOpaque = false
452+
453+ add(dropdown, "align left")
454+ add(rightPanel, "align right")
455+
456+ cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
457+ }
458+
459+ private val subPanelB: JPanel =
460+ JPanel(BorderLayout()).apply {
461+ isOpaque = false
462+
463+ val progressBar = JProgressBar().apply { isIndeterminate = true }
464+
465+ add(progressBar, BorderLayout.CENTER)
466+ border = JBUI.Borders.empty(0, 0, 16, 12)
467+ }
468+
469+ private val subPanelC: JPanel =
470+ JPanel(MigLayout("insets 0, fillx")).apply {
471+ val leftLabel =
472+ JLabel("Type to re-prompt").apply {
473+ foreground = Color(156, 163, 175) // text-gray-400
474+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
475+ border = JBUI.Borders.emptyLeft(4)
476+ }
477+
478+ val leftButton =
479+ CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
480+ .apply {
481+ background = Color(0, 0, 0, 0)
482+ foreground = JBColor.foreground()
483+ border = JBUI.Borders.empty(2, 6)
484+ }
485+
486+ val rightButton =
487+ CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
488+ .apply {
489+ background = JBColor.namedColor("Button.startBackground")
490+ foreground = JBColor.namedColor("Button.foreground")
491+ border = JBUI.Borders.empty(2, 6)
492+ }
493+
494+ val rightPanel =
495+ JPanel(MigLayout("insets 0, fillx")).apply {
496+ isOpaque = false
497+ add(leftButton, "align right")
498+ add(rightButton, "align right")
499+ border = JBUI.Borders.empty()
500+ }
501+
502+ add(leftLabel, "align left")
503+ add(rightPanel, "align right")
504+ border = JBUI.Borders.empty(0, 0, 16, 12)
505+ isOpaque = false
506+ }
507+
508+ fun setup() {
509+ remove(subPanelB)
510+ remove(subPanelC)
511+ add(subPanelA, "grow, gap 0!")
512+ isFinished = false
513+ revalidate()
514+ repaint()
515+ textArea.foreground = originalTextColor
516+ }
517+
518+ fun enter() {
519+ remove(subPanelA)
520+ remove(subPanelC)
521+ add(subPanelB, "grow, gap 0!")
522+ revalidate()
523+ repaint()
524+ }
525+
526+ fun finish() {
527+ remove(subPanelB)
528+ add(subPanelC, "grow, gap 0!")
529+ revalidate()
530+ repaint()
531+ isFinished = true
532+ textArea.foreground = greyTextColor
533+ }
534+
535+ override fun paintComponent(g: Graphics) {
536+ super.paintComponent(g)
537+
538+ val g2 = g as Graphics2D
539+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
540+
541+ val w = width - shadowSize
542+ val h = height - shadowSize
543+
544+ // Create the shape for the tooltip/triangle
545+ val shape = Path2D.Double()
546+ shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
547+ shape.quadTo(
548+ borderThickness / 2.0,
549+ borderThickness / 2.0,
550+ cornerRadius.toDouble(),
551+ borderThickness / 2.0
552+ )
553+ shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
554+ shape.quadTo(
555+ w - borderThickness / 2.0 - rightMargin,
556+ borderThickness / 2.0,
557+ w - borderThickness / 2.0 - rightMargin,
558+ cornerRadius.toDouble()
559+ )
560+ shape.lineTo(
561+ w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
562+ )
563+ shape.quadTo(
564+ w - borderThickness / 2.0 - rightMargin,
565+ h - triangleSize.toDouble(),
566+ w - cornerRadius.toDouble() - rightMargin,
567+ h - triangleSize.toDouble()
568+ )
569+ shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
570+ shape.lineTo(borderThickness / 2.0, h.toDouble())
571+ shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
572+
573+ // Draw shadow
574+ g2.color = shadowColor
575+ g2.fill(
576+ shape.createTransformedShape(
577+ AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
578+ )
579+ )
580+
581+ // Draw main shape
582+ g2.color = background
583+ g2.fill(shape)
584+
585+ // Draw border
586+ g2.color = borderColor
587+ g2.stroke = BasicStroke(borderThickness.toFloat())
588+ g2.draw(shape)
589+ }
590+}
591+
592+class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
593+ private var isHovered = false
594+
595+ init {
596+ isOpaque = false
597+ cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
598+ addMouseListener(
599+ object : MouseAdapter() {
600+ override fun mouseEntered(e: MouseEvent?) {
601+ isHovered = true
602+ repaint()
603+ }
604+
605+ override fun mouseExited(e: MouseEvent?) {
606+ isHovered = false
607+ repaint()
608+ }
609+
610+ override fun mouseClicked(e: MouseEvent?) {
611+ onClick()
612+ }
613+ })
614+
615+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
616+ border = JBUI.Borders.empty(2, 6)
617+ }
618+
619+ override fun paintComponent(g: Graphics) {
620+ val g2 = g as Graphics2D
621+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
622+
623+ val cornerRadius = 8
624+ val rect = Rectangle(0, 0, width, height)
625+ val roundRect =
626+ RoundRectangle2D.Float(
627+ rect.x.toFloat(),
628+ rect.y.toFloat(),
629+ rect.width.toFloat(),
630+ rect.height.toFloat(),
631+ cornerRadius.toFloat(),
632+ cornerRadius.toFloat()
633+ )
634+ g2.color = background
635+ g2.fill(roundRect)
636+ g2.color = foreground
637+ g2.drawString(
638+ text,
639+ (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
640+ (height / 2 + g.fontMetrics.ascent / 2).toFloat()
641+ )
642+ }
643+}
644+
645+class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
646+ init {
647+ setRows(rows)
648+ setColumns(columns)
649+ }
650+
651+ override fun paintComponent(g: Graphics) {
652+ // Draw placeholder
653+ if (text.isEmpty()) {
654+ g.color = Color(128, 128, 128, 255)
655+ g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
656+ g.drawString("Enter instructions...", 8, 20)
657+ }
658+
659+ super.paintComponent(g)
660+ }
661+}
662+
663+class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
664+ override fun getPreferredSize(): Dimension {
665+ val prefSize = super.getPreferredSize()
666+ val insets = getInsets()
667+ prefSize.width += insets.left + insets.right
668+ prefSize.height += insets.top + insets.bottom
669+ return prefSize
670+ }
671+
672+ override fun paintComponent(g: Graphics) {
673+ super.paintComponent(g)
674+ }
675+}
676+
677+class TransparentArrowButtonUI : BasicComboBoxUI() {
678+ override fun createArrowButton() =
679+ JButton().apply {
680+ isVisible = false
681+ preferredSize = Dimension(0, 0)
682+ }
683+
684+ override fun getInsets(): Insets {
685+ return JBUI.insetsLeft(6)
686+ }
687+
688+ override fun installUI(c: JComponent?) {
689+ super.installUI(c)
690+ comboBox.isOpaque = false
691+ val globalScheme = EditorColorsManager.getInstance().globalScheme
692+ val defaultBackground = globalScheme.defaultBackground
693+ comboBox.background = defaultBackground
694+
695+ // Modify the ComboBoxModel to include the down symbol
696+ val originalModel = comboBox.model
697+ comboBox.model =
698+ object : ComboBoxModel<Any> {
699+ override fun getSize(): Int = originalModel.size
700+
701+ override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
702+
703+ override fun setSelectedItem(anItem: Any?) {
704+ originalModel.selectedItem = anItem
705+ }
706+
707+ override fun getSelectedItem(): Any? {
708+ val item = originalModel.selectedItem
709+ return "$item$DOWN_ARROW"
710+ }
711+
712+ override fun addListDataListener(l: ListDataListener?) {
713+ originalModel.addListDataListener(l)
714+ }
715+
716+ override fun removeListDataListener(l: ListDataListener?) {
717+ originalModel.removeListDataListener(l)
718+ }
719+ }
720+ }
721+
722+ override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
723+ // Do nothing to prevent painting the background
724+ }
725+
726+ override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
727+ val renderer = comboBox.renderer
728+ val item = comboBox.selectedItem
729+
730+ if (item != null) {
731+ val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
732+ c.font = comboBox.font
733+ c.foreground = Color(156, 163, 175) // text-gray-400
734+ c.background = comboBox.background
735+
736+ if (c is JComponent) {
737+ c.isOpaque = false
738+ }
739+
740+ val currentValuePane = currentValuePane
741+ currentValuePane.paintComponent(
742+ g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
743+ )
744+ }
745+ }
746+}
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt +59 −11
@@ -12,22 +12,43 @@
1212 class RangeInFileWithContents(
1313 val filepath: String,
1414 val range: Range,
15- val contents: String
15+ val contents: String,
16+ val document: Document
17+
1618 ) {
1719 /**
18- * Returns the absolute document offset for the start position
20+ * The absolute document offset for the start position
21+ */
22+ val startOffset: Int
23+ get() = document.getLineStartOffset(range.start.line) + range.start.character
24+
25+ /**
26+ * The absolute document offset for the end position
27+ */
28+ val endOffset: Int
29+ get() = document.getLineStartOffset(range.end.line) + range.end.character
30+
31+ /**
32+ * The line number where the highlighted range starts (zero-based)
33+ */
34+ val startLine: Int
35+ get() = range.start.line
36+
37+ /**
38+ * The line number where the highlighted range ends (zero-based)
39+ * This already accounts for proper line ending calculations.
1940 */
20- fun getStartOffset(document: Document): Int {
21- return document.getLineStartOffset(range.start.line) + range.start.character
22- }
41+ val endLine: Int
42+ get() = range.end.line
2343
2444 /**
25- * Returns the absolute document offset for the end position
45+ * Both the start and end line numbers of the highlighted range as a pair
2646 */
27- fun getEndOffset(document: Document): Int {
28- return document.getLineStartOffset(range.end.line) + range.end.character
29- }
47+ val lines: Pair<Int, Int>
48+ get() = Pair(startLine, endLine)
3049
50+ val offsets: Pair<Int, Int>
51+ get() = Pair(startOffset, endOffset)
3152
3253 companion object {
3354 /**
@@ -45,6 +66,13 @@
4566 val startChar = selectionStart - document.getLineStartOffset(startLine)
4667 val endChar = selectionEnd - document.getLineStartOffset(endLine)
4768
69+ // Adjust end line if it's a single line selection with trailing newlines
70+ val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) {
71+ endLine - 1
72+ } else {
73+ endLine
74+ }
75+
4876 val selectedText = document.getText(
4977 TextRange(selectionStart, selectionEnd)
5078 )
@@ -53,10 +81,30 @@
5381 filepath,
5482 Range(
5583 Position(startLine, startChar),
56- Position(endLine, endChar)
84+ Position(adjustedEndLine, endChar)
5785 ),
58- selectedText
86+ selectedText,
87+ document
5988 )
6089 }
90+
91+ /**
92+ * Checks if the selection spans to the next line only because of trailing newlines.
93+ * This matters when a user double-clicks to highlight a full line.
94+ *
95+ * @return true if the selection is actually a single line selection with trailing newline
96+ */
97+ fun isSelectionWithTrailingNewline(
98+ document: Document,
99+ selectionStart: Int,
100+ selectionEnd: Int
101+ ): Boolean {
102+ val startLine = document.getLineNumber(selectionStart)
103+ val endLine = document.getLineNumber(selectionEnd)
104+
105+ return endLine > startLine &&
106+ endLine < document.lineCount &&
107+ document.getLineStartOffset(endLine) == selectionEnd
108+ }
61109 }
62110 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +3 −2
@@ -166,7 +166,7 @@
166166 val rejectBtn =
167167 createButton(
168168 "${getAltKeyLabel()}${getShiftKeyLabel()}N",
169- JBColor(0x77FF0000, 0x77FF0000)
169+ JBColor(0xFF0000, 0xFF0000)
170170 ).apply {
171171 addActionListener {
172172 handleReject()
@@ -178,13 +178,14 @@
178178 createButton(
179179 "${getAltKeyLabel()}${
180180 getShiftKeyLabel()
181- }Y", JBColor(0x7700BB00, 0x7700BB00)
181+ }Y", JBColor(0x00BB00, 0x00BB00)
182182 ).apply {
183183 addActionListener {
184184 handleAccept()
185185 }
186186 }
187187
188+
188189 return Pair(acceptBtn, rejectBtn)
189190 }
190191
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +0 −10
@@ -15,16 +15,6 @@
1515 val toolCallId: String?
1616 )
1717
18-data class AcceptDiffParams(
19- val filepath: String,
20- val streamId: String
21-)
22-
23-data class RejectDiffParams(
24- val filepath: String,
25- val streamId: String
26-)
27-
2818 data class InsertAtCursorParams(
2919 val text: String
3020 )
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +4 −0
@@ -250,4 +250,8 @@
250250 data class AcceptOrRejectDiffPayload(
251251 val filepath: String,
252252 val streamId: String? = null
253+)
254+
255+data class ShowFilePayload(
256+ val filepath: String
253257 )
No newline at the end of the file
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +2 −2
@@ -78,9 +78,9 @@
7878 class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
7979 text="Reject Diff" description="Reject Diff">
8080 <keyboard-shortcut keymap="$default"
81- first-keystroke="shift ctrl DELETE"/>
81+ first-keystroke="shift ctrl BACK_SPACE"/>
8282 <keyboard-shortcut keymap="Mac OS X"
83- first-keystroke="shift meta DELETE"/>
83+ first-keystroke="shift meta BACK_SPACE"/>
8484 <override-text place="GoToAction" text="Continue: Reject Diff"/>
8585 </action>
8686
modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

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.36",
5+ "version": "1.1.38",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -105,7 +105,7 @@
105105 "continue.enableQuickActions": {
106106 "type": "boolean",
107107 "default": false,
108- "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/features/quick-actions)"
108+ "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/customize/deep-dives/vscode-actions#quick-actions)"
109109 },
110110 "continue.enableTabAutocomplete": {
111111 "type": "boolean",
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/App.tsx +5 −0
@@ -9,6 +9,7 @@
99 import Chat from "./pages/gui";
1010 import History from "./pages/history";
1111 import Stats from "./pages/stats";
12+import ThemePage from "./styles/ThemePage";
1213 import { ROUTES } from "./util/navigation";
1314
1415 const router = createMemoryRouter([
@@ -37,6 +38,10 @@
3738 path: ROUTES.CONFIG,
3839 element: <ConfigPage />,
3940 },
41+ {
42+ path: ROUTES.THEME,
43+ element: <ThemePage />,
44+ },
4045 ],
4146 },
4247 ]);
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +1 −12
@@ -3,6 +3,7 @@
33 import { lightGray, vscForeground } from "../..";
44 import { IdeMessengerContext } from "../../../context/IdeMessenger";
55 import { isJetBrains } from "../../../util";
6+import { extractCommand } from "../utils/commandExtractor";
67
78 interface RunInTerminalButtonProps {
89 command: string;
@@ -16,18 +17,6 @@
1617 return null;
1718 }
1819
19- // Extract just the command line (the line after $ or the first line)
20- function extractCommand(cmd: string): string {
21- // If the command contains a $ prompt, extract the line after it
22- if (cmd.includes("$")) {
23- const match = cmd.match(/\$\s*([^\n]+)/);
24- return match ? match[1].trim() : "";
25- }
26-
27- // Otherwise, just take the first line
28- return cmd.split("\n")[0].trim();
29- }
30-
3120 function runInTerminal() {
3221 // Extract just the command line
3322 const extractedCommand = extractCommand(command);
modified gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +1 −8
@@ -44,14 +44,7 @@
4444 data-tooltip-id={id}
4545 data-tooltip-delay-show={500}
4646 >
47- <code
48- className="align-middle"
49- style={{
50- color: "var(--vscode-textLink-foreground)",
51- }}
52- >
53- {content}
54- </code>
47+ <code className="text-link align-middle">{content}</code>
5548 </span>
5649 <ToolTip id={id} place="top" className="m-0 p-0">
5750 <pre className="text-left">{processedContent ?? symbol.filepath}</pre>
added gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts +80 −0
@@ -0,0 +1,80 @@
1+import { extractCommand } from './commandExtractor';
2+
3+describe('extractCommand', () => {
4+ // Test basic command extraction
5+ it('should extract command from $ prompt', () => {
6+ expect(extractCommand('$ echo hello')).toBe('echo hello');
7+ expect(extractCommand('$ echo hello')).toBe('echo hello');
8+ expect(extractCommand('$echo hello')).toBe('echo hello');
9+ });
10+
11+ // Test comment removal
12+ it('should remove comments at beginning of lines', () => {
13+ expect(extractCommand('# shell comment\necho hello')).toBe('echo hello');
14+ expect(extractCommand('// js comment\necho hello')).toBe('echo hello');
15+ expect(extractCommand('/* multi-line\ncomment */\necho hello')).toBe('echo hello');
16+ });
17+
18+ // Test multiline comment removal
19+ it('should remove multiline comments anywhere in the text', () => {
20+ expect(extractCommand('echo /* comment */ hello')).toBe('echo hello');
21+ expect(extractCommand('echo hello /* comment */')).toBe('echo hello');
22+ expect(extractCommand('echo /* multiple\nline\ncomment */ hello')).toBe('echo hello');
23+ });
24+
25+ // Test line continuation handling
26+ it('should handle line continuations correctly', () => {
27+ expect(extractCommand('echo hello && \\\necho world')).toBe('echo hello && echo world');
28+ expect(extractCommand('echo hello | \\\ngrep h')).toBe('echo hello | grep h');
29+ expect(extractCommand('echo hello \\\nworld')).toBe('echo hello world');
30+ });
31+
32+ // Test complex command combinations
33+ it('should handle complex command combinations', () => {
34+ expect(extractCommand(`
35+ # shell comment
36+ echo hello /* inline comment */ && \\
37+ // js comment
38+ echo world
39+ `)).toBe('echo hello && echo world');
40+ });
41+
42+ // Test empty and whitespace handling
43+ it('should handle empty and whitespace inputs', () => {
44+ expect(extractCommand('')).toBe('');
45+ expect(extractCommand(' \n \t ')).toBe('');
46+ });
47+
48+ // Test comment-only inputs
49+ it('should handle comment-only inputs', () => {
50+ expect(extractCommand('/* comment */')).toBe('');
51+ expect(extractCommand('# comment')).toBe('');
52+ expect(extractCommand('// comment')).toBe('');
53+ expect(extractCommand('/* multi\nline\ncomment */')).toBe('');
54+ });
55+
56+ // Test inline comments
57+ it('should handle inline comments correctly according to implementation', () => {
58+ // But removes multiline comments even when inline
59+ expect(extractCommand('/* inline */ echo hello world')).toBe('echo hello world');
60+ });
61+
62+ // Test multiple line continuations
63+ it('should handle multiple line continuations', () => {
64+ expect(extractCommand(`
65+ echo hello && \\
66+ echo world && \\
67+ echo test
68+ `)).toBe('echo hello && echo world && echo test');
69+ });
70+
71+ // Test nested line continuations
72+ it('should handle nested line continuations', () => {
73+ expect(extractCommand(`
74+ echo hello && \\
75+ (echo nested && \\
76+ echo more) && \\
77+ echo final
78+ `)).toBe('echo hello && (echo nested && echo more) && echo final');
79+ });
80+});
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts +50 −0
@@ -0,0 +1,50 @@
1+/**
2+ * Extracts and processes command strings, handling comments and line continuations.
3+ * @param cmd The command string to process
4+ * @returns The processed command string
5+ */
6+export function extractCommand(cmd: string): string {
7+ if (!cmd || cmd.trim() === '') {
8+ return '';
9+ }
10+
11+ // Remove multi-line comments (/* ... */) and replace with a single space
12+ cmd = cmd.replace(/\/\*[\s\S]*?\*\//g, " ");
13+
14+ // Handle the $ prompt case first
15+ if (cmd.includes("$")) {
16+ const match = cmd.match(/\$\s*([^\n]+)/);
17+ if (match) {
18+ // Return just the command after $ without further processing
19+ return match[1].trim();
20+ }
21+ }
22+
23+ // Process lines - remove single-line comments only at beginning of lines
24+ const lines = cmd.split('\n')
25+ .map(line => line.replace(/^\s*#.*$/, '').replace(/^\s*\/\/.*$/, ''))
26+ .map(line => line.trim())
27+ .filter(line => line);
28+
29+ // Join lines with proper handling of continuations
30+ let result = '';
31+ for (let i = 0; i < lines.length; i++) {
32+ let line = lines[i];
33+
34+ // Remove trailing continuation characters and join with next line
35+ while (
36+ (line.endsWith('&&') || line.endsWith('|') || line.endsWith('\\')) &&
37+ i < lines.length - 1
38+ ) {
39+ // Remove the continuation character(s) and any trailing spaces
40+ line = line.replace(/(&&|\||\\)\s*$/, '').trim();
41+ // Join with the next line
42+ i++;
43+ line += ' ' + lines[i];
44+ }
45+
46+ result += line + ' ';
47+ }
48+
49+ return result.trim().replace(/\s+/g, ' ');
50+}
No newline at the end of the file
modified gui/src/components/TabBar/TabBar.tsx +23 −42
@@ -13,13 +13,25 @@
1313 } from "../../redux/slices/tabsSlice";
1414 import { AppDispatch, RootState } from "../../redux/store";
1515 import { loadSession, saveCurrentSession } from "../../redux/thunks/session";
16+import { varWithFallback } from "../../styles/theme";
17+
18+// Haven't set up theme colors for tabs yet
19+// Will keep it simple and choose from existing ones. Comments show vars we could use
20+const tabBorderVar = varWithFallback("border"); // --vscode-tab-border
21+const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground
22+const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground
23+const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground
24+const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground
25+const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground
26+const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground
27+const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop
1628
1729 const TabBarContainer = styled.div`
1830 display: flex;
1931 flex-wrap: wrap;
2032 flex-shrink: 0;
2133 flex-grow: 0;
22- background-color: var(--vscode-tab-inactiveBackground);
34+ background-color: ${tabBackgroundVar};
2335 border-bottom: none;
2436 position: relative;
2537 margin-top: 2px;
@@ -41,24 +53,18 @@
4153 max-width: 150px;
4254 height: 25px;
4355 background-color: ${(props) =>
44- props.isActive
45- ? "var(--vscode-tab-activeBackground)"
46- : "var(--vscode-tab-inactiveBackground)"};
56+ props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar};
4757 color: ${(props) =>
48- props.isActive
49- ? "var(--vscode-tab-activeForeground)"
50- : "var(--vscode-tab-inactiveForeground)"};
58+ props.isActive ? tabSelectedForegroundVar : tabForegroundVar};
5159 cursor: pointer;
52- border: 1px solid var(--vscode-tab-border);
60+ border: 1px solid ${tabBorderVar};
5361 border-bottom: ${(props) =>
54- props.isActive ? "none" : `1px solid var(--vscode-tab-border)`};
62+ props.isActive ? "none" : `1px solid ${tabBorderVar}`};
5563 user-select: none;
5664 position: relative;
5765 transition: background-color 0.2s;
5866 border-top: ${(props) =>
59- props.isActive
60- ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)`
61- : `1px solid var(--vscode-tab-border)`};
67+ props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`};
6268 &:first-child {
6369 border-left: none;
6470 }
@@ -68,13 +74,9 @@
6874
6975 &:hover {
7076 background-color: ${(props) =>
71- props.isActive
72- ? "var(--vscode-tab-activeBackground)"
73- : "var(--vscode-tab-hoverBackground)"};
77+ props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar};
7478 color: ${(props) =>
75- props.isActive
76- ? "var(--vscode-tab-activeForeground)"
77- : "var(--vscode-tab-hoverForeground)"};
79+ props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar};
7880 }
7981 `;
8082
@@ -104,7 +106,7 @@
104106
105107 &:hover {
106108 opacity: 1;
107- background-color: var(--vscode-tab-hoverBackground);
109+ background-color: ${tabHoverBackgroundVar};
108110 }
109111
110112 ${Tab}:hover & {
@@ -119,33 +121,12 @@
119121 const TabBarSpace = styled.div`
120122 flex: 1;
121123 display: flex;
122- border-bottom: 1px solid var(--vscode-tab-border);
123- background-color: var(--vscode-tab-inactiveBackground);
124-`;
125-
126-const NewTabButton = styled.button`
127- display: flex;
128- align-items: center;
129- justify-content: center;
130- width: 35px;
131- height: 100%;
132- border: none;
133- background: transparent;
134- color: var(--vscode-tab-inactiveForeground);
135- cursor: pointer;
136- opacity: 0.7;
137- transition: opacity 0.2s;
138-
139- &:hover {
140- opacity: 1;
141- background-color: var(--vscode-tab-hoverBackground);
142- color: var(--vscode-tab-hoverForeground);
143- }
124+ border-bottom: 1px solid ${tabBorderVar};
125+ background-color: ${tabBackgroundVar};
144126 `;
145127
146128 export function TabBar() {
147129 const dispatch = useDispatch<AppDispatch>();
148- const currentSession = useSelector((state: RootState) => state.session);
149130 const currentSessionId = useSelector((state: RootState) => state.session.id);
150131 const currentSessionTitle = useSelector(
151132 (state: RootState) => state.session.title,
modified gui/src/components/dialogs/index.tsx +2 −3
@@ -4,12 +4,11 @@
44 import styled from "styled-components";
55 import {
66 CloseButton,
7- VSC_BACKGROUND_VAR,
87 defaultBorderRadius,
9- parseColorForHex,
108 vscBackground,
119 vscForeground,
1210 } from "..";
11+import { varWithFallback } from "../../styles/theme";
1312
1413 interface TextDialogProps {
1514 showDialog: boolean;
@@ -22,7 +21,7 @@
2221 position: fixed;
2322 width: 100%;
2423 height: 100%;
25- background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa;
24+ background-color: ${varWithFallback("background")}aa;
2625 z-index: 100000;
2726 flex-direction: column;
2827 `;
modified gui/src/components/find/FindWidget.tsx +2 −2
@@ -12,8 +12,8 @@
1212 useState,
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
15-import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
1615 import { useAppSelector } from "../../redux/hooks";
16+import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
1717
1818 interface SearchMatch {
1919 index: number;
@@ -41,7 +41,7 @@
4141 const { isCurrent, top, left, width, height } = props;
4242 return (
4343 <div
44- className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work
44+ className={isCurrent ? "bg-findMatch-selected/50" : "bg-findMatch/50"}
4545 key={`highlight-${top}-${left}`}
4646 style={{
4747 position: "absolute",
modified gui/src/components/gui/Alert.tsx +1 −1
@@ -39,7 +39,7 @@
3939 const { Icon } = ALERT_CONFIGS[type];
4040
4141 return (
42- <div className="rounded-lg border-l-4 bg-[color:var(--vscode-editor-foreground)] p-4 opacity-70 shadow-none">
42+ <div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none">
4343 <div className="flex items-start">
4444 <Icon
4545 className="h-6 min-h-5 w-6 min-w-5"
modified gui/src/components/index.ts +23 −110
@@ -1,114 +1,31 @@
11 import styled from "styled-components";
2-import { getFontSize } from "../util";
3-
4-export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
5-export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
6-export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground";
7-export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background";
8-export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground";
9-export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background";
10-export const VSC_LIST_SELECTION_BACKGROUND_VAR =
11- "--vscode-list-activeSelectionBackground";
12-export const VSC_FOCUS_BORDER_VAR = "--vscode-focusBorder";
13-export const VSC_LIST_ACTIVE_FOREGROUND_VAR =
14- "--vscode-quickInputList-focusForeground";
15-export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
16-export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
17-export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
18-export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground";
19-export const VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR =
20- "--vscode-commandCenter-activeBorder";
21-export const VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR =
22- "--vscode-commandCenter-inactiveBorder";
23-export const VSC_FIND_MATCH_SELECTED_VAR =
24- "--vscode-editor-findMatchHighlightBackground";
25-
26-export const VSC_THEME_COLOR_VARS = [
27- VSC_INPUT_BACKGROUND_VAR,
28- VSC_BACKGROUND_VAR,
29- VSC_FOREGROUND_VAR,
30- VSC_BUTTON_BACKGROUND_VAR,
31- VSC_BUTTON_FOREGROUND_VAR,
32- VSC_EDITOR_BACKGROUND_VAR,
33- VSC_LIST_SELECTION_BACKGROUND_VAR,
34- VSC_FOCUS_BORDER_VAR,
35- VSC_LIST_ACTIVE_FOREGROUND_VAR,
36- VSC_QUICK_INPUT_BACKGROUND_VAR,
37- VSC_INPUT_BORDER_VAR,
38- VSC_BADGE_BACKGROUND_VAR,
39- VSC_BADGE_FOREGROUND_VAR,
40- VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR,
41- VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR,
42- VSC_FIND_MATCH_SELECTED_VAR,
43-];
2+import { varWithFallback } from "../styles/theme";
443
4+// DEPRECATED - avoid using these where possible, use tailwind classes instead
455 export const defaultBorderRadius = "5px";
466 export const lightGray = "#999998";
477 export const greenButtonColor = "#189e72";
488
49-export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
50-export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
51-export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
52-export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`;
53-export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`;
54-export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`;
55-export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
56-export const vscListActiveBackground = `var(${VSC_LIST_SELECTION_BACKGROUND_VAR}, #1bbe84)`;
57-export const vscFocusBorder = `var(${VSC_FOCUS_BORDER_VAR}, #1bbe84)`;
58-export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`;
59-export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
60-export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`;
61-export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
62-export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`;
63-export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`;
64-export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`;
65-export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`;
66-
67-export function parseHexColor(hexColor: string): {
68- r: number;
69- g: number;
70- b: number;
71-} {
72- if (hexColor.startsWith("#")) {
73- hexColor = hexColor.slice(1);
74- }
75-
76- if (hexColor.length > 6) {
77- hexColor = hexColor.slice(0, 6);
78- }
79-
80- const r = parseInt(hexColor.substring(0, 2), 16);
81- const g = parseInt(hexColor.substring(2, 4), 16);
82- const b = parseInt(hexColor.substring(4, 6), 16);
83-
84- return { r, g, b };
85-}
86-
87-export function parseColorForHex(colorVar: string): string {
88- const value = getComputedStyle(document.documentElement).getPropertyValue(
89- colorVar,
90- );
91- if (value.startsWith("#")) {
92- return value.slice(0, 7);
93- }
94-
95- // Parse rgb/rgba
96- const rgbValues = value
97- .slice(value.startsWith("rgba") ? 5 : 4, -1)
98- .split(",")
99- .map((x) => x.trim())
100- .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
101- .map((x) => parseInt(x, 10));
102-
103- let hex =
104- "#" +
105- rgbValues
106- .map((x) => x.toString(16))
107- .map((x) => (x.length === 1 ? "0" + x : x))
108- .join("");
109-
110- return hex;
111-}
9+export const vscInputBackground = varWithFallback("input-background");
10+export const vscQuickInputBackground = varWithFallback("input-background");
11+export const vscBackground = varWithFallback("background");
12+export const vscForeground = varWithFallback("foreground");
13+export const vscButtonBackground = varWithFallback("primary-background");
14+export const vscButtonForeground = varWithFallback("primary-foreground");
15+export const vscEditorBackground = varWithFallback("editor-background");
16+export const vscListActiveBackground = varWithFallback("list-active");
17+export const vscFocusBorder = varWithFallback("border-focus");
18+export const vscListActiveForeground = varWithFallback(
19+ "list-active-foreground",
20+);
21+export const vscInputBorder = varWithFallback("input-border");
22+export const vscInputBorderFocus = varWithFallback("border-focus");
23+export const vscBadgeBackground = varWithFallback("badge-background");
24+export const vscBadgeForeground = varWithFallback("badge-foreground");
25+export const vscCommandCenterActiveBorder = varWithFallback(
26+ "command-border-focus",
27+);
28+export const vscCommandCenterInactiveBorder = varWithFallback("command-border");
11229
11330 export const Button = styled.button`
11431 padding: 6px 12px;
@@ -158,7 +75,7 @@
15875
15976 border: none;
16077 color: ${vscForeground};
161- background-color: rgba(255, 255, 255, 0.08);
78+ background-color: rgba(128, 128, 128, 0.4);
16279 &:disabled {
16380 color: gray;
16481 pointer-events: none;
@@ -226,10 +143,6 @@
226143 }
227144 `;
228145
229-export const Label = styled.label<{ fontSize?: number }>`
230- font-size: ${(props) => props.fontSize || getFontSize()}px;
231-`;
232-
233146 export const HeaderButton = styled.button<{
234147 inverted: boolean | undefined;
235148 backgroundColor?: string;
modified gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +1 −1
@@ -49,7 +49,7 @@
4949
5050 return (
5151 <GhostButton
52- className="w-full cursor-pointer rounded px-2 py-0.5 text-center text-gray-400 hover:text-gray-300"
52+ className="w-full cursor-pointer rounded px-2 py-0.5 text-center"
5353 style={{
5454 fontSize: fontSize(-3),
5555 }}
modified gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +1 −1
@@ -159,7 +159,7 @@
159159 contentEditable={false}
160160 >
161161 <div
162- className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
162+ className="border-b-command-border m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
163163 style={{
164164 fontSize: getFontSize() - 3,
165165 }}
modified gui/src/context/VscTheme.tsx +1 −1
@@ -1,6 +1,6 @@
11 import { createContext, useContext, useState } from "react";
2-import { parseHexColor } from "../components";
32 import { useWebviewListener } from "../hooks/useWebviewListener";
3+import { parseHexColor } from "../styles/utils";
44
55 const hljsToTextMate: Record<string, string[]> = {
66 ".hljs-comment": ["comment"],
modified gui/src/hooks/ParallelListeners.tsx +7 −34
@@ -1,5 +1,4 @@
11 import { useCallback, useContext, useEffect, useRef } from "react";
2-import { VSC_THEME_COLOR_VARS } from "../components";
32 import { IdeMessengerContext } from "../context/IdeMessenger";
43
54 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
@@ -29,6 +28,10 @@
2928 import { refreshSessionMetadata } from "../redux/thunks/session";
3029 import { streamResponseThunk } from "../redux/thunks/streamResponse";
3130 import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
31+import {
32+ setDocumentStylesFromLocalStorage,
33+ setDocumentStylesFromTheme,
34+} from "../styles/theme";
3235 import { isJetBrains } from "../util";
3336 import { setLocalStorage } from "../util/localStorage";
3437 import { useWebviewListener } from "./useWebviewListener";
@@ -139,31 +142,13 @@
139142 dispatch(cancelStream());
140143
141144 const jetbrains = isJetBrains();
142- for (const colorVar of VSC_THEME_COLOR_VARS) {
143- if (jetbrains) {
144- const cached = localStorage.getItem(colorVar);
145- if (cached) {
146- document.body.style.setProperty(colorVar, cached);
147- }
148- }
149-
150- // Remove alpha channel from colors
151- const value = getComputedStyle(document.documentElement).getPropertyValue(
152- colorVar,
153- );
154- if (colorVar.startsWith("#") && value.length > 7) {
155- document.body.style.setProperty(colorVar, value.slice(0, 7));
156- }
157- }
145+ setDocumentStylesFromLocalStorage(jetbrains);
158146
159147 if (jetbrains) {
160148 // Save theme colors to local storage for immediate loading in JetBrains
161149 ideMessenger.request("jetbrains/getColors", undefined).then((result) => {
162150 if (result.status === "success") {
163- Object.entries(result.content).forEach(([key, value]) => {
164- document.body.style.setProperty(key, value);
165- document.documentElement.style.setProperty(key, value);
166- });
151+ setDocumentStylesFromTheme(result.content);
167152 }
168153 });
169154
@@ -180,25 +165,13 @@
180165 (window as any).vscMachineId = msg.vscMachineId;
181166 (window as any).vscMediaUrl = msg.vscMediaUrl;
182167 });
183-
184- for (const colorVar of VSC_THEME_COLOR_VARS) {
185- if (document.body.style.getPropertyValue(colorVar)) {
186- localStorage.setItem(
187- colorVar,
188- document.body.style.getPropertyValue(colorVar),
189- );
190- }
191- }
192168 }
193169 }, []);
194170
195171 useWebviewListener(
196172 "jetbrains/setColors",
197173 async (data) => {
198- Object.entries(data).forEach(([key, value]) => {
199- document.body.style.setProperty(key, value);
200- document.documentElement.style.setProperty(key, value);
201- });
174+ setDocumentStylesFromTheme(data);
202175 },
203176 [],
204177 );
modified gui/src/pages/config/HelpCenterSection.tsx +12 −0
@@ -1,6 +1,7 @@
11 import {
22 ArrowTopRightOnSquareIcon,
33 DocumentArrowUpIcon,
4+ PaintBrushIcon,
45 TableCellsIcon,
56 } from "@heroicons/react/24/outline";
67 import { useContext } from "react";
@@ -9,6 +10,7 @@
910 import { useAppDispatch } from "../../redux/hooks";
1011 import { setOnboardingCard } from "../../redux/slices/uiSlice";
1112 import { saveCurrentSession } from "../../redux/thunks/session";
13+import { ROUTES } from "../../util/navigation";
1214 import MoreHelpRow from "./MoreHelpRow";
1315
1416 export function HelpCenterSection() {
@@ -83,6 +85,16 @@
8385 ideMessenger.post("showTutorial", undefined);
8486 }}
8587 />
88+ {process.env.NODE_ENV === "development" && (
89+ <MoreHelpRow
90+ title="Theme Test Page"
91+ description="Development page for testing themes"
92+ Icon={PaintBrushIcon}
93+ onClick={async () => {
94+ navigate(ROUTES.THEME);
95+ }}
96+ />
97+ )}
8698 </div>
8799 </div>
88100 );
modified gui/src/pages/config/KeyboardShortcuts.tsx +1 −1
@@ -11,7 +11,7 @@
1111 function KeyboardShortcut(props: KeyboardShortcutProps) {
1212 return (
1313 <div
14- className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-odd-rows"}`}
14+ className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-oddRow"}`}
1515 >
1616 <div className="w-full flex-grow pb-1 pr-4 sm:w-auto sm:pb-0">
1717 <span className="block break-words text-xs">{props.description}:</span>
modified gui/src/redux/thunks/streamResponse.ts +1 −0
@@ -100,6 +100,7 @@
100100 ? (userMsg as UserChatMessage | ToolResultChatMessage)
101101 : undefined,
102102 rules,
103+ selectedContextItems,
103104 );
104105
105106 // Store in history for UI display
added gui/src/styles/ThemePage.tsx +232 −0
@@ -0,0 +1,232 @@
1+import {
2+ CheckCircleIcon,
3+ ExclamationCircleIcon,
4+ ExclamationTriangleIcon,
5+} from "@heroicons/react/24/outline";
6+import { useContext, useEffect, useMemo, useState } from "react";
7+import { useNavigate } from "react-router-dom";
8+import { Button } from "../components";
9+import { IdeMessengerContext } from "../context/IdeMessenger";
10+import { isJetBrains } from "../util";
11+import { ROUTES } from "../util/navigation";
12+import {
13+ clearThemeLocalCache,
14+ setDocumentStylesFromTheme,
15+ THEME_COLORS,
16+ varWithFallback,
17+} from "./theme";
18+
19+const ThemeTailwindClassExample = ({
20+ colorName,
21+ varNames,
22+ defaultColor,
23+ isMissing,
24+}: {
25+ colorName: string;
26+ varNames: string[];
27+ defaultColor: string;
28+ isMissing?: boolean;
29+}) => {
30+ return (
31+ <>
32+ <div className={`line-clamp-1 break-all px-2 text-right`}>
33+ {colorName}
34+ </div>
35+ <div
36+ className={`line-clamp-1 break-all p-1 text-[9px] ${isMissing ? "text-error" : ""}`}
37+ style={{
38+ backgroundColor: varWithFallback(
39+ colorName as keyof typeof THEME_COLORS,
40+ ),
41+ }}
42+ >
43+ {varNames.join(", ")}
44+ </div>
45+ <div
46+ className={`line-clamp-1 break-all p-1 text-[9px]`}
47+ style={{
48+ backgroundColor: defaultColor,
49+ }}
50+ >
51+ {defaultColor}
52+ </div>
53+ </>
54+ );
55+};
56+
57+function ThemePage() {
58+ const navigate = useNavigate();
59+ const [listToggled, setListToggled] = useState(false);
60+ const ideMessenger = useContext(IdeMessengerContext);
61+ const jetbrains = useMemo(() => {
62+ return isJetBrains();
63+ }, []);
64+
65+ const [missingVars, setMissingVars] = useState<string[]>([]);
66+ const refreshColors = () => {
67+ if (jetbrains) {
68+ // Jetbrains: get colors and check which ones are missing from theme
69+ void ideMessenger
70+ .request("jetbrains/getColors", undefined)
71+ .then((result) => {
72+ console.log(result);
73+ if (result.status === "success") {
74+ const missingColors = setDocumentStylesFromTheme(result.content);
75+ setMissingVars(missingColors);
76+ }
77+ });
78+ } else {
79+ // VS Code: find actual missing CSS variables
80+ const notFound: string[] = [];
81+ Object.entries(THEME_COLORS).forEach(([colorName, themeVals], idx) => {
82+ let found = false;
83+ themeVals.vars.forEach((cssVar) => {
84+ const value = getComputedStyle(
85+ document.documentElement,
86+ ).getPropertyValue(cssVar);
87+ if (!value) {
88+ notFound.push(`cssVar (choice #${idx + 1} for color ${colorName}`);
89+ }
90+ });
91+ });
92+ setMissingVars(notFound);
93+ }
94+ };
95+
96+ useEffect(() => {
97+ refreshColors();
98+ }, []);
99+
100+ return (
101+ <div className="flex flex-1 flex-col gap-3 px-2 py-2">
102+ <span
103+ className="flex cursor-pointer flex-row items-center gap-2"
104+ onClick={() => navigate(ROUTES.HOME)}
105+ >
106+ <span className="">←</span>
107+ Back to Chat
108+ </span>
109+ <h2 className="mb-2 mt-0 p-0 text-center text-xl font-semibold">
110+ Theme Tester
111+ </h2>
112+ <div className="bg-background border-border grid grid-cols-1 gap-4 rounded-md border border-solid p-4 md:grid-cols-2">
113+ <div className="col-span-2 flex gap-4">
114+ <p className="">Normal text</p>
115+ <p className="text-description">Description text</p>
116+ <p className="text-description-muted">Muted text</p>
117+ </div>
118+
119+ <button className="bg-primary text-primary-foreground hover:bg-primary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
120+ Primary Button
121+ </button>
122+ <button className="bg-secondary text-secondary-foreground hover:bg-secondary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
123+ Secondary Button
124+ </button>
125+
126+ <div className="border-border rounded-md border border-solid p-3">
127+ Normal border
128+ </div>
129+
130+ <div className="border-border-focus rounded-md border border-solid p-3">
131+ Focus border
132+ </div>
133+
134+ <input
135+ className="bg-input text-input-foreground border-input-border placeholder:text-input-placeholder focus:border-border-focus rounded-md border border-solid p-2 focus:outline-none"
136+ placeholder="Input example"
137+ />
138+
139+ <div className="bg-badge text-badge-foreground border-border inline-block rounded-full border border-solid p-2">
140+ <span className="px-2">Badge</span>
141+ </div>
142+
143+ <div className="flex items-center gap-2">
144+ <CheckCircleIcon className="text-success h-4 w-4" />
145+ <span className="text-success">Success</span>
146+ </div>
147+ <div className="flex items-center gap-2">
148+ <ExclamationCircleIcon className="text-warning h-4 w-4" />
149+ <span className="text-warning">Warning</span>
150+ </div>
151+ <div className="flex items-center gap-2">
152+ <ExclamationTriangleIcon className="text-error h-4 w-4" />
153+ <span className="text-error">Error</span>
154+ </div>
155+
156+ <div
157+ onClick={() => setListToggled(!listToggled)}
158+ className={`cursor-pointer p-2 ${listToggled ? "bg-list-active text-list-active-foreground" : "bg-background text-foreground hover:bg-list-hover"}`}
159+ >
160+ List item (clickable)
161+ </div>
162+ <div className="bg-editor text-editor-foreground border-border rounded-sm border border-solid p-2">
163+ <span>Editor</span>
164+ </div>
165+ <table>
166+ <tbody>
167+ <tr>
168+ <td className="border-border border-b border-solid p-2">
169+ <span>even table row</span>
170+ </td>
171+ </tr>
172+ <tr className="bg-table-oddRow">
173+ <td className="border-border border-b border-solid p-2">
174+ <span>odd table row</span>
175+ </td>
176+ </tr>
177+ </tbody>
178+ </table>
179+ <div>
180+ <span className="text-link">Link</span>
181+ </div>
182+ <div className="flex items-center gap-2">
183+ <span className="bg-findMatch">find match</span>
184+ <span className="bg-findMatch-selected">current match</span>
185+ </div>
186+ <div className="flex items-center gap-2">
187+ <span className="">Accent</span>
188+ <div className="bg-accent h-3 w-3" />
189+ </div>
190+ </div>
191+ <h2 className="mb-2 mt-6 text-xl font-semibold">Manage Theme</h2>
192+ <h2 className="mb-2 text-lg font-semibold">Missing Theme Colors</h2>
193+ {missingVars.length > 0 ? (
194+ <div className="flex flex-col gap-1">
195+ {missingVars.map((varName) => (
196+ <div key={varName} className="">
197+ {varName}
198+ </div>
199+ ))}
200+ </div>
201+ ) : (
202+ <div className="">No missing variables</div>
203+ )}
204+ <Button onClick={refreshColors}>Refresh Missing Colors</Button>
205+ {jetbrains ? (
206+ <Button onClick={clearThemeLocalCache}>Clear Theme Cache</Button>
207+ ) : null}
208+ <h2 className="mb-2 mt-6 text-xl font-semibold">All Theme Colors</h2>
209+ <div className="grid grid-cols-3">
210+ <div className="p-1">
211+ <span className="font-bold">Theme Color</span>
212+ </div>
213+ <div className="p-1">
214+ <span className="font-bold">CSS Var</span>
215+ </div>
216+ <div className="p-1">
217+ <span className="font-bold">Default</span>
218+ </div>
219+ {Object.entries(THEME_COLORS).map(([colorName, val]) => (
220+ <ThemeTailwindClassExample
221+ isMissing={missingVars.includes(colorName)}
222+ key={colorName}
223+ colorName={colorName}
224+ defaultColor={val.default}
225+ varNames={val.vars}
226+ />
227+ ))}
228+ </div>
229+ </div>
230+ );
231+}
232+export default ThemePage;
added gui/src/styles/theme.test.ts +24 −0
@@ -0,0 +1,24 @@
1+import { getRecursiveVar } from "./theme";
2+
3+test("getRecursiveVar returns single var with default for one variable", () => {
4+ const vars = ["--test-var"];
5+ const defaultColor = "#ffffff";
6+ const result = getRecursiveVar(vars, defaultColor);
7+ expect(result).toBe("var(--test-var, #ffffff)");
8+});
9+
10+test("getRecursiveVar returns nested vars in correct order for multiple variables", () => {
11+ const vars = ["--first-var", "--second-var", "--third-var"];
12+ const defaultColor = "#000000";
13+ const result = getRecursiveVar(vars, defaultColor);
14+ expect(result).toBe(
15+ "var(--first-var, var(--second-var, var(--third-var, #000000)))",
16+ );
17+});
18+
19+test("getRecursiveVar handles empty vars array", () => {
20+ const vars: string[] = [];
21+ const defaultColor = "#123456";
22+ const result = getRecursiveVar(vars, defaultColor);
23+ expect(result).toBe("#123456");
24+});
added gui/src/styles/theme.ts +271 −0
@@ -0,0 +1,271 @@
1+// All vscode variables https://gist.github.com/estruyf/ba49203e1a7d6868e9320a4ea480c27a
2+// Examples for vscode https://github.com/githubocto/tailwind-vscode/blob/main/index.js
3+
4+// The current default theme is dark with blue accents
5+export const THEME_COLORS = {
6+ background: {
7+ vars: [
8+ "--vscode-sideBar-background",
9+ "--vscode-editor-background",
10+ "--vscode-panel-background",
11+ ],
12+ default: "#1e1e1e", // dark gray
13+ },
14+ foreground: {
15+ vars: [
16+ "--vscode-sideBar-foreground",
17+ "--vscode-editor-foreground",
18+ "--vscode-panel-foreground",
19+ ],
20+ default: "#e6e6e6", // light gray
21+ },
22+ "editor-background": {
23+ vars: ["--vscode-editor-background"],
24+ default: "#1e1e1e", // dark gray
25+ },
26+ "editor-foreground": {
27+ vars: ["--vscode-editor-foreground"],
28+ default: "#e6e6e6", // light gray
29+ },
30+ "primary-background": {
31+ vars: ["--vscode-button-background"],
32+ default: "#2c5aa0", // medium blue
33+ },
34+ "primary-foreground": {
35+ vars: ["--vscode-button-foreground"],
36+ default: "#ffffff", // white
37+ },
38+ "primary-hover": {
39+ vars: ["--vscode-button-hoverBackground"],
40+ default: "#3a6db3", // lighter blue
41+ },
42+ "secondary-background": {
43+ vars: ["--vscode-button-secondaryBackground"],
44+ default: "#303030", // medium dark gray
45+ },
46+ "secondary-foreground": {
47+ vars: ["--vscode-button-secondaryForeground"],
48+ default: "#e6e6e6", // light gray
49+ },
50+ "secondary-hover": {
51+ vars: ["--vscode-button-secondaryHoverBackground"],
52+ default: "#3a3a3a", // medium gray
53+ },
54+ border: {
55+ vars: ["--vscode-sideBar-border", "--vscode-panel-border"],
56+ default: "#2a2a2a", // dark gray border
57+ },
58+ "border-focus": {
59+ vars: ["--vscode-focusBorder"],
60+ default: "#3a6db3", // lighter blue
61+ },
62+ // Command styles are used for tip-tap editor
63+ "command-background": {
64+ vars: ["--vscode-commandCenter-background"],
65+ default: "#252525", // dark gray
66+ },
67+ "command-foreground": {
68+ vars: ["--vscode-commandCenter-foreground"],
69+ default: "#e6e6e6", // light gray
70+ },
71+ "command-border": {
72+ vars: ["--vscode-commandCenter-inactiveBorder"],
73+ default: "#555555", // medium gray
74+ },
75+ "command-border-focus": {
76+ vars: ["--vscode-commandCenter-activeBorder"],
77+ default: "#4d8bf0", // bright blue
78+ },
79+ description: {
80+ vars: ["--vscode-descriptionForeground"],
81+ default: "#b3b3b3", // medium light gray
82+ },
83+ "description-muted": {
84+ vars: ["--vscode-list-deemphasizedForeground"],
85+ default: "#8c8c8c", // medium gray
86+ },
87+ "input-background": {
88+ vars: ["--vscode-input-background"],
89+ default: "#2d2d2d", // dark gray
90+ },
91+ "input-foreground": {
92+ vars: ["--vscode-input-foreground"],
93+ default: "#e6e6e6", // light gray
94+ },
95+ "input-border": {
96+ vars: [
97+ "--vscode-input-border",
98+ "--vscode-commandCenter-inactiveBorder",
99+ "vscode-border",
100+ ],
101+ default: "#555555", // medium gray
102+ },
103+ "input-placeholder": {
104+ vars: ["--vscode-input-placeholderForeground"],
105+ default: "#9e9e9e", // medium light gray
106+ },
107+ "table-oddRow": {
108+ vars: ["--vscode-tree-tableOddRowsBackground"],
109+ default: "#2d2d2d", // dark gray
110+ },
111+ "badge-background": {
112+ vars: ["--vscode-badge-background"],
113+ default: "#4d4d4d", // medium dark gray
114+ },
115+ "badge-foreground": {
116+ vars: ["--vscode-badge-foreground"],
117+ default: "#ffffff", // white
118+ },
119+ success: {
120+ vars: [
121+ "--vscode-notebookStatusSuccessIcon-foreground",
122+ "--vscode-testing-iconPassed",
123+ "--vscode-gitDecoration-addedResourceForeground",
124+ "--vscode-charts-green",
125+ ],
126+ default: "#4caf50", // green
127+ },
128+ warning: {
129+ vars: [
130+ "--vscode-editorWarning-foreground",
131+ "--vscode-list-warningForeground",
132+ ],
133+ default: "#ffb74d", // amber/yellow
134+ },
135+ error: {
136+ vars: ["--vscode-editorError-foreground", "--vscode-list-errorForeground"],
137+ default: "#f44336", // red
138+ },
139+ link: {
140+ vars: ["--vscode-textLink-foreground"],
141+ default: "#5c9ce6", // medium blue
142+ },
143+ accent: {
144+ vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"],
145+ default: "#4d8bf0", // bright blue
146+ },
147+ "find-match": {
148+ vars: ["--vscode-editor-findMatchBackground"], // Can't get "var(--vscode-editor-findMatchBackground, rgba(237, 18, 146, 0.5))" to work
149+ default: "#264f7840", // translucent blue
150+ },
151+ "find-match-selected": {
152+ vars: ["--vscode-editor-findMatchHighlightBackground"],
153+ default: "#ffb74d40", // translucent amber
154+ },
155+ "list-hover": {
156+ // --vscode-tab-hoverBackground
157+ vars: ["--vscode-list-hoverBackground"],
158+ default: "#383838", // medium dark gray
159+ },
160+ "list-active": {
161+ vars: ["--vscode-list-activeSelectionBackground"],
162+ default: "#2c5aa050", // translucent medium blue
163+ },
164+ "list-active-foreground": {
165+ vars: ["--vscode-list-activeSelectionForeground"],
166+ default: "#ffffff", // white
167+ },
168+};
169+
170+// TODO: add fonts - GUI fonts in jetbrains differ from IDE:
171+// --vscode-editor-font-family;
172+// --vscode-font-family;
173+export const THEME_CSS_VARS = Object.values(THEME_COLORS)
174+ .map((value) => value.vars)
175+ .flat();
176+
177+export const THEME_CSS_VAR_DEFAULTS = Object.entries(THEME_COLORS).reduce(
178+ (acc, [_, value]) => {
179+ value.vars.forEach((varName) => {
180+ acc[varName] = value.default;
181+ });
182+ return acc;
183+ },
184+ {} as Record<string, string>,
185+);
186+
187+export const THEME_DEFAULTS = Object.entries(THEME_COLORS).reduce(
188+ (acc, [key, value]) => {
189+ acc[key] = value.default;
190+ return acc;
191+ },
192+ {} as Record<string, string>,
193+);
194+
195+// Generates recursive CSS variable fallback for a given color name
196+// e.g. var(--vscode-button-background, var(--vscode-button-foreground, #ffffff))
197+export const getRecursiveVar = (vars: string[], defaultColor: string) => {
198+ return [...vars].reverse().reduce((curr, varName) => {
199+ return `var(${varName}, ${curr})`;
200+ }, defaultColor);
201+};
202+
203+export const varWithFallback = (colorName: keyof typeof THEME_COLORS) => {
204+ const themeVals = THEME_COLORS[colorName];
205+ if (!themeVals) {
206+ throw new Error(`Invalid theme color name ${colorName}`);
207+ }
208+ return getRecursiveVar(themeVals.vars, themeVals.default);
209+};
210+
211+export const setDocumentStylesFromTheme = (
212+ theme: Record<string, string | undefined | null>,
213+) => {
214+ // Check for extraneous theme items
215+ Object.entries(theme).forEach(([colorName, value]) => {
216+ const themeVals = THEME_COLORS[colorName as keyof typeof THEME_COLORS];
217+ if (!themeVals) {
218+ console.warn(
219+ `Receieved theme color ${colorName} which is not used by the theme`,
220+ );
221+ return;
222+ }
223+ });
224+
225+ // Write theme values to document
226+ const missingColors: string[] = [];
227+ Object.entries(THEME_COLORS).forEach(([colorName, settings]) => {
228+ let colorVal = settings.default;
229+ const newColor = theme[colorName];
230+ if (newColor) {
231+ colorVal = newColor;
232+ // Remove alpha channel from all hex colors (seems to cause bad colors)
233+ if (newColor.startsWith("#") && newColor.length > 7) {
234+ colorVal = colorVal.slice(0, 7);
235+ }
236+ } else {
237+ missingColors.push(colorName);
238+ // console.warn(
239+ // `Missing theme color: ${colorName}. Falling back to default ${colorVal}`,
240+ // );
241+ }
242+
243+ localStorage.setItem(colorName, colorVal);
244+ for (const cssVar of settings.vars) {
245+ document.body.style.setProperty(cssVar, colorVal);
246+ document.documentElement.style.setProperty(cssVar, colorVal);
247+ }
248+ });
249+
250+ return missingColors;
251+};
252+
253+export const setDocumentStylesFromLocalStorage = (checkCache: boolean) => {
254+ for (const [colorName, themeVals] of Object.entries(THEME_COLORS)) {
255+ for (const cssVar of themeVals.vars) {
256+ // Get cached values (for non-vscode IDEs)
257+ if (checkCache) {
258+ const cached = localStorage.getItem(colorName);
259+ if (cached) {
260+ document.body.style.setProperty(cssVar, cached);
261+ }
262+ }
263+ }
264+ }
265+};
266+
267+export const clearThemeLocalCache = () => {
268+ for (const colorName of Object.keys(THEME_COLORS)) {
269+ localStorage.removeItem(colorName);
270+ }
271+};
added gui/src/styles/utils.ts +45 −0
@@ -0,0 +1,45 @@
1+export function parseHexColor(hexColor: string): {
2+ r: number;
3+ g: number;
4+ b: number;
5+} {
6+ if (hexColor.startsWith("#")) {
7+ hexColor = hexColor.slice(1);
8+ }
9+
10+ if (hexColor.length > 6) {
11+ hexColor = hexColor.slice(0, 6);
12+ }
13+
14+ const r = parseInt(hexColor.substring(0, 2), 16);
15+ const g = parseInt(hexColor.substring(2, 4), 16);
16+ const b = parseInt(hexColor.substring(4, 6), 16);
17+
18+ return { r, g, b };
19+}
20+
21+export function parseColorForHex(colorVar: string): string {
22+ const value = getComputedStyle(document.documentElement).getPropertyValue(
23+ colorVar,
24+ );
25+ if (value.startsWith("#")) {
26+ return value.slice(0, 7);
27+ }
28+
29+ // Parse rgb/rgba
30+ const rgbValues = value
31+ .slice(value.startsWith("rgba") ? 5 : 4, -1)
32+ .split(",")
33+ .map((x) => x.trim())
34+ .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
35+ .map((x) => parseInt(x, 10));
36+
37+ let hex =
38+ "#" +
39+ rgbValues
40+ .map((x) => x.toString(16))
41+ .map((x) => (x.length === 1 ? "0" + x : x))
42+ .join("");
43+
44+ return hex;
45+}
modified gui/src/util/navigation.ts +1 −0
@@ -2,5 +2,6 @@
22 export const ROUTES = {
33 HOME: "/",
44 CONFIG: "/config",
5+ THEME: "/theme",
56 // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`,
67 };
modified gui/tailwind.config.cjs +69 −18
@@ -1,5 +1,6 @@
11 /** @type {import('tailwindcss').Config} */
22 const defaultTheme = require("tailwindcss/defaultTheme");
3+const { varWithFallback, THEME_COLORS } = require("./src/styles/theme");
34
45 module.exports = {
56 content: [
@@ -29,25 +30,75 @@
2930 default: "5px",
3031 },
3132 colors: {
32- lightgray: "#999998",
33- "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))",
34- "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))",
35- "vsc-foreground": "var(--vscode-editor-foreground, #fff)",
36- "vsc-editor-background":
37- "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))",
38- "vsc-input-border": "var(--vscode-input-border, #999998)",
39- "vsc-commandCenter-inactiveBorder":
40- "var(--vscode-commandCenter-inactiveBorder, #999998)",
33+ background: varWithFallback("background"),
34+ foreground: varWithFallback("foreground"),
35+ editor: {
36+ DEFAULT: varWithFallback("editor-background"),
37+ foreground: varWithFallback("editor-foreground"),
38+ },
39+ primary: {
40+ DEFAULT: varWithFallback("primary-background"),
41+ foreground: varWithFallback("primary-foreground"),
42+ hover: varWithFallback("primary-hover"),
43+ },
44+ secondary: {
45+ DEFAULT: varWithFallback("secondary-background"),
46+ foreground: varWithFallback("secondary-foreground"),
47+ hover: varWithFallback("secondary-hover"),
48+ },
49+ border: {
50+ DEFAULT: varWithFallback("border"),
51+ focus: varWithFallback("border-focus"),
52+ },
53+ command: {
54+ DEFAULT: varWithFallback("command-background"),
55+ foreground: varWithFallback("command-foreground"),
56+ border: {
57+ DEFAULT: varWithFallback("command-border"),
58+ focus: varWithFallback("command-border-focus"),
59+ },
60+ },
61+ description: {
62+ DEFAULT: varWithFallback("description"),
63+ muted: varWithFallback("description-muted"),
64+ },
65+ input: {
66+ DEFAULT: varWithFallback("input-background"),
67+ foreground: varWithFallback("input-foreground"),
68+ border: varWithFallback("input-border"),
69+ placeholder: varWithFallback("input-placeholder"),
70+ },
71+ table: {
72+ oddRow: varWithFallback("table-oddRow"),
73+ },
74+ badge: {
75+ DEFAULT: varWithFallback("badge-background"),
76+ foreground: varWithFallback("badge-foreground"),
77+ },
78+ success: varWithFallback("success"),
79+ warning: varWithFallback("warning"),
80+ error: varWithFallback("error"),
81+ link: varWithFallback("link"),
82+ accent: varWithFallback("accent"),
83+ findMatch: {
84+ DEFAULT: THEME_COLORS["find-match"].default,
85+ selected: varWithFallback("find-match-selected"),
86+ },
87+ list: {
88+ hover: varWithFallback("list-hover"),
89+ active: {
90+ DEFAULT: varWithFallback("list-active"),
91+ foreground: varWithFallback("list-active-foreground"),
92+ },
93+ },
4194
42- // Starting to make things less vsc-specific
43- // TODO make it all non-IDE-specific naming
44- "find-match-selected":
45- "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))",
46- "table-odd-rows":"var(--vscode-tree-tableOddRowsBackground, #1bbe84)",
47- "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)",
48- "list-active-foreground":
49- "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))",
50- badge: "var(--vscode-badge-background, #1bbe84)",
95+ // DEPRECATED, slowly remove usages of these ide-named or explicit colors
96+ lightgray: "#999998", // use border, description, or description-muted instead - AVOID
97+ "vsc-input-background": varWithFallback("input-background"), // use "input-background" instead
98+ "vsc-background": varWithFallback("background"), // use "background" instead
99+ "vsc-foreground": varWithFallback("editor-foreground"), // use "foreground" instead
100+ "vsc-editor-background": varWithFallback("editor-background"), // use "editor" instead
101+ "vsc-input-border": varWithFallback("input-border"), // use "input-border" instead
51102 },
52103 },
53104 },
modified manual-testing-sandbox/test.ts +2 −2
@@ -9,7 +9,7 @@
99 this.result += number;
1010 return this;
1111 }
12-
12+
1313 subtract(number: number): Calculator {
1414 this.result -= number;
1515 return this;
@@ -38,4 +38,4 @@
3838 }
3939 }
4040
41-export default Calculator;
No newline at the end of the file
41+export default Calculator;