Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into nate/dev-data-updates
Changeset28132f96f4d39295e1945039893dbaf4e5bddc39776f65dbc8474511e83cbfee
AuthorNate <sestinj@gmail.com> · 2025-05-25 18:53 -07:00
CommitterNate <sestinj@gmail.com> · 2025-05-25 18:53 -07:00
Parents2b5a128962b1, f8a28b58727d

Browse the files at this changeset

142 files changed

modified binary/package-lock.json +5 −3
@@ -93,6 +93,7 @@
9393 "p-limit": "^6.1.0",
9494 "partial-json": "^0.1.7",
9595 "pg": "^8.11.3",
96+ "plist": "^3.1.0",
9697 "posthog-node": "^3.6.3",
9798 "puppeteer": "^22.4.0",
9899 "puppeteer-chromium-resolver": "^23.0.0",
@@ -129,6 +130,7 @@
129130 "@types/mustache": "^4.2.5",
130131 "@types/node-fetch": "^2.6.11",
131132 "@types/pg": "^8.11.6",
133+ "@types/plist": "^3.0.5",
132134 "@types/request": "^2.48.12",
133135 "@types/tar": "^6.1.13",
134136 "@types/uuid": "^9.0.7",
@@ -2587,9 +2589,9 @@
25872589 }
25882590 },
25892591 "node_modules/axios": {
2590- "version": "1.7.9",
2591- "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
2592- "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
2592+ "version": "1.9.0",
2593+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
2594+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
25932595 "license": "MIT",
25942596 "dependencies": {
25952597 "follow-redirects": "^1.15.6",
modified core/commands/slash/http.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { SlashCommand } from "../../index.js";
23 import { removeQuotesAndEscapes } from "../../util/index.js";
3-import { streamResponse } from "../../llm/stream.js";
44
55 const HttpSlashCommand: SlashCommand = {
66 name: "http",
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 +8 −1
@@ -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 };
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 +174 −0
@@ -0,0 +1,174 @@
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+
155+ it("should include description from frontmatter", () => {
156+ const content = `---
157+globs: "**/test/**/*.kt"
158+name: Test Rule
159+description: This is a rule description from frontmatter
160+---
161+
162+# Test Rule
163+
164+This is the content of the rule.`;
165+
166+ const result = convertMarkdownRuleToContinueRule(
167+ "/path/to/rule.md",
168+ content,
169+ );
170+ expect(result.description).toBe(
171+ "This is a rule description from frontmatter",
172+ );
173+ });
174+});
added core/config/markdown/parseMarkdownRule.ts +69 −0
@@ -0,0 +1,69 @@
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+ name,
63+ rule: markdown,
64+ globs: frontmatter.globs,
65+ description: frontmatter.description,
66+ source: "rules-block",
67+ ruleFile: path,
68+ };
69+}
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/util.ts +1 −0
@@ -77,6 +77,7 @@
7777 model: model.model,
7878 apiKey: model.apiKey,
7979 apiBase: model.apiBase,
80+ maxStopWords: model.maxStopWords,
8081 defaultCompletionOptions: model.completionOptions,
8182 };
8283 if (model.systemMessage) {
modified core/config/yaml/loadYaml.ts +4 −4
@@ -42,7 +42,7 @@
4242
4343 import { getControlPlaneEnvSync } from "../../control-plane/env";
4444 import { getCleanUriPath } from "../../util/uri";
45-import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
45+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4646 import { LocalPlatformClient } from "./LocalPlatformClient";
4747 import { llmsFromModelConfig } from "./models";
4848
@@ -71,7 +71,7 @@
7171 command: server.command,
7272 args: server.args ?? [],
7373 env: server.env,
74- },
74+ } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
7575 timeout: server.connectionTimeout,
7676 };
7777 }
@@ -96,7 +96,7 @@
9696 // Add local .continue blocks
9797 const allLocalBlocks: PackageIdentifier[] = [];
9898 for (const blockType of BLOCK_TYPES) {
99- const localBlocks = await getAllDotContinueYamlFiles(
99+ const localBlocks = await getAllDotContinueDefinitionFiles(
100100 ide,
101101 { includeGlobal: true, includeWorkspace: true },
102102 blockType,
@@ -458,7 +458,7 @@
458458 transport: {
459459 type: "stdio",
460460 args: [],
461- ...server,
461+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
462462 },
463463 timeout: server.connectionTimeout,
464464 })),
modified core/control-plane/schema.ts +1 −0
@@ -26,6 +26,7 @@
2626 apiKey: z.string().optional(),
2727 apiBase: z.string().optional(),
2828 contextLength: z.number().optional(),
29+ maxStopWords: z.number().optional(),
2930 template: z
3031 .enum([
3132 "llama2",
modified core/core.ts +65 −70
@@ -35,7 +35,6 @@
3535
3636 import {
3737 ContextItemWithId,
38- DiffLine,
3938 IdeSettings,
4039 ModelDescription,
4140 RangeInFile,
@@ -62,61 +61,7 @@
6261 import { llmStreamChat } from "./llm/streamChat";
6362 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
6463 import type { IMessenger, Message } from "./protocol/messenger";
65-
66-// This function is used for jetbrains inline edit and apply
67-async function* streamDiffLinesGenerator(
68- configHandler: ConfigHandler,
69- abortedMessageIds: Set<string>,
70- msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
71-): AsyncGenerator<DiffLine> {
72- const {
73- highlighted,
74- prefix,
75- suffix,
76- input,
77- language,
78- modelTitle,
79- includeRulesInSystemMessage,
80- } = msg.data;
81-
82- const { config } = await configHandler.loadConfig();
83- if (!config) {
84- throw new Error("Failed to load config");
85- }
86-
87- // Title can be an edit, chat, or apply model
88- // Fall back to chat
89- const llm =
90- config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
91- config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
92- config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
93- config.selectedModelByRole.chat;
94-
95- if (!llm) {
96- throw new Error("No model selected");
97- }
98-
99- // rules included for edit, NOT apply
100- const rules = includeRulesInSystemMessage ? config.rules : undefined;
101-
102- for await (const diffLine of streamDiffLines({
103- highlighted,
104- prefix,
105- suffix,
106- llm,
107- rulesToInclude: rules,
108- input,
109- language,
110- onlyOneInsertion: false,
111- overridePrompt: undefined,
112- })) {
113- if (abortedMessageIds.has(msg.messageId)) {
114- abortedMessageIds.delete(msg.messageId);
115- break;
116- }
117- yield diffLine;
118- }
119-}
64+import { StreamAbortManager } from "./util/abortManager";
12065
12166 export class Core {
12267 configHandler: ConfigHandler;
@@ -132,7 +77,18 @@
13277 this.globalContext.get("indexingPaused") === true,
13378 );
13479
135- private abortedMessageIds: Set<string> = new Set();
80+ private messageAbortControllers = new Map<string, AbortController>();
81+ private addMessageAbortController(id: string): AbortController {
82+ const controller = new AbortController();
83+ this.messageAbortControllers.set(id, controller);
84+ controller.signal.addEventListener("abort", () => {
85+ this.messageAbortControllers.delete(id);
86+ });
87+ return controller;
88+ }
89+ private abortById(messageId: string) {
90+ this.messageAbortControllers.get(messageId)?.abort();
91+ }
13692
13793 invoke<T extends keyof ToCoreProtocol>(
13894 messageType: T,
@@ -301,7 +257,7 @@
301257 });
302258
303259 on("abort", (msg) => {
304- this.abortedMessageIds.add(msg.messageId);
260+ this.abortById(msg.data ?? msg.messageId);
305261 });
306262
307263 on("ping", (msg) => {
@@ -470,27 +426,28 @@
470426 }
471427 });
472428
473- on("llm/streamChat", (msg) =>
474- llmStreamChat(
429+ on("llm/streamChat", (msg) => {
430+ const abortController = this.addMessageAbortController(msg.messageId);
431+ return llmStreamChat(
475432 this.configHandler,
476- this.abortedMessageIds,
433+ abortController,
477434 msg,
478435 this.ide,
479436 this.messenger,
480- ),
481- );
437+ );
438+ });
482439
483440 on("llm/complete", async (msg) => {
484- const model = (await this.configHandler.loadConfig()).config
485- ?.selectedModelByRole.chat;
486-
441+ const { config } = await this.configHandler.loadConfig();
442+ const model = config?.selectedModelByRole.chat;
487443 if (!model) {
488444 throw new Error("No chat model selected");
489445 }
446+ const abortController = this.addMessageAbortController(msg.messageId);
490447
491448 const completion = await model.complete(
492449 msg.data.prompt,
493- new AbortController().signal,
450+ abortController.signal,
494451 msg.data.completionOptions,
495452 );
496453 return completion;
@@ -532,9 +489,47 @@
532489 this.completionProvider.cancel();
533490 });
534491
535- on("streamDiffLines", (msg) =>
536- streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
537- );
492+ on("streamDiffLines", async (msg) => {
493+ const { config } = await this.configHandler.loadConfig();
494+ if (!config) {
495+ throw new Error("Failed to load config");
496+ }
497+
498+ const { data } = msg;
499+
500+ // Title can be an edit, chat, or apply model
501+ // Fall back to chat
502+ const llm =
503+ config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
504+ config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
505+ config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
506+ config.selectedModelByRole.chat;
507+
508+ if (!llm) {
509+ throw new Error("No model selected");
510+ }
511+
512+ return streamDiffLines({
513+ highlighted: data.highlighted,
514+ prefix: data.prefix,
515+ suffix: data.suffix,
516+ llm,
517+ // rules included for edit, NOT apply
518+ rulesToInclude: data.includeRulesInSystemMessage
519+ ? config.rules
520+ : undefined,
521+ input: data.input,
522+ language: data.language,
523+ onlyOneInsertion: false,
524+ overridePrompt: undefined,
525+ abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
526+ });
527+ });
528+
529+ on("cancelApply", async (msg) => {
530+ const abortManager = StreamAbortManager.getInstance();
531+ abortManager.clear();
532+ });
538533
539534 on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
540535
modified core/edit/recursiveStream.ts +5 −2
@@ -16,6 +16,7 @@
1616
1717 export async function* recursiveStream(
1818 llm: ILLM,
19+ abortController: AbortController,
1920 prompt: ChatMessage[] | string,
2021 prediction: Prediction | undefined,
2122 currentBuffer = "",
@@ -28,7 +29,7 @@
2829 // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
2930
3031 if (typeof prompt === "string") {
31- const generator = llm.streamComplete(prompt, new AbortController().signal, {
32+ const generator = llm.streamComplete(prompt, abortController.signal, {
3233 raw: true,
3334 prediction: undefined,
3435 reasoning: false,
@@ -50,6 +51,7 @@
5051 // // TODO - Prediction capabilities lost because of partial input
5152 // yield* recursiveStream(
5253 // llm,
54+ // abortController,
5355 // continuationPrompt,
5456 // undefined,
5557 // buffer,
@@ -60,7 +62,7 @@
6062 }
6163 }
6264 } else {
63- const generator = llm.streamChat(prompt, new AbortController().signal, {
65+ const generator = llm.streamChat(prompt, abortController.signal, {
6466 prediction,
6567 reasoning: false,
6668 });
@@ -90,6 +92,7 @@
9092 // await generator.return(DUD_PROMPT_LOG);
9193 // yield* recursiveStream(
9294 // llm,
95+ // abortController,
9396 // continuationPrompt,
9497 // undefined,
9598 // buffer,
modified core/edit/streamDiffLines.ts +7 −1
@@ -20,6 +20,7 @@
2020 import { streamLines } from "../diff/util";
2121 import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
2222 import { gptEditPrompt } from "../llm/templates/edit";
23+import { StreamAbortManager } from "../util/abortManager";
2324 import { findLast } from "../util/findLast";
2425 import { Telemetry } from "../util/posthog";
2526 import { recursiveStream } from "./recursiveStream";
@@ -63,6 +64,7 @@
6364 highlighted,
6465 suffix,
6566 llm,
67+ abortControllerId,
6668 input,
6769 language,
6870 onlyOneInsertion,
@@ -73,12 +75,15 @@
7375 highlighted: string;
7476 suffix: string;
7577 llm: ILLM;
78+ abortControllerId: string;
7679 input: string;
7780 language: string | undefined;
7881 onlyOneInsertion: boolean;
7982 overridePrompt: ChatMessage[] | undefined;
8083 rulesToInclude: RuleWithSource[] | undefined;
8184 }): AsyncGenerator<DiffLine> {
85+ const abortManager = StreamAbortManager.getInstance();
86+ const abortController = abortManager.get(abortControllerId);
8287 void Telemetry.capture(
8388 "inlineEdit",
8489 {
@@ -122,6 +127,7 @@
122127 (msg) => msg.role === "user" || msg.role === "tool",
123128 ) as UserChatMessage | ToolResultChatMessage | undefined),
124129 baseSystemMessage: undefined,
130+ contextItems: [],
125131 })
126132 : undefined;
127133
@@ -157,7 +163,7 @@
157163 content: highlighted,
158164 };
159165
160- const completion = recursiveStream(llm, prompt, prediction);
166+ const completion = recursiveStream(llm, abortController, prompt, prediction);
161167
162168 let lines = streamLines(completion);
163169
modified core/index.d.ts +5 −0
@@ -1242,6 +1242,7 @@
12421242 language: string | undefined;
12431243 modelTitle: string | undefined;
12441244 includeRulesInSystemMessage: boolean;
1245+ fileUri?: string;
12451246 }
12461247
12471248 export interface HighlightedCodePayload {
@@ -1255,6 +1256,10 @@
12551256 streamId?: string;
12561257 }
12571258
1259+export interface ShowFilePayload {
1260+ filepath: string;
1261+}
1262+
12581263 export interface RangeInFileWithContents {
12591264 filepath: string;
12601265 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()) {
modified core/llm/index.ts +3 −0
@@ -390,6 +390,9 @@
390390
391391 // Error mapping to be more helpful
392392 if (!resp.ok) {
393+ if (resp.status === 499) {
394+ return resp; // client side cancellation
395+ }
393396 let text = await resp.text();
394397 if (resp.status === 404 && !resp.url.includes("/v1")) {
395398 const error = JSON.parse(text)?.error?.replace(/"/g, "'");
modified core/llm/llms/Anthropic.ts +5 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
23 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 class Anthropic extends BaseLLM {
77 static providerName = "anthropic";
@@ -213,6 +213,10 @@
213213 signal,
214214 });
215215
216+ if (response.status === 499) {
217+ return; // Aborted by user
218+ }
219+
216220 if (!response.ok) {
217221 const json = await response.json();
218222 if (json.type === "error") {
modified core/llm/llms/Asksage.ts +4 −8
@@ -134,10 +134,8 @@
134134 body: JSON.stringify(args),
135135 });
136136
137- if (!response.ok) {
138- throw new Error(
139- `API request failed with status ${response.status}: ${response.statusText}`,
140- );
137+ if (response.status === 499) {
138+ return ""; // Aborted by user
141139 }
142140
143141 const data = await response.json();
@@ -167,10 +165,8 @@
167165 signal,
168166 });
169167
170- if (!response.ok) {
171- throw new Error(
172- `API request failed with status ${response.status}: ${response.statusText}`,
173- );
168+ if (response.status === 499) {
169+ return; // Aborted by user
174170 }
175171
176172 const data = await response.json();
modified core/llm/llms/Bedrock.ts +1 −1
@@ -306,7 +306,7 @@
306306 }
307307
308308 const supportsTools =
309- PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
309+ (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
310310
311311 let toolConfig = supportsTools && options.tools
312312 ? {
modified core/llm/llms/Cloudflare.ts +1 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions } from "../../index.js";
23 import { renderChatMessage } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 export default class Cloudflare extends BaseLLM {
77 static providerName = "cloudflare";
modified core/llm/llms/Cohere.ts +5 −1
@@ -1,3 +1,4 @@
1+import { streamJSON } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
@@ -6,7 +7,6 @@
67 } from "../../index.js";
78 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
89 import { BaseLLM } from "../index.js";
9-import { streamJSON } from "../stream.js";
1010
1111 class Cohere extends BaseLLM {
1212 static providerName = "cohere";
@@ -84,6 +84,10 @@
8484 signal,
8585 });
8686
87+ if (resp.status === 499) {
88+ return; // Aborted by user
89+ }
90+
8791 if (options.stream === false) {
8892 const data = await resp.json();
8993 yield { role: "assistant", content: data.text };
modified core/llm/llms/Deepseek.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Flowise.ts +7 −3
@@ -132,12 +132,16 @@
132132 ): AsyncGenerator<ChatMessage> {
133133 const requestBody = this._getRequestBody(messages, options);
134134 const { socket, socketInfo } = await this._initializeSocket();
135- const request = this.fetch(this._getChatUrl(), {
135+ const response = await this.fetch(this._getChatUrl(), {
136136 method: "POST",
137137 headers: this._getHeaders(),
138138 body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
139139 signal,
140- }).then((res) => res.json());
140+ });
141+
142+ if (response.status === 499) {
143+ return; // Aborted by user
144+ }
141145
142146 while (await socketInfo.hasNextToken()) {
143147 yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@@ -145,7 +149,7 @@
145149 if (socketInfo.error) {
146150 socket.disconnect();
147151 try {
148- yield { role: "assistant", content: (await request).text };
152+ yield { role: "assistant", content: await response.text() };
149153 } catch (error: any) {
150154 yield { role: "assistant", content: (error as Error).message ?? error };
151155 }
modified core/llm/llms/FreeTrial.ts +1 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
23 import { getHeaders } from "../../continueServer/stubs/headers.js";
34 import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@@ -8,7 +9,6 @@
89 LLMOptions,
910 } from "../../index.js";
1011 import { BaseLLM } from "../index.js";
11-import { streamResponse } from "../stream.js";
1212
1313 class FreeTrial extends BaseLLM {
1414 static providerName = "free-trial";
modified core/llm/llms/Gemini.ts +4 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { v4 as uuidv4 } from "uuid";
23 import {
34 AssistantChatMessage,
@@ -10,7 +11,6 @@
1011 } from "../../index.js";
1112 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
1213 import { BaseLLM } from "../index.js";
13-import { streamResponse } from "../stream.js";
1414 import {
1515 GeminiChatContent,
1616 GeminiChatContentPart,
@@ -438,6 +438,9 @@
438438 body: JSON.stringify(body),
439439 signal,
440440 });
441+ if (response.status === 499) {
442+ return; // Aborted by user
443+ }
441444 const data = await response.json();
442445 yield { role: "assistant", content: data.candidates[0].content };
443446 }
modified core/llm/llms/HuggingFaceInferenceAPI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceInferenceAPI extends BaseLLM {
66 static providerName = "huggingface-inference-api";
modified core/llm/llms/HuggingFaceTGI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceTGI extends BaseLLM {
66 private static MAX_STOP_TOKENS = 4;
modified core/llm/llms/Inception.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33
44 import OpenAI from "./OpenAI.js";
55
modified core/llm/llms/LlamaCpp.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class LlamaCpp extends BaseLLM {
66 static providerName = "llama.cpp";
modified core/llm/llms/Moonshot.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Ollama.ts +4 −1
@@ -2,6 +2,7 @@
22 import { JSONSchema7, JSONSchema7Object } from "json-schema";
33 import { v4 as uuidv4 } from "uuid";
44
5+import { streamResponse } from "@continuedev/fetch";
56 import {
67 ChatMessage,
78 ChatMessageRole,
@@ -12,7 +13,6 @@
1213 import { renderChatMessage } from "../../util/messageContent.js";
1314 import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
1415 import { BaseLLM } from "../index.js";
15-import { streamResponse } from "../stream.js";
1616
1717 type OllamaChatMessage = {
1818 role: ChatMessageRole;
@@ -457,6 +457,9 @@
457457 }
458458
459459 if (chatOptions.stream === false) {
460+ if (response.status === 499) {
461+ return; // Aborted by user
462+ }
460463 const json = (await response.json()) as OllamaChatResponse;
461464 yield convertChatMessage(json);
462465 } else {
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 +8 −5
@@ -3,6 +3,7 @@
33 ChatCompletionMessageParam,
44 } from "openai/resources/index";
55
6+import { streamSse } from "@continuedev/fetch";
67 import {
78 ChatMessage,
89 CompletionOptions,
@@ -16,7 +17,6 @@
1617 LlmApiRequestType,
1718 toChatBody,
1819 } from "../openaiTypeConverters.js";
19-import { streamSse } from "../stream.js";
2020
2121 const NON_CHAT_MODELS = [
2222 "text-davinci-002",
@@ -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;
@@ -352,6 +352,9 @@
352352
353353 // Handle non-streaming response
354354 if (body.stream === false) {
355+ if (response.status === 499) {
356+ return; // Aborted by user
357+ }
355358 const data = await response.json();
356359 yield data.choices[0].message;
357360 return;
modified core/llm/llms/SiliconFlow.ts +2 −2
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
@@ -58,7 +58,7 @@
5858 console.warn("[SiliconFlow] rerank: query is empty");
5959 return [];
6060 }
61-
61+
6262 if (!chunks || chunks.length === 0) {
6363 console.warn("[SiliconFlow] rerank: chunks is empty");
6464 return [];
modified core/llm/llms/VertexAI.ts +23 −5
@@ -1,9 +1,9 @@
11 import { GoogleAuth } from "google-auth-library";
22
3+import { streamResponse, streamSse } from "@continuedev/fetch";
34 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
45 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
56 import { BaseLLM } from "../index.js";
6-import { streamResponse, streamSse } from "../stream.js";
77
88 import Anthropic from "./Anthropic.js";
99 import Gemini from "./Gemini.js";
@@ -95,6 +95,7 @@
9595 protected async *StreamChatAnthropic(
9696 messages: ChatMessage[],
9797 options: CompletionOptions,
98+ signal: AbortSignal,
9899 ): AsyncGenerator<ChatMessage> {
99100 const systemMessage = stripImages(
100101 messages.filter((m) => m.role === "system")[0]?.content ?? "",
@@ -128,8 +129,13 @@
128129 ]
129130 : systemMessage,
130131 }),
132+ signal,
131133 });
132134
135+ if (response.status === 499) {
136+ return; // Aborted by user
137+ }
138+
133139 if (options.stream === false) {
134140 const data = await response.json();
135141 yield { role: "assistant", content: data.content[0].text };
@@ -150,6 +156,7 @@
150156 private async *streamChatGemini(
151157 messages: ChatMessage[],
152158 options: CompletionOptions,
159+ signal: AbortSignal,
153160 ): AsyncGenerator<ChatMessage> {
154161 const apiURL = new URL(
155162 `publishers/google/models/${options.model}:streamGenerateContent`,
@@ -160,6 +167,7 @@
160167 const response = await this.fetch(apiURL, {
161168 method: "POST",
162169 body: JSON.stringify(body),
170+ signal,
163171 });
164172 for await (const message of this.geminiInstance.processGeminiResponse(
165173 streamResponse(response),
@@ -171,6 +179,7 @@
171179 private async *streamChatBison(
172180 messages: ChatMessage[],
173181 options: CompletionOptions,
182+ signal: AbortSignal,
174183 ): AsyncGenerator<ChatMessage> {
175184 const instances = messages.map((message) => ({ prompt: message.content }));
176185
@@ -193,7 +202,11 @@
193202 const response = await this.fetch(apiURL, {
194203 method: "POST",
195204 body: JSON.stringify(body),
205+ signal,
196206 });
207+ if (response.status === 499) {
208+ return; // Aborted by user
209+ }
197210 const data = await response.json();
198211 yield { role: "assistant", content: data.predictions[0].content };
199212 }
@@ -203,6 +216,7 @@
203216 protected async *StreamChatMistral(
204217 messages: ChatMessage[],
205218 options: CompletionOptions,
219+ signal: AbortSignal,
206220 ): AsyncGenerator<ChatMessage> {
207221 const apiBase = this.apiBase!;
208222 const apiURL = new URL(
@@ -228,6 +242,7 @@
228242 const response = await this.fetch(apiURL, {
229243 method: "POST",
230244 body: JSON.stringify(body),
245+ signal,
231246 });
232247
233248 for await (const chunk of streamSse(response)) {
@@ -304,6 +319,9 @@
304319 }),
305320 signal,
306321 });
322+ if (resp.status === 499) {
323+ return; // Aborted by user
324+ }
307325 // Streaming is not supported by code-gecko
308326 // TODO: convert to non-streaming fim method when one exist in continue.
309327 yield (await resp.json()).predictions[0].content;
@@ -323,14 +341,14 @@
323341 ? this.geminiInstance.removeSystemMessage(messages)
324342 : messages;
325343 if (this.vertexProvider === "gemini") {
326- yield* this.streamChatGemini(convertedMsgs, options);
344+ yield* this.streamChatGemini(convertedMsgs, options, signal);
327345 } else if (this.vertexProvider === "mistral") {
328- yield* this.StreamChatMistral(messages, options);
346+ yield* this.StreamChatMistral(messages, options, signal);
329347 } else if (this.vertexProvider === "anthropic") {
330- yield* this.StreamChatAnthropic(messages, options);
348+ yield* this.StreamChatAnthropic(messages, options, signal);
331349 } else {
332350 if (options.model.includes("bison")) {
333- yield* this.streamChatBison(convertedMsgs, options);
351+ yield* this.streamChatBison(convertedMsgs, options, signal);
334352 } else {
335353 throw new Error(`Unsupported model: ${options.model}`);
336354 }
modified core/llm/llms/WatsonX.ts +37 −53
@@ -1,15 +1,12 @@
1+import { streamResponse, streamSse } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
45 CompletionOptions,
56 LLMOptions,
67 } from "../../index.js";
7-import {
8- fromChatCompletionChunk,
9-} from "../openaiTypeConverters.js";
10-import { renderChatMessage } from "../../util/messageContent.js";
118 import { BaseLLM } from "../index.js";
12-import { streamResponse, streamSse } from "../stream.js";
9+import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
1310
1411 let watsonxToken = {
1512 expiration: 0,
@@ -86,7 +83,7 @@
8683 }
8784
8885 _getEndpoint(endpoint: string): string {
89- return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
86+ return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
9087 }
9188
9289 static providerName = "watsonx";
@@ -182,7 +179,6 @@
182179 signal: AbortSignal,
183180 options: CompletionOptions,
184181 ): AsyncGenerator<string> {
185-
186182 await this.updateWatsonxToken();
187183
188184 const stopSequences = options.stop?.slice(0, 6) ?? [];
@@ -214,44 +210,38 @@
214210 payload.project_id = this.projectId;
215211 }
216212
217- var response = await this.fetch(url, {
213+ const response = await this.fetch(url, {
218214 method: "POST",
219215 headers: headers,
220216 body: JSON.stringify(payload),
221217 signal,
222218 });
223219
224- if (!response.ok || response.body === null) {
225- throw new Error(
226- "Something went wrong. No response received, check your connection",
227- );
228- } else {
229- for await (const value of streamResponse(response)) {
230- const lines = value.split("\n");
231- let generatedChunk = "";
232- let generatedTextIndex = undefined;
233- lines.forEach((el: string) => {
234- // console.log(`${el}`);
235- if (el.startsWith("id:")) {
236- generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
237- if (isNaN(generatedTextIndex)) {
238- console.error(`Unable to parse stream chunk ID: ${el}`);
239- }
240- } else if (el.startsWith("data:")) {
241- const dataStr = el.replace(/^data:\s+/, "");
242- try {
243- const data = JSON.parse(dataStr);
244- data.results.forEach((result: any) => {
245- generatedChunk += result.generated_text || "";
246- });
247- } catch (e) {
248- // parsing error is expected with streaming response
249- // console.error(`Error parsing JSON string: ${dataStr}`, e);
250- }
220+ for await (const value of streamResponse(response)) {
221+ const lines = value.split("\n");
222+ let generatedChunk = "";
223+ let generatedTextIndex = undefined;
224+ lines.forEach((el: string) => {
225+ // console.log(`${el}`);
226+ if (el.startsWith("id:")) {
227+ generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
228+ if (isNaN(generatedTextIndex)) {
229+ console.error(`Unable to parse stream chunk ID: ${el}`);
251230 }
252- });
253- yield generatedChunk
254- }
231+ } else if (el.startsWith("data:")) {
232+ const dataStr = el.replace(/^data:\s+/, "");
233+ try {
234+ const data = JSON.parse(dataStr);
235+ data.results.forEach((result: any) => {
236+ generatedChunk += result.generated_text || "";
237+ });
238+ } catch (e) {
239+ // parsing error is expected with streaming response
240+ // console.error(`Error parsing JSON string: ${dataStr}`, e);
241+ }
242+ }
243+ });
244+ yield generatedChunk;
255245 }
256246 }
257247
@@ -267,7 +257,7 @@
267257 const headers = this._getHeaders();
268258
269259 const payload: any = {
270- messages: messages,
260+ messages: messages,
271261 max_tokens: options.maxTokens ?? 1024,
272262 stop: stopSequences,
273263 frequency_penalty: options.frequencyPenalty || 1,
@@ -281,36 +271,30 @@
281271
282272 if (!!options.temperature) {
283273 payload.temperature = options.temperature;
284- }
274+ }
285275 if (!!options.topP) {
286276 payload.top_p = options.topP;
287277 }
288278 if (!!options.tools) {
289279 payload.tools = options.tools;
290280 if (options.toolChoice) {
291- payload.tool_choice = options.toolChoice;
281+ payload.tool_choice = options.toolChoice;
292282 } else {
293- payload.tool_choice_option = "auto";
283+ payload.tool_choice_option = "auto";
294284 }
295285 }
296286
297- var response = await this.fetch(url, {
287+ const response = await this.fetch(url, {
298288 method: "POST",
299289 headers: headers,
300290 body: JSON.stringify(payload),
301291 signal,
302292 });
303293
304- if (!response.ok || response.body === null) {
305- throw new Error(
306- "Something went wrong. No response received, check your connection",
307- );
308- } else {
309- for await (const value of streamSse(response)) {
310- const chunk = fromChatCompletionChunk(value);
311- if (chunk) {
312- yield chunk;
313- }
294+ for await (const value of streamSse(response)) {
295+ const chunk = fromChatCompletionChunk(value);
296+ if (chunk) {
297+ yield chunk;
314298 }
315299 }
316300 }
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
@@ -28,8 +28,12 @@
2828 // to call whatever LLM API is chosen
2929 private actualApiBase?: string;
3030
31+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
32+ private configEnv?: Record<string, any>;
33+
3134 constructor(options: LLMOptions) {
3235 super(options);
36+ this.configEnv = options.env;
3337 this.actualApiBase = options.apiBase;
3438 this.apiKeyLocation = options.apiKeyLocation;
3539 this.orgScopeId = options.orgScopeId;
@@ -54,6 +58,7 @@
5458 apiKeyLocation: this.apiKeyLocation,
5559 apiBase: this.actualApiBase,
5660 orgScopeId: this.orgScopeId ?? null,
61+ env: this.configEnv,
5762 };
5863 return {
5964 continueProperties,
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) {
deleted core/llm/stream.test.ts +0 −72
@@ -1,72 +0,0 @@
1-import { Readable } from "stream";
2-import { streamSse } from "./stream";
3-
4-function createMockResponse(sseLines: string[]): Response {
5- // Create a Readable stream that emits the SSE lines
6- const stream = new Readable({
7- read() {
8- for (const line of sseLines) {
9- this.push(line + "\n\n");
10- }
11- this.push(null); // End of stream
12- }
13- }) as any;
14-
15- // Minimal Response mock
16- return {
17- status: 200,
18- body: stream,
19- text: async () => "",
20- } as unknown as Response;
21-}
22-
23-describe("streamSse", () => {
24- it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25- const sseLines = [
26- 'data: {"foo": "bar"}',
27- 'data: {"baz": 42}',
28- 'data:[DONE]'
29- ];
30- const response = createMockResponse(sseLines);
31-
32- const results = [];
33- for await (const data of streamSse(response)) {
34- results.push(data);
35- }
36-
37- expect(results).toEqual([
38- { foo: "bar" },
39- { baz: 42 }
40- ]);
41- });
42-
43- it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
44- const sseLines = [
45- 'data: {"foo": "bar"}',
46- 'data: {"baz": 42}',
47- 'data: [DONE]'
48- ];
49- const response = createMockResponse(sseLines);
50-
51- const results = [];
52- for await (const data of streamSse(response)) {
53- results.push(data);
54- }
55-
56- expect(results).toEqual([
57- { foo: "bar" },
58- { baz: 42 }
59- ]);
60- });
61-
62- it("throws on malformed JSON", async () => {
63- const sseLines = [
64- 'data: {"foo": "bar"',
65- 'data:[DONE]'
66- ];
67- const response = createMockResponse(sseLines);
68-
69- const iterator = streamSse(response)[Symbol.asyncIterator]();
70- await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
71- });
72-});
modified core/llm/stream.ts +1 −1
@@ -1,4 +1,4 @@
1-async function* toAsyncIterable(
1+export async function* toAsyncIterable(
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
modified core/llm/streamChat.ts +27 −35
@@ -8,7 +8,7 @@
88
99 export async function* llmStreamChat(
1010 configHandler: ConfigHandler,
11- abortedMessageIds: Set<string>,
11+ abortController: AbortController,
1212 msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
1313 ide: IDE,
1414 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
@@ -75,52 +75,44 @@
7575 selectedCode,
7676 config,
7777 fetch: (url, init) =>
78- fetchwithRequestOptions(url, init, config.requestOptions),
78+ fetchwithRequestOptions(
79+ url,
80+ {
81+ ...init,
82+ signal: abortController.signal,
83+ },
84+ config.requestOptions,
85+ ),
7986 completionOptions,
8087 });
81- const checkActiveInterval = setInterval(() => {
82- if (abortedMessageIds.has(msg.messageId)) {
83- abortedMessageIds.delete(msg.messageId);
84- clearInterval(checkActiveInterval);
85- }
86- }, 100);
87- try {
88- let next = await gen.next();
89- while (!next.done) {
90- if (abortedMessageIds.has(msg.messageId)) {
91- abortedMessageIds.delete(msg.messageId);
92- next = await gen.return(errorPromptLog);
93- clearInterval(checkActiveInterval);
94- break;
95- }
96- if (next.value) {
97- yield {
98- role: "assistant",
99- content: next.value,
100- };
101- }
102- next = await gen.next();
88+ let next = await gen.next();
89+ while (!next.done) {
90+ if (abortController.signal.aborted) {
91+ next = await gen.return(errorPromptLog);
92+ break;
10393 }
104- if (!next.done) {
105- throw new Error("Will never happen");
94+ if (next.value) {
95+ yield {
96+ role: "assistant",
97+ content: next.value,
98+ };
10699 }
107-
108- return next.value;
109- } catch (e) {
110- throw e;
111- } finally {
112- clearInterval(checkActiveInterval);
100+ next = await gen.next();
113101 }
102+ if (!next.done) {
103+ throw new Error("Will never happen");
104+ }
105+
106+ return next.value;
114107 } else {
115108 const gen = model.streamChat(
116109 messages,
117- new AbortController().signal,
110+ abortController.signal,
118111 completionOptions,
119112 );
120113 let next = await gen.next();
121114 while (!next.done) {
122- if (abortedMessageIds.has(msg.messageId)) {
123- abortedMessageIds.delete(msg.messageId);
115+ if (abortController.signal.aborted) {
124116 next = await gen.return(errorPromptLog);
125117 break;
126118 }
modified core/llm/toolSupport.test.ts +3 −0
@@ -191,6 +191,7 @@
191191 expect(supportsFn("pixtral-12b-2409")).toBe(true);
192192 expect(supportsFn("pixtral-large-latest")).toBe(true);
193193 expect(supportsFn("open-mistral-nemo")).toBe(true);
194+ expect(supportsFn("devstral-latest")).toBe(true);
194195 });
195196
196197 it("should return false for other unsupported models", () => {
@@ -206,6 +207,7 @@
206207 expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
207208 expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
208209 expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
210+ expect(supportsFn("DEVSTRAL-LATEST")).toBe(true);
209211 });
210212 });
211213
@@ -228,6 +230,7 @@
228230 expect(supportsFn("aya-expanse")).toBe(true);
229231 expect(supportsFn("firefunction-v2")).toBe(true);
230232 expect(supportsFn("mistral-7b")).toBe(true);
233+ expect(supportsFn("devstral-24b")).toBe(true);
231234 });
232235
233236 it("should return false for explicitly unsupported models", () => {
modified core/llm/toolSupport.ts +27 −9
@@ -18,6 +18,7 @@
1818 "claude-3.5",
1919 "claude-3-7",
2020 "claude-3.7",
21+ "claude-4",
2122 "gpt-4",
2223 "o3",
2324 "gemini",
@@ -25,9 +26,13 @@
2526 },
2627 anthropic: (model) => {
2728 if (
28- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
29- model.toLowerCase().startsWith(part),
30- )
29+ [
30+ "claude-3-5",
31+ "claude-3.5",
32+ "claude-3-7",
33+ "claude-3.7",
34+ "claude-4",
35+ ].some((part) => model.toLowerCase().startsWith(part))
3136 ) {
3237 return true;
3338 }
@@ -81,9 +86,13 @@
8186 // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
8287 if (
8388 model.toLowerCase().includes("sonnet") &&
84- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
85- model.toLowerCase().includes(part),
86- )
89+ [
90+ "claude-3-5",
91+ "claude-3.5",
92+ "claude-3-7",
93+ "claude-3.7",
94+ "claude-4",
95+ ].some((part) => model.toLowerCase().includes(part))
8796 ) {
8897 return true;
8998 }
@@ -101,6 +110,7 @@
101110 "pixtral",
102111 "ministral",
103112 "mistral-nemo",
113+ "devstral",
104114 ].some((part) => model.toLowerCase().includes(part))
105115 );
106116 },
@@ -143,6 +153,7 @@
143153 "aya-expanse",
144154 "firefunction-v2",
145155 "mistral",
156+ "devstral",
146157 ].some((part) => modelName.toLowerCase().includes(part))
147158 ) {
148159 return true;
@@ -174,9 +185,14 @@
174185 return false;
175186 }
176187 if (
177- ["llama-3", "llama-4", "mistral", "codestral", "granite-3"].some(
178- (part) => model.toLowerCase().includes(part),
179- )
188+ [
189+ "llama-3",
190+ "llama-4",
191+ "mistral",
192+ "codestral",
193+ "granite-3",
194+ "devstral",
195+ ].some((part) => model.toLowerCase().includes(part))
180196 ) {
181197 return true;
182198 }
@@ -200,6 +216,7 @@
200216 "openai/o3",
201217 "openai/o4",
202218 "anthropic/claude-3",
219+ "anthropic/claude-4",
203220 "microsoft/phi-3",
204221 "google/gemini-flash-1.5",
205222 "google/gemini-2",
@@ -214,6 +231,7 @@
214231 "mistralai/codestral",
215232 "mistralai/mixtral",
216233 "mistral/ministral",
234+ "mistral/devstral",
217235 "mistralai/pixtral",
218236 "meta-llama/llama-3.3",
219237 "amazon/nova",
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/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 core/package.json +2 −2
@@ -49,9 +49,9 @@
4949 "@aws-sdk/credential-providers": "^3.778.0",
5050 "@continuedev/config-types": "^1.0.13",
5151 "@continuedev/config-yaml": "file:../packages/config-yaml",
52- "@continuedev/fetch": "^1.0.6",
52+ "@continuedev/fetch": "^1.0.10",
5353 "@continuedev/llm-info": "^1.0.8",
54- "@continuedev/openai-adapters": "^1.0.19",
54+ "@continuedev/openai-adapters": "^1.0.25",
5555 "@modelcontextprotocol/sdk": "^1.5.0",
5656 "@mozilla/readability": "^0.5.0",
5757 "@octokit/rest": "^20.1.1",
modified core/protocol/core.ts +1 −0
@@ -46,6 +46,7 @@
4646 // Special
4747 ping: [string, string];
4848 abort: [undefined, void];
49+ cancelApply: [undefined, void];
4950
5051 // History
5152 "history/list": [ListHistoryOptions, SessionMetadata[]];
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/definitions/createRuleBlock.ts +4 −0
@@ -28,6 +28,10 @@
2828 description:
2929 "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
3030 },
31+ description: {
32+ type: "string",
33+ description: "Short description of the rule",
34+ },
3135 globs: {
3236 type: "string",
3337 description:
modified core/tools/implementations/createRuleBlock.test.ts +54 −36
@@ -1,4 +1,4 @@
1-import * as YAML from "yaml";
1+import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
22 import { createRuleBlockImpl } from "./createRuleBlock";
33
44 // Mock the extras parameter with necessary functions
@@ -17,33 +17,6 @@
1717 jest.clearAllMocks();
1818 });
1919
20- it("should create a basic rule with name and rule content", async () => {
21- const args = {
22- name: "Test Rule",
23- rule: "Always write tests",
24- };
25-
26- const result = await createRuleBlockImpl(args, mockExtras as any);
27-
28- // Verify that writeFile was called with the correct YAML
29- expect(mockIde.writeFile).toHaveBeenCalled();
30- const yamlContent = mockIde.writeFile.mock.calls[0][1];
31- const parsedYaml = YAML.parse(yamlContent);
32-
33- // Verify the structure of the YAML
34- expect(parsedYaml).toEqual({
35- name: "Test Rule",
36- version: "0.0.1",
37- schema: "v1",
38- rules: [
39- {
40- name: "Test Rule",
41- rule: "Always write tests",
42- },
43- ],
44- });
45- });
46-
4720 it("should create a rule with glob pattern", async () => {
4821 const args = {
4922 name: "TypeScript Rule",
@@ -53,14 +26,16 @@
5326
5427 await createRuleBlockImpl(args, mockExtras as any);
5528
56- // Verify the YAML structure with globs
57- const yamlContent = mockIde.writeFile.mock.calls[0][1];
58- const parsedYaml = YAML.parse(yamlContent);
59- expect(parsedYaml.rules[0]).toEqual({
60- name: "TypeScript Rule",
61- rule: "Use interfaces for object shapes",
29+ const fileContent = mockIde.writeFile.mock.calls[0][1];
30+
31+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
32+
33+ expect(frontmatter).toEqual({
6234 globs: "**/*.{ts,tsx}",
6335 });
36+
37+ expect(markdown).toContain("# TypeScript Rule");
38+ expect(markdown).toContain("Use interfaces for object shapes");
6439 });
6540
6641 it("should create a filename based on sanitized rule name", async () => {
@@ -71,8 +46,51 @@
7146
7247 await createRuleBlockImpl(args, mockExtras as any);
7348
74- // Check that the filename is sanitized
7549 const fileUri = mockIde.writeFile.mock.calls[0][0];
76- expect(fileUri).toContain("special-chracters-spaces.yaml");
50+ expect(fileUri).toContain("special-chracters-spaces.md");
51+ });
52+
53+ it("should create a rule with description pattern", async () => {
54+ const args = {
55+ name: "Description Test",
56+ rule: "This is the rule content",
57+ description: "This is a detailed explanation of the rule",
58+ };
59+
60+ await createRuleBlockImpl(args, mockExtras as any);
61+
62+ const fileContent = mockIde.writeFile.mock.calls[0][1];
63+
64+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
65+
66+ expect(frontmatter).toEqual({
67+ description: "This is a detailed explanation of the rule",
68+ });
69+
70+ expect(markdown).toContain("# Description Test");
71+ expect(markdown).toContain("This is the rule content");
72+ });
73+
74+ it("should include both globs and description in frontmatter", async () => {
75+ const args = {
76+ name: "Complete Rule",
77+ rule: "Follow this standard",
78+ description: "This rule enforces our team standards",
79+ globs: "**/*.js",
80+ };
81+
82+ await createRuleBlockImpl(args, mockExtras as any);
83+
84+ const fileContent = mockIde.writeFile.mock.calls[0][1];
85+
86+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
87+
88+ expect(frontmatter).toEqual({
89+ description: "This rule enforces our team standards",
90+ globs: "**/*.js",
91+ });
92+
93+ expect(markdown).toContain("# Complete Rule");
94+ expect(markdown).toContain("Follow this standard");
7795 });
7896 });
modified core/tools/implementations/createRuleBlock.ts +22 −17
@@ -1,4 +1,3 @@
1-import { ConfigYaml } from "@continuedev/config-yaml";
21 import * as YAML from "yaml";
32 import { ToolImpl } from ".";
43 import { joinPathsToUri } from "../../util/uri";
@@ -6,6 +5,7 @@
65 export interface CreateRuleBlockArgs {
76 name: string;
87 rule: string;
8+ description: string;
99 globs?: string;
1010 }
1111
@@ -19,41 +19,46 @@
1919 .replace(/[^a-z0-9\s-]/g, "")
2020 .replace(/\s+/g, "-");
2121
22- const ruleObject = {
23- name: args.name,
24- rule: args.rule,
25- ...(args.globs ? { globs: args.globs.trim() } : {}),
26- };
22+ const fileExtension = "md";
2723
28- const ruleBlock: ConfigYaml = {
29- name: args.name,
30- version: "0.0.1",
31- schema: "v1",
32- rules: [ruleObject],
33- };
24+ const frontmatter: Record<string, string> = {};
3425
35- const ruleYaml = YAML.stringify(ruleBlock);
26+ if (args.globs) {
27+ frontmatter.globs = args.globs.trim();
28+ }
3629
30+ if (args.description) {
31+ frontmatter.description = args.description.trim();
32+ }
33+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
34+ let fileContent = `---
35+${frontmatterYaml}
36+---
37+
38+# ${args.name}
39+
40+${args.rule}
41+`;
3742 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
3843 const rulesDirUri = joinPathsToUri(
3944 localContinueDir,
4045 ".continue",
4146 "rules",
42- `${safeRuleName}.yaml`,
47+ `${safeRuleName}.${fileExtension}`,
4348 );
4449
45- await extras.ide.writeFile(rulesDirUri, ruleYaml);
50+ await extras.ide.writeFile(rulesDirUri, fileContent);
4651 await extras.ide.openFile(rulesDirUri);
4752
4853 return [
4954 {
5055 name: "New Rule Block",
51- description: "", // No description throws an error in the GUI
56+ description: args.description || "",
5257 uri: {
5358 type: "file",
5459 value: rulesDirUri,
5560 },
56- content: "Rule created successfully",
61+ content: `Rule created successfully`,
5762 },
5863 ];
5964 };
added core/util/abortManager.ts +37 −0
@@ -0,0 +1,37 @@
1+export class StreamAbortManager {
2+ private static instance: StreamAbortManager;
3+ private controllers: Map<string, AbortController>;
4+
5+ private constructor() {
6+ this.controllers = new Map();
7+ }
8+
9+ public static getInstance(): StreamAbortManager {
10+ if (!StreamAbortManager.instance) {
11+ StreamAbortManager.instance = new StreamAbortManager();
12+ }
13+ return StreamAbortManager.instance;
14+ }
15+
16+ public get(id: string): AbortController {
17+ let controller = this.controllers.get(id);
18+ if (!controller) {
19+ controller = new AbortController();
20+ this.controllers.set(id, controller);
21+ }
22+ return controller;
23+ }
24+
25+ public abort(id: string): void {
26+ const controller = this.controllers.get(id);
27+ if (controller) {
28+ controller.abort();
29+ this.controllers.delete(id);
30+ }
31+ }
32+
33+ public clear(): void {
34+ this.controllers.forEach((controller) => controller.abort());
35+ this.controllers.clear();
36+ }
37+}
modified core/vendor/.gitignore +1 −1
@@ -1,1 +1,1 @@
1-!node_modules
No newline at the end of the file
1+node_modules
No newline at the end of the file
modified core/vendor/package-lock.json +105 −17
@@ -10,6 +10,9 @@
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@xenova/transformers": "^2.14.0"
13+ },
14+ "engines": {
15+ "node": ">=20.19.0"
1316 }
1417 },
1518 "node_modules/@huggingface/jinja": {
@@ -105,6 +108,78 @@
105108 "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz",
106109 "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw=="
107110 },
111+ "node_modules/bare-events": {
112+ "version": "2.5.4",
113+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz",
114+ "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==",
115+ "license": "Apache-2.0",
116+ "optional": true
117+ },
118+ "node_modules/bare-fs": {
119+ "version": "4.1.5",
120+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz",
121+ "integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==",
122+ "license": "Apache-2.0",
123+ "optional": true,
124+ "dependencies": {
125+ "bare-events": "^2.5.4",
126+ "bare-path": "^3.0.0",
127+ "bare-stream": "^2.6.4"
128+ },
129+ "engines": {
130+ "bare": ">=1.16.0"
131+ },
132+ "peerDependencies": {
133+ "bare-buffer": "*"
134+ },
135+ "peerDependenciesMeta": {
136+ "bare-buffer": {
137+ "optional": true
138+ }
139+ }
140+ },
141+ "node_modules/bare-os": {
142+ "version": "3.6.1",
143+ "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
144+ "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
145+ "license": "Apache-2.0",
146+ "optional": true,
147+ "engines": {
148+ "bare": ">=1.14.0"
149+ }
150+ },
151+ "node_modules/bare-path": {
152+ "version": "3.0.0",
153+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
154+ "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
155+ "license": "Apache-2.0",
156+ "optional": true,
157+ "dependencies": {
158+ "bare-os": "^3.0.1"
159+ }
160+ },
161+ "node_modules/bare-stream": {
162+ "version": "2.6.5",
163+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz",
164+ "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==",
165+ "license": "Apache-2.0",
166+ "optional": true,
167+ "dependencies": {
168+ "streamx": "^2.21.0"
169+ },
170+ "peerDependencies": {
171+ "bare-buffer": "*",
172+ "bare-events": "*"
173+ },
174+ "peerDependenciesMeta": {
175+ "bare-buffer": {
176+ "optional": true
177+ },
178+ "bare-events": {
179+ "optional": true
180+ }
181+ }
182+ },
108183 "node_modules/base64-js": {
109184 "version": "1.5.1",
110185 "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -444,9 +519,10 @@
444519 }
445520 },
446521 "node_modules/prebuild-install/node_modules/tar-fs": {
447- "version": "2.1.1",
448- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
449- "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
522+ "version": "2.1.2",
523+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
524+ "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
525+ "license": "MIT",
450526 "dependencies": {
451527 "chownr": "^1.1.1",
452528 "mkdirp-classic": "^0.5.2",
@@ -503,11 +579,6 @@
503579 "once": "^1.3.1"
504580 }
505581 },
506- "node_modules/queue-tick": {
507- "version": "1.0.1",
508- "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
509- "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag=="
510- },
511582 "node_modules/rc": {
512583 "version": "1.2.8",
513584 "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
@@ -642,12 +713,16 @@
642713 }
643714 },
644715 "node_modules/streamx": {
645- "version": "2.15.6",
646- "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz",
647- "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==",
716+ "version": "2.22.0",
717+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz",
718+ "integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==",
719+ "license": "MIT",
648720 "dependencies": {
649- "fast-fifo": "^1.1.0",
650- "queue-tick": "^1.0.1"
721+ "fast-fifo": "^1.3.2",
722+ "text-decoder": "^1.1.0"
723+ },
724+ "optionalDependencies": {
725+ "bare-events": "^2.2.0"
651726 }
652727 },
653728 "node_modules/string_decoder": {
@@ -667,13 +742,17 @@
667742 }
668743 },
669744 "node_modules/tar-fs": {
670- "version": "3.0.4",
671- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz",
672- "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==",
745+ "version": "3.0.8",
746+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
747+ "integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
748+ "license": "MIT",
673749 "dependencies": {
674- "mkdirp-classic": "^0.5.2",
675750 "pump": "^3.0.0",
676751 "tar-stream": "^3.1.5"
752+ },
753+ "optionalDependencies": {
754+ "bare-fs": "^4.0.1",
755+ "bare-path": "^3.0.0"
677756 }
678757 },
679758 "node_modules/tar-stream": {
@@ -686,6 +765,15 @@
686765 "streamx": "^2.15.0"
687766 }
688767 },
768+ "node_modules/text-decoder": {
769+ "version": "1.2.3",
770+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz",
771+ "integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==",
772+ "license": "Apache-2.0",
773+ "dependencies": {
774+ "b4a": "^1.6.4"
775+ }
776+ },
689777 "node_modules/tunnel-agent": {
690778 "version": "0.6.0",
691779 "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
modified docs/docs/reference.md +2 −1
@@ -188,6 +188,7 @@
188188 not currently used.
189189 - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
190190 provider and model. Supported capabilities include `tool_use` and `image_input`.
191+- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
191192 - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
192193 `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
193194 `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@@ -406,7 +407,7 @@
406407 - `destination` (**required**): The destination/endpoint that will receive the data. Can be:
407408 - an HTTP endpoint that will receive a POST request with a JSON blob
408409 - a file URL to a directory in which events will be dumpted to `.jsonl` files
409-- `schema` (**required**): the schema version of the JSON blobs to be sent
410+- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
410411 - `events`: an array of event names to include. Defaults to all events if not specified.
411412 - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
412413 contents, prompts, and completions. Defaults to `all`
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 docs/docusaurus.config.js +3 −1
@@ -66,7 +66,9 @@
6666 ],
6767
6868 scripts: [
69- '!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();',
69+ {
70+ src: "/scripts/custom-reo.js", // it references from static folder
71+ },
7072 ],
7173
7274 themeConfig:
added docs/static/scripts/custom-reo.js +1 −0
@@ -0,0 +1,1 @@
1+!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();
No newline at the end of the file
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/Diffs.kt +1 −1
@@ -108,7 +108,7 @@
108108 )
109109 continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
110110 continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
111-
111+ continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
112112 cleanUpFile(file)
113113 }
114114
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 +2 −3
@@ -111,7 +111,8 @@
111111 suffix = suffix,
112112 language = virtualFile?.fileType?.name,
113113 modelTitle = modelTitle,
114- includeRulesInSystemMessage = includeRulesInSystemMessage
114+ includeRulesInSystemMessage = includeRulesInSystemMessage,
115+ fileUri = virtualFile?.url
115116 ),
116117 null
117118 ) { response ->
@@ -289,7 +290,6 @@
289290 }
290291 }
291292
292-
293293 private fun handleFinishedResponse() {
294294 ApplicationManager.getApplication().invokeLater {
295295 // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
@@ -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 +6 −1
@@ -244,10 +244,15 @@
244244 val input: String,
245245 val language: String?,
246246 val modelTitle: String?,
247- val includeRulesInSystemMessage: Boolean
247+ val includeRulesInSystemMessage: Boolean,
248+ val fileUri: String?
248249 )
249250
250251 data class AcceptOrRejectDiffPayload(
251252 val filepath: String,
252253 val streamId: String? = null
254+)
255+
256+data class ShowFilePayload(
257+ val filepath: String
253258 )
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 +4 −4
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.38",
5+ "version": "1.1.39",
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",
@@ -631,7 +631,7 @@
631631 "devDependencies": {
632632 "@biomejs/biome": "1.6.4",
633633 "@nestjs/common": "^11.0.16",
634- "@openapitools/openapi-generator-cli": "^2.5.2",
634+ "@openapitools/openapi-generator-cli": "^2.20.0",
635635 "@types/chai": "^5.0.1",
636636 "@types/cors": "^2.8.17",
637637 "@types/express": "^4.17.21",
@@ -661,7 +661,7 @@
661661 },
662662 "dependencies": {
663663 "@continuedev/config-types": "^1.0.14",
664- "@continuedev/fetch": "^1.0.3",
664+ "@continuedev/fetch": "^1.0.10",
665665 "@electron/rebuild": "^3.2.10",
666666 "@reduxjs/toolkit": "^1.9.3",
667667 "@types/node-fetch": "^2.6.11",
modified extensions/vscode/src/commands.ts +14 −4
@@ -97,6 +97,7 @@
9797 action: "accept" | "reject",
9898 sidebar: ContinueGUIWebviewViewProvider,
9999 ide: VsCodeIde,
100+ core: Core,
100101 verticalDiffManager: VerticalDiffManager,
101102 newFileUri?: string,
102103 streamId?: string,
@@ -121,6 +122,9 @@
121122
122123 // Clear vertical diffs depending on action
123124 verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
125+ if (action === "reject") {
126+ core.invoke("cancelApply", undefined);
127+ }
124128
125129 if (streamId) {
126130 const fileContent = await ide.readFile(newOrCurrentUri);
@@ -236,18 +240,20 @@
236240 "accept",
237241 sidebar,
238242 ide,
243+ core,
239244 verticalDiffManager,
240245 newFileUri,
241246 streamId,
242247 ),
243248
244- "continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
249+ "continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
245250 processDiff(
246251 "reject",
247252 sidebar,
248253 ide,
254+ core,
249255 verticalDiffManager,
250- newFilepath,
256+ newFileUri,
251257 streamId,
252258 ),
253259 "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
@@ -573,11 +579,15 @@
573579 await addEntireFileToContext(
574580 vscode.Uri.parse(fileUri),
575581 sidebar.webviewProtocol,
576- ide.ideUtils
582+ ide.ideUtils,
577583 );
578584 }
579585 } else {
580- await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
586+ await addEntireFileToContext(
587+ uri,
588+ sidebar.webviewProtocol,
589+ ide.ideUtils,
590+ );
581591 }
582592 }
583593 },
modified extensions/vscode/src/diff/vertical/manager.ts +3 −4
@@ -1,5 +1,4 @@
11 import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
2-import { ConfigHandler } from "core/config/ConfigHandler";
32 import { streamDiffLines } from "core/edit/streamDiffLines";
43 import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
54 import { getMarkdownLanguageTagForFile } from "core/util";
@@ -31,7 +30,6 @@
3130 logDiffs: DiffLine[] | undefined;
3231
3332 constructor(
34- private readonly configHandler: ConfigHandler,
3533 private readonly webviewProtocol: VsCodeWebviewProtocol,
3634 private readonly editDecorationManager: EditDecorationManager,
3735 ) {
@@ -43,12 +41,12 @@
4341 startLine: number,
4442 endLine: number,
4543 options: VerticalDiffHandlerOptions,
46- ) {
44+ ): VerticalDiffHandler | undefined {
4745 if (this.fileUriToHandler.has(fileUri)) {
4846 this.fileUriToHandler.get(fileUri)?.clear(false);
4947 this.fileUriToHandler.delete(fileUri);
5048 }
51- const editor = vscode.window.activeTextEditor; // TODO
49+ const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
5250 if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
5351 const handler = new VerticalDiffHandler(
5452 startLine,
@@ -453,6 +451,7 @@
453451 language: getMarkdownLanguageTagForFile(fileUri),
454452 onlyOneInsertion: !!onlyOneInsertion,
455453 overridePrompt,
454+ abortControllerId: fileUri,
456455 });
457456
458457 for await (const line of stream) {
modified extensions/vscode/src/extension/VsCodeExtension.ts +0 −1
@@ -130,7 +130,6 @@
130130 this.configHandler.loadConfig();
131131
132132 this.verticalDiffManager = new VerticalDiffManager(
133- this.configHandler,
134133 this.sidebar.webviewProtocol,
135134 this.editDecorationManager,
136135 );
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 +35 −50
@@ -1,5 +1,5 @@
11 import { XMarkIcon } from "@heroicons/react/24/outline";
2-import { useCallback, useEffect } from "react";
2+import React, { useCallback, useEffect } from "react";
33 import { useDispatch, useSelector } from "react-redux";
44 import styled from "styled-components";
55 import { defaultBorderRadius } from "..";
@@ -13,16 +13,30 @@
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;
38+ max-height: 100px;
39+ overflow: auto;
2640
2741 /* Hide scrollbar but keep functionality */
2842 scrollbar-width: none;
@@ -41,24 +55,18 @@
4155 max-width: 150px;
4256 height: 25px;
4357 background-color: ${(props) =>
44- props.isActive
45- ? "var(--vscode-tab-activeBackground)"
46- : "var(--vscode-tab-inactiveBackground)"};
58+ props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar};
4759 color: ${(props) =>
48- props.isActive
49- ? "var(--vscode-tab-activeForeground)"
50- : "var(--vscode-tab-inactiveForeground)"};
60+ props.isActive ? tabSelectedForegroundVar : tabForegroundVar};
5161 cursor: pointer;
52- border: 1px solid var(--vscode-tab-border);
62+ border: 1px solid ${tabBorderVar};
5363 border-bottom: ${(props) =>
54- props.isActive ? "none" : `1px solid var(--vscode-tab-border)`};
64+ props.isActive ? "none" : `1px solid ${tabBorderVar}`};
5565 user-select: none;
5666 position: relative;
5767 transition: background-color 0.2s;
5868 border-top: ${(props) =>
59- props.isActive
60- ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)`
61- : `1px solid var(--vscode-tab-border)`};
69+ props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`};
6270 &:first-child {
6371 border-left: none;
6472 }
@@ -68,13 +76,9 @@
6876
6977 &:hover {
7078 background-color: ${(props) =>
71- props.isActive
72- ? "var(--vscode-tab-activeBackground)"
73- : "var(--vscode-tab-hoverBackground)"};
79+ props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar};
7480 color: ${(props) =>
75- props.isActive
76- ? "var(--vscode-tab-activeForeground)"
77- : "var(--vscode-tab-hoverForeground)"};
81+ props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar};
7882 }
7983 `;
8084
@@ -104,7 +108,7 @@
104108
105109 &:hover {
106110 opacity: 1;
107- background-color: var(--vscode-tab-hoverBackground);
111+ background-color: ${tabHoverBackgroundVar};
108112 }
109113
110114 ${Tab}:hover & {
@@ -119,33 +123,12 @@
119123 const TabBarSpace = styled.div`
120124 flex: 1;
121125 display: flex;
122- border-bottom: 1px solid var(--vscode-tab-border);
123- background-color: var(--vscode-tab-inactiveBackground);
126+ border-bottom: 1px solid ${tabBorderVar};
127+ background-color: ${tabBackgroundVar};
124128 `;
125129
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- }
144-`;
145-
146-export function TabBar() {
130+export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
147131 const dispatch = useDispatch<AppDispatch>();
148- const currentSession = useSelector((state: RootState) => state.session);
149132 const currentSessionId = useSelector((state: RootState) => state.session.id);
150133 const currentSessionTitle = useSelector(
151134 (state: RootState) => state.session.title,
@@ -160,7 +143,6 @@
160143 return Date.now().toString(36) + Math.random().toString(36).substring(2);
161144 }, []);
162145
163- // Handle session changes
164146 useEffect(() => {
165147 if (!currentSessionId) return;
166148
@@ -243,10 +225,13 @@
243225 }
244226 };
245227
246- return tabs.length === 1 ? (
247- <></>
248- ) : (
249- <TabBarContainer>
228+ return (
229+ <TabBarContainer
230+ ref={ref}
231+ style={{
232+ display: tabs.length === 1 ? "none" : "flex",
233+ }}
234+ >
250235 {tabs.map((tab) => (
251236 <Tab
252237 key={tab.id}
@@ -272,4 +257,4 @@
272257 </TabBarSpace>
273258 </TabBarContainer>
274259 );
275-}
260+});
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 +126 −292
@@ -13,35 +13,24 @@
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
1515 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
16-import { useAppSelector } from "../../redux/hooks";
17-
18-interface SearchMatch {
19- index: number;
20- textNode: Text;
21- overlayRectangle: Rectangle;
22-}
23-
24-type ScrollToMatchOption = "closest" | "first" | "none";
25-
26-const SEARCH_DEBOUNCE = 300;
27-const RESIZE_DEBOUNCE = 200;
28-
29-interface Rectangle {
30- top: number;
31- left: number;
32- width: number;
33- height: number;
34-}
35-
36-interface HighlightOverlayProps extends Rectangle {
16+import {
17+ Rectangle,
18+ SearchMatch,
19+ searchWithinContainer,
20+} from "./findWidgetSearch";
21+import useDebounceValue from "./useDebounce";
22+import { useElementSize } from "./useElementSize";
23+
24+interface HighlightOverlayProps {
25+ rectangle: Rectangle;
3726 isCurrent: boolean;
3827 }
3928
4029 const HighlightOverlay = (props: HighlightOverlayProps) => {
41- const { isCurrent, top, left, width, height } = props;
30+ const { top, left, width, height } = props.rectangle;
4231 return (
4332 <div
44- className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work
33+ className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
4534 key={`highlight-${top}-${left}`}
4635 style={{
4736 position: "absolute",
@@ -56,6 +45,8 @@
5645 );
5746 };
5847
48+type ScrollToMatchOption = "closest" | "first" | "none";
49+
5950 /*
6051 useFindWidget takes a container ref and returns
6152 1. A widget that can be placed anywhere to search the contents of that container
@@ -64,18 +55,22 @@
6455
6556 Container must have relative positioning
6657 */
67-export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
58+export const useFindWidget = (
59+ searchRef: RefObject<HTMLDivElement>,
60+ headerRef: RefObject<HTMLDivElement>,
61+ disabled: boolean,
62+) => {
6863 // Search input, debounced
69- const [input, setInput] = useState<string>("");
70- const debouncedInput = useRef<string>("");
7164 const inputRef = useRef<HTMLInputElement>(null);
65+ const [currentValue, setCurrentValue] = useState<string>("");
66+ const searchTerm = useDebounceValue(currentValue, 300);
7267
7368 // Widget open/closed state
7469 const [open, setOpen] = useState<boolean>(false);
7570 const openWidget = useCallback(() => {
7671 setOpen(true);
7772 inputRef?.current?.select();
78- }, [setOpen, inputRef]);
73+ }, [inputRef]);
7974
8075 // Search settings and results
8176 const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
@@ -97,7 +92,7 @@
9792 behavior: "smooth",
9893 });
9994 },
100- [searchRef.current],
95+ [searchRef],
10196 );
10297
10398 const nextMatch = useCallback(() => {
@@ -143,327 +138,166 @@
143138 }, [inputRef, matches, nextMatch]);
144139
145140 // Handle container resize changes - highlight positions must adjust
146- const [isResizing, setIsResizing] = useState(false);
147- useEffect(() => {
148- let timeoutId: NodeJS.Timeout | null = null;
149- if (!searchRef?.current) return;
150-
151- const resizeObserver = new ResizeObserver((entries) => {
152- if (timeoutId) {
153- clearTimeout(timeoutId);
154- }
155- setIsResizing(true);
156- timeoutId = setTimeout(() => {
157- setIsResizing(false);
158- }, RESIZE_DEBOUNCE);
159- });
160-
161- resizeObserver.observe(searchRef.current);
162- return () => {
163- if (timeoutId) {
164- clearTimeout(timeoutId);
165- }
166- if (searchRef.current) resizeObserver.unobserve(searchRef.current);
167- };
168- }, [searchRef.current]);
141+ const { clientHeight: headerHeight, isResizing: headerResizing } =
142+ useElementSize(headerRef);
143+ const { isResizing: containerResizing } = useElementSize(searchRef);
144+ const isResizing = useMemo(() => {
145+ return containerResizing || headerResizing;
146+ }, [containerResizing, headerResizing]);
169147
170148 // Main function for finding matches and generating highlight overlays
171149 const refreshSearch = useCallback(
172- (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
173- if (clearFirst) setMatches([]);
174-
175- const searchContainer = searchRef.current;
176-
177- const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
178- if (!searchContainer || !_query) {
179- setMatches([]);
180- return;
181- }
182- const query = caseSensitive ? _query : _query.toLowerCase();
183-
184- // First grab all text nodes
185- // Skips any elements with the "find-widget-skip" class
186- const textNodes: Text[] = [];
187- const walker = document.createTreeWalker(
188- searchRef.current,
189- NodeFilter.SHOW_ALL,
150+ (scrollTo: ScrollToMatchOption = "none") => {
151+ const { results, closestToMiddle } = searchWithinContainer(
152+ searchRef,
153+ searchTerm,
190154 {
191- acceptNode: (node) => {
192- if (node.nodeType === Node.ELEMENT_NODE) {
193- if ((node as Element).classList.contains("find-widget-skip"))
194- return NodeFilter.FILTER_REJECT;
195- return NodeFilter.FILTER_ACCEPT;
196- } else if (node.nodeType === Node.TEXT_NODE) {
197- if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
198- const nodeValue = caseSensitive
199- ? node.nodeValue
200- : node.nodeValue.toLowerCase();
201- if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
202- }
203- return NodeFilter.FILTER_REJECT;
204- },
155+ caseSensitive,
156+ useRegex,
157+ offsetHeight: headerHeight,
205158 },
206159 );
207-
208- while (walker.nextNode()) {
209- if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
210- textNodes.push(walker.currentNode as Text);
211- }
212-
213- // Now walk through each node match and extract search results
214- // One node can have several matches
215- const newMatches: SearchMatch[] = [];
216- textNodes.forEach((textNode, idx) => {
217- // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
218- const highlightFullLine =
219- textNode.parentElement?.className.includes("hljs");
220-
221- let nodeTextValue = caseSensitive
222- ? textNode.nodeValue
223- : textNode.nodeValue.toLowerCase();
224- let startIndex = 0;
225- while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
226- // Create a range to measure the size and position of the match
227- const range = document.createRange();
228- range.setStart(textNode, startIndex);
229- const endIndex = startIndex + query.length;
230- range.setEnd(textNode, endIndex);
231- const rect = range.getBoundingClientRect();
232- range.detach();
233- startIndex = endIndex;
234-
235- const top =
236- rect.top + searchContainer.clientTop + searchContainer.scrollTop;
237- const left =
238- rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
239-
240- // Build a match result and push to matches
241- const newMatch: SearchMatch = {
242- index: 0, // will set later
243- textNode,
244- overlayRectangle: {
245- top,
246- left: highlightFullLine ? 2 : left,
247- width: highlightFullLine
248- ? searchContainer.clientWidth - 4
249- : rect.width, // equivalent of adding 2 px x padding
250- height: rect.height,
251- },
252- };
253- newMatches.push(newMatch);
254-
255- if (highlightFullLine) {
256- break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
257- }
258- }
259- });
260-
261- // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
262- // Filter them out by using the overlay rectangle as a hash key
263- const matchHash = Object.fromEntries(
264- newMatches.map((match) => [
265- JSON.stringify(match.overlayRectangle),
266- match,
267- ]),
268- );
269- const filteredMatches = Object.values(matchHash).map((match, index) => ({
270- ...match,
271- index,
272- }));
273-
160+ setMatches(results);
274161 // Find match closest to the middle of the view
275- const verticalMiddle =
276- searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
277- let closestDist = Infinity;
278- let closestMatchToMiddle: SearchMatch | null = null;
279- filteredMatches.forEach((match) => {
280- const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
281- if (dist < closestDist) {
282- closestDist = dist;
283- closestMatchToMiddle = match;
284- }
285- });
286-
287- // Update matches and scroll to the closest or first match
288- setMatches(filteredMatches);
289- if (query.length > 1 && filteredMatches.length) {
162+ if (searchTerm.length > 1 && results.length) {
290163 if (scrollTo === "first") {
291- scrollToMatch(filteredMatches[0]);
164+ scrollToMatch(results[0]);
292165 }
293166 if (scrollTo === "closest") {
294- if (closestMatchToMiddle) {
295- scrollToMatch(closestMatchToMiddle);
167+ if (closestToMiddle) {
168+ scrollToMatch(closestToMiddle);
296169 }
297170 }
298171 if (scrollTo === "none") {
299- if (closestMatchToMiddle) {
300- setCurrentMatch(closestMatchToMiddle);
172+ if (closestToMiddle) {
173+ setCurrentMatch(closestToMiddle);
301174 } else {
302- setCurrentMatch(filteredMatches[0]);
175+ setCurrentMatch(results[0]);
303176 }
304177 }
305178 }
306179 },
307- [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex],
180+ [
181+ searchTerm,
182+ caseSensitive,
183+ useRegex,
184+ searchRef,
185+ headerHeight,
186+ scrollToMatch,
187+ ],
308188 );
309189
310190 // Triggers that should cause immediate refresh of results to closest search value:
311- // Input change (debounced) and window click
312- const lastUpdateRef = useRef(0);
313191 useEffect(() => {
314- const debounce = () => {
315- debouncedInput.current = input;
316- lastUpdateRef.current = Date.now();
317- refreshSearch("closest");
318- };
319- const timeSinceLastUpdate = Date.now() - lastUpdateRef.current;
320- if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) {
321- debounce();
192+ if (disabled || isResizing || !open) {
193+ setMatches([]);
322194 } else {
323- const handler = setTimeout(() => {
324- debounce();
325- }, SEARCH_DEBOUNCE - timeSinceLastUpdate);
326- return () => {
327- clearTimeout(handler);
328- };
195+ refreshSearch("closest");
329196 }
330- }, [refreshSearch, input]);
197+ }, [refreshSearch, open, disabled, isResizing]);
331198
332- // Could consider doing any window click but I only handled search div here
333- // Since usually only clicks in search div will cause content changes in search div
199+ // Clicks in search div can cause content changes that for some reason don't trigger resize
200+ // Refresh clicking within container
334201 useEffect(() => {
335202 const searchContainer = searchRef.current;
336203 if (!open || !searchContainer) return;
337204 const handleSearchRefClick = () => {
338- refreshSearch("none");
205+ setTimeout(() => {
206+ refreshSearch("none");
207+ }, 150);
339208 };
340209 searchContainer.addEventListener("click", handleSearchRefClick);
341210 return () => {
342211 searchContainer.removeEventListener("click", handleSearchRefClick);
343212 };
344- }, [searchRef.current, refreshSearch, open]);
345-
346- // Triggers that should cause results to temporarily disappear and then reload
347- // Active = LLM is generating, etc.
348- const active = useAppSelector((state) => state.session.isStreaming);
349-
350- useEffect(() => {
351- if (active || isResizing) setMatches([]);
352- else refreshSearch("none");
353- }, [refreshSearch, active]);
354-
355- useEffect(() => {
356- if (!open) setMatches([]);
357- else refreshSearch("closest");
358- }, [refreshSearch, open]);
359-
360- useEffect(() => {
361- refreshSearch("closest");
362- }, [refreshSearch, caseSensitive, useRegex]);
213+ }, [searchRef, refreshSearch, open]);
363214
364215 // Find widget component
365- const widget = useMemo(() => {
366- return (
367- <div
368- className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
369- >
370- <Input
371- disabled={active}
372- type="text"
373- ref={inputRef}
374- value={input}
375- onChange={(e) => {
376- setInput(e.target.value);
377- }}
378- placeholder="Search..."
379- />
380- <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
381- {matches.length === 0
382- ? "No results"
383- : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
384- </p>
385- <div className="hidden flex-row gap-0.5 sm:flex">
386- <HeaderButtonWithToolTip
387- tooltipPlacement="top-end"
388- text={"Previous Match"}
389- onClick={(e) => {
390- e.stopPropagation();
391- previousMatch();
392- }}
393- className="h-4 w-4 focus:ring"
394- disabled={matches.length < 2 || active}
395- >
396- <ArrowUpIcon className="h-4 w-4" />
397- </HeaderButtonWithToolTip>
398- <HeaderButtonWithToolTip
399- tooltipPlacement="top-end"
400- text={"Next Match"}
401- onClick={(e) => {
402- e.stopPropagation();
403- nextMatch();
404- }}
405- className="h-4 w-4 focus:ring"
406- disabled={matches.length < 2 || active}
407- >
408- <ArrowDownIcon className="h-4 w-4" />
409- </HeaderButtonWithToolTip>
410- </div>
216+ const widget = (
217+ <div
218+ className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
219+ >
220+ <Input
221+ disabled={disabled}
222+ type="text"
223+ ref={inputRef}
224+ value={currentValue}
225+ onChange={(e) => {
226+ setCurrentValue(e.target.value);
227+ }}
228+ placeholder="Search..."
229+ />
230+ <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
231+ {matches.length === 0
232+ ? "No results"
233+ : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
234+ </p>
235+ <div className="hidden flex-row gap-0.5 sm:flex">
411236 <HeaderButtonWithToolTip
412- disabled={active}
413- inverted={caseSensitive}
414237 tooltipPlacement="top-end"
415- text={
416- caseSensitive
417- ? "Turn off case sensitivity"
418- : "Turn on case sensitivity"
419- }
238+ text={"Previous Match"}
420239 onClick={(e) => {
421240 e.stopPropagation();
422- setCaseSensitive((curr) => !curr);
241+ previousMatch();
423242 }}
424- className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
243+ className="h-4 w-4 focus:ring"
244+ disabled={matches.length < 2 || disabled}
425245 >
426- Aa
246+ <ArrowUpIcon className="h-4 w-4" />
427247 </HeaderButtonWithToolTip>
428- {/* TODO - add useRegex functionality */}
429- <HeaderButton
430- inverted={false}
431- onClick={() => setOpen(false)}
432- className="focus:ring"
248+ <HeaderButtonWithToolTip
249+ tooltipPlacement="top-end"
250+ text={"Next Match"}
251+ onClick={(e) => {
252+ e.stopPropagation();
253+ nextMatch();
254+ }}
255+ className="h-4 w-4 focus:ring"
256+ disabled={matches.length < 2 || disabled}
433257 >
434- <XMarkIcon className="h-4 w-4" />
435- </HeaderButton>
258+ <ArrowDownIcon className="h-4 w-4" />
259+ </HeaderButtonWithToolTip>
436260 </div>
437- );
438- }, [
439- open,
440- input,
441- inputRef,
442- caseSensitive,
443- matches,
444- currentMatch,
445- previousMatch,
446- nextMatch,
447- ]);
261+ <HeaderButtonWithToolTip
262+ disabled={disabled}
263+ inverted={caseSensitive}
264+ tooltipPlacement="top-end"
265+ text={
266+ caseSensitive
267+ ? "Turn off case sensitivity"
268+ : "Turn on case sensitivity"
269+ }
270+ onClick={(e) => {
271+ e.stopPropagation();
272+ setCaseSensitive((curr) => !curr);
273+ }}
274+ className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
275+ >
276+ Aa
277+ </HeaderButtonWithToolTip>
278+ {/* TODO - add useRegex functionality */}
279+ <HeaderButton
280+ inverted={false}
281+ onClick={() => setOpen(false)}
282+ className="focus:ring"
283+ >
284+ <XMarkIcon className="h-4 w-4" />
285+ </HeaderButton>
286+ </div>
287+ );
448288
449289 // Generate the highlight overlay elements
450290 const highlights = useMemo(() => {
451291 return matches.map((match) => (
452292 <HighlightOverlay
453- {...match.overlayRectangle}
293+ rectangle={match.overlayRectangle}
454294 isCurrent={currentMatch?.index === match.index}
455295 />
456296 ));
457297 }, [matches, currentMatch]);
458298
459299 return {
460- matches,
461300 highlights,
462- inputRef,
463- input: debouncedInput,
464- setInput,
465- open,
466- setOpen,
467301 widget,
468302 };
469303 };
added gui/src/components/find/findWidgetSearch.ts +146 −0
@@ -0,0 +1,146 @@
1+export interface Rectangle {
2+ top: number;
3+ left: number;
4+ width: number;
5+ height: number;
6+}
7+
8+export interface SearchMatch {
9+ index: number;
10+ textNode: Text;
11+ overlayRectangle: Rectangle;
12+}
13+
14+interface SearchOptions {
15+ caseSensitive: boolean;
16+ useRegex: boolean;
17+ offsetHeight: number;
18+}
19+
20+export const searchWithinContainer = (
21+ containerRef: React.RefObject<HTMLDivElement>,
22+ searchQuery: string,
23+ options: SearchOptions,
24+): {
25+ results: SearchMatch[];
26+ closestToMiddle: SearchMatch | null;
27+} => {
28+ const searchContainer = containerRef.current;
29+
30+ if (!searchContainer || !searchQuery) {
31+ return {
32+ results: [],
33+ closestToMiddle: null,
34+ };
35+ }
36+ const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase();
37+
38+ // First grab all text nodes
39+ // Skips any elements with the "find-widget-skip" class
40+ const textNodes: Text[] = [];
41+ const walker = document.createTreeWalker(
42+ searchContainer,
43+ NodeFilter.SHOW_ALL,
44+ {
45+ acceptNode: (node) => {
46+ if (node.nodeType === Node.ELEMENT_NODE) {
47+ if ((node as Element).classList.contains("find-widget-skip"))
48+ return NodeFilter.FILTER_REJECT;
49+ return NodeFilter.FILTER_ACCEPT;
50+ } else if (node.nodeType === Node.TEXT_NODE) {
51+ if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
52+ const nodeValue = options.caseSensitive
53+ ? node.nodeValue
54+ : node.nodeValue.toLowerCase();
55+ if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
56+ }
57+ return NodeFilter.FILTER_REJECT;
58+ },
59+ },
60+ );
61+
62+ while (walker.nextNode()) {
63+ if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
64+ textNodes.push(walker.currentNode as Text);
65+ }
66+
67+ // Now walk through each node match and extract search results
68+ // One node can have several matches
69+ const newMatches: SearchMatch[] = [];
70+ textNodes.forEach((textNode, idx) => {
71+ // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
72+ const highlightFullLine =
73+ textNode.parentElement?.className.includes("hljs");
74+
75+ let nodeTextValue = options.caseSensitive
76+ ? textNode.nodeValue
77+ : textNode.nodeValue.toLowerCase();
78+ let startIndex = 0;
79+ while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
80+ // Create a range to measure the size and position of the match
81+ const range = document.createRange();
82+ range.setStart(textNode, startIndex);
83+ const endIndex = startIndex + query.length;
84+ range.setEnd(textNode, endIndex);
85+ const rect = range.getBoundingClientRect();
86+ range.detach();
87+ startIndex = endIndex;
88+
89+ const top =
90+ rect.top +
91+ searchContainer.clientTop +
92+ searchContainer.scrollTop -
93+ options.offsetHeight;
94+
95+ const left =
96+ rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
97+
98+ // Build a match result and push to matches
99+ const newMatch: SearchMatch = {
100+ index: 0, // will set later
101+ textNode,
102+ overlayRectangle: {
103+ top,
104+ left: highlightFullLine ? 2 : left,
105+ width: highlightFullLine
106+ ? searchContainer.clientWidth - 4
107+ : rect.width, // equivalent of adding 2 px x padding
108+ height: rect.height,
109+ },
110+ };
111+ newMatches.push(newMatch);
112+
113+ if (highlightFullLine) {
114+ break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
115+ }
116+ }
117+ });
118+
119+ // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
120+ // Filter them out by using the overlay rectangle as a hash key
121+ const matchHash = Object.fromEntries(
122+ newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]),
123+ );
124+ const filteredMatches = Object.values(matchHash).map((match, index) => ({
125+ ...match,
126+ index,
127+ }));
128+
129+ // Find the match closest to the vertical middle of the container
130+ const verticalMiddle =
131+ searchContainer.scrollTop + searchContainer.clientHeight / 2;
132+ let closestDist = Infinity;
133+ let closestMatchToMiddle: SearchMatch | null = null;
134+ filteredMatches.forEach((match) => {
135+ const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
136+ if (dist < closestDist) {
137+ closestDist = dist;
138+ closestMatchToMiddle = match;
139+ }
140+ });
141+
142+ return {
143+ results: filteredMatches,
144+ closestToMiddle: closestMatchToMiddle,
145+ };
146+};
added gui/src/components/find/useDebounce.ts +19 −0
@@ -0,0 +1,19 @@
1+import { useEffect, useState } from "react";
2+
3+function useDebounceValue<T>(value: T, delay: number = 500): T {
4+ const [debouncedValue, setDebouncedValue] = useState<T>(value);
5+
6+ useEffect(() => {
7+ const timer = setTimeout(() => {
8+ setDebouncedValue(value);
9+ }, delay);
10+
11+ return () => {
12+ clearTimeout(timer);
13+ };
14+ }, [value, delay]);
15+
16+ return debouncedValue;
17+}
18+
19+export default useDebounceValue;
added gui/src/components/find/useElementSize.ts +81 −0
@@ -0,0 +1,81 @@
1+import { RefObject, useCallback, useEffect, useState } from "react";
2+
3+interface ElementSize {
4+ clientWidth: number;
5+ clientHeight: number;
6+ scrollWidth: number;
7+ scrollHeight: number;
8+ isResizing: boolean;
9+}
10+
11+interface UseElementSizeOptions {
12+ debounceMs?: number;
13+}
14+
15+export const useElementSize = (
16+ ref: RefObject<HTMLElement>,
17+ debounceMs = 250,
18+): ElementSize => {
19+ const [size, setSize] = useState<ElementSize>({
20+ clientWidth: 0,
21+ clientHeight: 0,
22+ scrollWidth: 0,
23+ scrollHeight: 0,
24+ isResizing: false,
25+ });
26+
27+ // Debounced update function
28+ const debouncedSetSize = useCallback(
29+ (measurements: Omit<ElementSize, "isResizing">) => {
30+ let timeoutId: NodeJS.Timeout;
31+
32+ setSize((prev) => ({ ...prev, isResizing: true }));
33+
34+ timeoutId = setTimeout(() => {
35+ setSize({
36+ ...measurements,
37+ isResizing: false,
38+ });
39+ }, debounceMs);
40+
41+ return () => clearTimeout(timeoutId);
42+ },
43+ [debounceMs],
44+ );
45+
46+ useEffect(() => {
47+ if (!ref.current) return;
48+
49+ const updateSize = () => {
50+ const element = ref.current;
51+ if (!element) return;
52+
53+ const measurements = {
54+ clientWidth: element.clientWidth,
55+ clientHeight: element.clientHeight,
56+ scrollWidth: element.scrollWidth,
57+ scrollHeight: element.scrollHeight,
58+ };
59+
60+ debouncedSetSize(measurements);
61+ };
62+
63+ // Create ResizeObserver instance
64+ const resizeObserver = new ResizeObserver(() => {
65+ updateSize();
66+ });
67+
68+ // Start observing the element
69+ resizeObserver.observe(ref.current);
70+
71+ // Initial size calculation
72+ updateSize();
73+
74+ // Cleanup
75+ return () => {
76+ resizeObserver.disconnect();
77+ };
78+ }, [ref, debouncedSetSize]);
79+
80+ return size;
81+};
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/LumpToolbar.tsx +36 −1
@@ -1,4 +1,4 @@
1-import { useContext, useEffect } from "react";
1+import { useContext, useEffect, useMemo } from "react";
22 import { useSelector } from "react-redux";
33 import styled from "styled-components";
44 import { AnimatedEllipsis } from "../..";
@@ -40,12 +40,27 @@
4040 );
4141 }
4242
43+function ApplyingIndicator() {
44+ return (
45+ <div className="text-xs text-gray-400">
46+ <span>Applying</span>
47+ <AnimatedEllipsis />
48+ </div>
49+ );
50+}
51+
4352 export function LumpToolbar() {
4453 const dispatch = useAppDispatch();
4554 const ideMessenger = useContext(IdeMessengerContext);
4655 const ttsActive = useAppSelector((state) => state.ui.ttsActive);
4756 const isStreaming = useAppSelector((state) => state.session.isStreaming);
4857 const jetbrains = isJetBrains();
58+ const applyStates = useAppSelector(
59+ (store) => store.session.codeBlockApplyStates.states,
60+ );
61+ const isApplying = useMemo(() => {
62+ return applyStates.find((state) => state.status === "streaming");
63+ }, [applyStates]);
4964
5065 const toolCallState = useSelector(selectCurrentToolCall);
5166
@@ -89,6 +104,26 @@
89104 );
90105 }
91106
107+ if (isApplying) {
108+ return (
109+ <Container>
110+ <ApplyingIndicator />
111+ <StopButton
112+ className="text-gray-400"
113+ onClick={() => {
114+ // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
115+ // Apply is prioritized because it can be more catastrophic
116+ // Intentional to be more WYSIWYG for now
117+ ideMessenger.post("cancelApply", undefined);
118+ }}
119+ >
120+ {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
121+ {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
122+ </StopButton>
123+ </Container>
124+ );
125+ }
126+
92127 if (isStreaming) {
93128 return (
94129 <Container>
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/pages/gui/Chat.tsx +11 −6
@@ -44,16 +44,17 @@
4444 setDialogMessage,
4545 setShowDialog,
4646 } from "../../redux/slices/uiSlice";
47+import { streamResponseThunk } from "../../redux/thunks";
4748 import { cancelStream } from "../../redux/thunks/cancelStream";
4849 import { streamEditThunk } from "../../redux/thunks/editMode";
4950 import { loadLastSession } from "../../redux/thunks/session";
50-import { streamResponseThunk } from "../../redux/thunks";
5151 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
5252 import {
5353 FREE_TRIAL_LIMIT_REQUESTS,
5454 incrementFreeTrialCount,
5555 } from "../../util/freeTrial";
5656
57+import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
5758 import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
5859 import EditModeDetails from "../../components/mainInput/EditModeDetails";
5960 import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
@@ -61,7 +62,6 @@
6162 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
6263 import { ToolCallDiv } from "./ToolCallDiv";
6364 import { useAutoScroll } from "./useAutoScroll";
64-import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
6565
6666 const StepsDiv = styled.div`
6767 position: relative;
@@ -113,6 +113,7 @@
113113 const [stepsOpen] = useState<(boolean | undefined)[]>([]);
114114 const mainTextInputRef = useRef<HTMLInputElement>(null);
115115 const stepsDivRef = useRef<HTMLDivElement>(null);
116+ const tabsRef = useRef<HTMLDivElement>(null);
116117 const history = useAppSelector((state) => state.session.history);
117118 const showChatScrollbar = useAppSelector(
118119 (state) => state.config.config.ui?.showChatScrollbar,
@@ -143,6 +144,7 @@
143144 !e.shiftKey
144145 ) {
145146 dispatch(cancelStream());
147+ ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
146148 }
147149 };
148150 window.addEventListener("keydown", listener);
@@ -152,7 +154,11 @@
152154 };
153155 }, [isStreaming, jetbrains]);
154156
155- const { widget, highlights } = useFindWidget(stepsDivRef);
157+ const { widget, highlights } = useFindWidget(
158+ stepsDivRef,
159+ tabsRef,
160+ isStreaming,
161+ );
156162
157163 const currentToolCallApplyState = useAppSelector(
158164 selectCurrentToolCallApplyState,
@@ -286,13 +292,12 @@
286292
287293 return (
288294 <>
295+ {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />}
289296 {widget}
290297
291- {!!showSessionTabs && mode !== "edit" && <TabBar />}
292-
293298 <StepsDiv
294299 ref={stepsDivRef}
295- className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
300+ className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
296301 >
297302 {highlights}
298303 {history.map((item, index: number) => (
modified gui/src/pages/gui/StreamError.tsx +86 −47
@@ -1,12 +1,15 @@
11 import {
22 ArrowTopRightOnSquareIcon,
3- Cog8ToothIcon,
3+ ClipboardIcon,
4+ Cog6ToothIcon,
5+ KeyIcon,
46 } from "@heroicons/react/24/outline";
57 import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
68 import { useContext, useMemo } from "react";
7-import { Button, SecondaryButton } from "../../components";
9+import { GhostButton, SecondaryButton } from "../../components";
810 import { DiscordIcon } from "../../components/svg/DiscordIcon";
911 import { GithubIcon } from "../../components/svg/GithubIcon";
12+import ToggleDiv from "../../components/ToggleDiv";
1013 import { useAuth } from "../../context/Auth";
1114 import { IdeMessengerContext } from "../../context/IdeMessenger";
1215 import { selectSelectedProfile } from "../../redux/";
@@ -48,11 +51,15 @@
4851 );
4952
5053 const handleRefreshProfiles = () => {
51- refreshProfiles();
54+ void refreshProfiles();
5255 dispatch(setShowDialog(false));
5356 dispatch(setDialogMessage(undefined));
5457 };
5558
59+ const copyErrorToClipboard = () => {
60+ void navigator.clipboard.writeText(parsedError);
61+ };
62+
5663 // Collect model information to display useful error info
5764 let modelTitle = "Chat model";
5865 let providerName = "the model provider";
@@ -99,30 +106,29 @@
99106 }
100107
101108 const checkKeysButton = apiKeyUrl ? (
102- <Button
103- className="cursor-pointer hover:underline"
109+ <GhostButton
110+ className="flex items-center"
104111 onClick={() => {
105112 ideMessenger.post("openUrl", apiKeyUrl!);
106113 }}
107114 >
108- Check keys/usage
109- </Button>
115+ <KeyIcon className="mr-1.5 h-3.5 w-3.5" />
116+ <span>View key</span>
117+ </GhostButton>
110118 ) : null;
111119
112120 const configButton = (
113- <SecondaryButton
114- className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70"
121+ <GhostButton
122+ className="flex items-center"
115123 onClick={() => {
116124 ideMessenger.post("config/openProfile", {
117125 profileId: undefined,
118126 });
119127 }}
120128 >
121- <div>
122- <Cog8ToothIcon className="h-4 w-4" />
123- </div>
124- <span>Open Assistant configuration</span>
125- </SecondaryButton>
129+ <Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
130+ <span>View config</span>
131+ </GhostButton>
126132 );
127133
128134 if (
@@ -131,7 +137,20 @@
131137 return <ModelsAddOnLimitDialog />;
132138 }
133139
134- let errorContent: React.ReactNode = <></>;
140+ let errorContent = (
141+ <div className="mb-3 mt-1">
142+ <div className="m-0 p-0">
143+ <p className="m-0 mb-2 p-0">
144+ There was an error handling the response from{" "}
145+ {selectedModel?.title || "the model"}.
146+ </p>
147+ <p className="m-0 p-0">
148+ Please try to submit your message again, and if the error persists,
149+ let us know by reporting the issue using the buttons below.
150+ </p>
151+ </div>
152+ </div>
153+ );
135154
136155 // Display components for specific errors
137156 if (statusCode === 429) {
@@ -141,7 +160,7 @@
141160 {`This might mean your ${modelTitle} usage has been rate limited
142161 by ${providerName}.`}
143162 </span>
144- <div className="flex flex-row flex-wrap gap-2">
163+ <div className="flex flex-row flex-wrap justify-start gap-3 py-4">
145164 {checkKeysButton}
146165 {configButton}
147166 </div>
@@ -230,51 +249,71 @@
230249 );
231250 }
232251
252+ console.log({ message });
253+
233254 return (
234- <div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}>
235- <p className="m-0 p-0 text-lg text-red-500">
236- {statusCode ? `Error (status code ${statusCode})` : "Error"}
237- </p>
238-
239- {message ? (
240- <div className="mt-2 flex flex-col gap-0 rounded-sm">
241- <code className="max-h-20 overflow-y-auto p-2 font-mono">
242- {parsedError}
243- </code>
244- <div
245- className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline"
246- onClick={() => {
247- ideMessenger.post("toggleDevTools", undefined);
248- }}
249- >
250- <span className="px-2">View Logs</span>
251- <ArrowTopRightOnSquareIcon className="h-4 w-4" />
252- </div>
255+ <div className="flex flex-col gap-4 px-3 pb-3 pt-3">
256+ {/* Concise error title */}
257+ <h3 className="text-error m-0 p-0 text-lg font-medium">
258+ Error handling model response
259+ </h3>
260+
261+ {errorContent}
262+
263+ {/* Expandable technical details using ToggleDiv */}
264+ {message && (
265+ <div className="mb-2">
266+ <ToggleDiv title="View error output" testId="error-output-toggle">
267+ <div className="flex flex-col gap-0 rounded-sm">
268+ <code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs">
269+ {parsedError}
270+ </code>
271+
272+ <div className="flex flex-row items-center justify-end gap-2 p-2">
273+ <GhostButton
274+ onClick={copyErrorToClipboard}
275+ className="flex items-center"
276+ >
277+ <ClipboardIcon className="mr-1.5 h-3.5 w-3.5" />
278+ <span>Copy output</span>
279+ </GhostButton>
280+
281+ <GhostButton
282+ onClick={() => {
283+ ideMessenger.post("toggleDevTools", undefined);
284+ }}
285+ className="flex items-center"
286+ >
287+ <ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" />
288+ <span className="text-xs">View Logs</span>
289+ </GhostButton>
290+ </div>
291+ </div>
292+ </ToggleDiv>
253293 </div>
254- ) : null}
255- <div className="mt-3">{errorContent}</div>
256-
257- <div className="mt-2 flex flex-col gap-1.5">
258- <span>Report this error:</span>
259- <div className="flex flex-row flex-wrap items-center gap-2">
260- <SecondaryButton
261- className="flex flex-row items-center gap-2 hover:opacity-70"
294+ )}
295+
296+ <div>
297+ <span className="text-base font-medium">Report this error</span>
298+ <div className="mt-2 flex flex-row flex-wrap items-center gap-2">
299+ <GhostButton
300+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
262301 onClick={() => {
263302 ideMessenger.post("openUrl", GITHUB_LINK);
264303 }}
265304 >
266305 <GithubIcon className="h-5 w-5" />
267306 <span className="xs:flex hidden">Github</span>
268- </SecondaryButton>
269- <SecondaryButton
270- className="flex flex-row items-center gap-2 hover:opacity-70"
307+ </GhostButton>
308+ <GhostButton
309+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
271310 onClick={() => {
272311 ideMessenger.post("openUrl", DISCORD_LINK);
273312 }}
274313 >
275314 <DiscordIcon className="h-5 w-5" />
276315 <span className="xs:flex hidden">Discord</span>
277- </SecondaryButton>
316+ </GhostButton>
278317 </div>
279318 </div>
280319 </div>
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/AdvancedPage.tsx +1 −4
@@ -13,10 +13,7 @@
1313 className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
1414 >
1515 <header className="mb-4 flex items-center justify-between border-b-2 pb-4">
16- I apologize, but there seems to be a misunderstanding. The user's
17- request doesn't appear to be related to rewriting the code section you
18- provided. The request mentions editing a readme.md file, which is not
19- part of the React component code you've shown.
16+ {" "}
2017 <button
2118 className="rounded bg-blue-500 px-4 py-2 text-white"
2219 onClick={toggleDarkMode}
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;
modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.87",
9+ "version": "1.0.88",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/config-yaml/src/__tests__/index.test.ts +5 −1
@@ -143,7 +143,7 @@
143143 );
144144
145145 // Test that packages were correctly unrolled and params replaced
146- expect(unrolledConfig.models?.length).toBe(3);
146+ expect(unrolledConfig.models?.length).toBe(4);
147147
148148 const openAiModel = unrolledConfig.models?.[0]!;
149149 expect(openAiModel.apiKey).toBe("sk-123");
@@ -163,6 +163,10 @@
163163 anthropicSecretLocation,
164164 );
165165
166+ const proxyOllamaModel = unrolledConfig.models?.[3]!;
167+ expect(proxyOllamaModel.provider).toBe('ollama')
168+ expect(proxyOllamaModel.defaultCompletionOptions?.stream).toBe(false);
169+
166170 expect(unrolledConfig.rules?.length).toBe(2);
167171 expect(unrolledConfig.docs?.[0]?.startUrl).toBe(
168172 "https://docs.python.org/release/3.13.1",
modified packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml +6 −0
@@ -27,3 +27,9 @@
2727 - uses: test-org/claude35sonnet
2828 with:
2929 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
30+
31+ - name: proxy-ollama
32+ provider: ollama
33+ model: llama3.1
34+ defaultCompletionOptions:
35+ stream: false
modified packages/config-yaml/src/load/clientRender.ts +1 −0
@@ -160,6 +160,7 @@
160160 apiKeyLocation: z.string().optional(),
161161 apiBase: z.string().optional(),
162162 orgScopeId: z.string().nullable(),
163+ env: z.record(z.string(), z.any()).optional(),
163164 });
164165
165166 export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;
modified packages/config-yaml/src/schemas/index.ts +6 −2
@@ -9,13 +9,16 @@
99 params: z.any().optional(),
1010 });
1111
12+// TODO: This should be a discriminated union by type
1213 const mcpServerSchema = z.object({
1314 name: z.string(),
14- command: z.string(),
15+ command: z.string().optional(),
16+ type: z.enum(["sse", "stdio"]).optional(),
17+ url: z.string().optional(),
1518 faviconUrl: z.string().optional(),
1619 args: z.array(z.string()).optional(),
1720 env: z.record(z.string()).optional(),
18- connectionTimeout: z.number().gt(0).optional()
21+ connectionTimeout: z.number().gt(0).optional(),
1922 });
2023
2124 export type MCPServer = z.infer<typeof mcpServerSchema>;
@@ -39,6 +42,7 @@
3942 const ruleObjectSchema = z.object({
4043 name: z.string(),
4144 rule: z.string(),
45+ description: z.string().optional(),
4246 globs: z.union([z.string(), z.array(z.string())]).optional(),
4347 });
4448 const ruleSchema = z.union([z.string(), ruleObjectSchema]);
modified packages/config-yaml/src/schemas/models.ts +2 −0
@@ -50,6 +50,7 @@
5050 reasoning: z.boolean().optional(),
5151 reasoningBudgetTokens: z.number().optional(),
5252 promptCaching: z.boolean().optional(),
53+ stream: z.boolean().optional()
5354 });
5455 export type CompletionOptions = z.infer<typeof completionOptionsSchema>;
5556
@@ -117,6 +118,7 @@
117118 model: z.string(),
118119 apiKey: z.string().optional(),
119120 apiBase: z.string().optional(),
121+ maxStopWords: z.number().optional(),
120122 roles: modelRolesSchema.array().optional(),
121123 capabilities: modelCapabilitySchema.array().optional(),
122124 defaultCompletionOptions: completionOptionsSchema.optional(),
added packages/fetch/.gitignore +1 −0
@@ -0,0 +1,1 @@
1+coverage/
No newline at the end of the file
added packages/fetch/jest.globals.d.ts +14 −0
@@ -0,0 +1,14 @@
1+// This file declares the Jest globals for TypeScript
2+import '@jest/globals';
3+
4+declare global {
5+ const describe: typeof import('@jest/globals').describe;
6+ const expect: typeof import('@jest/globals').expect;
7+ const it: typeof import('@jest/globals').it;
8+ const test: typeof import('@jest/globals').test;
9+ const beforeAll: typeof import('@jest/globals').beforeAll;
10+ const afterAll: typeof import('@jest/globals').afterAll;
11+ const beforeEach: typeof import('@jest/globals').beforeEach;
12+ const afterEach: typeof import('@jest/globals').afterEach;
13+ const jest: typeof import('@jest/globals').jest;
14+}
No newline at the end of the file
modified packages/fetch/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/fetch",
3- "version": "1.0.6",
3+ "version": "1.0.9",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/fetch",
9- "version": "1.0.6",
9+ "version": "1.0.9",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.5",
modified packages/fetch/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/fetch",
3- "version": "1.0.9",
3+ "version": "1.0.10",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/fetch/src/stream.test.ts +63 −3
@@ -1,6 +1,66 @@
1-// The parseDataLine function is not exported, so we need to import it
2-// indirectly by re-exporting it for testing purposes
3-import { parseDataLine } from "./stream.js";
1+import { Readable } from "stream";
2+import { parseDataLine, streamSse } from "./stream.js";
3+
4+function createMockResponse(sseLines: string[]): Response {
5+ // Create a Readable stream that emits the SSE lines
6+ const stream = new Readable({
7+ read() {
8+ for (const line of sseLines) {
9+ this.push(line + "\n\n");
10+ }
11+ this.push(null); // End of stream
12+ },
13+ }) as any;
14+
15+ // Minimal Response mock
16+ return {
17+ status: 200,
18+ body: stream,
19+ text: async () => "",
20+ } as unknown as Response;
21+}
22+
23+describe("streamSse", () => {
24+ it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25+ const sseLines = [
26+ 'data: {"foo": "bar"}',
27+ 'data: {"baz": 42}',
28+ "data:[DONE]",
29+ ];
30+ const response = createMockResponse(sseLines);
31+
32+ const results = [];
33+ for await (const data of streamSse(response)) {
34+ results.push(data);
35+ }
36+
37+ expect(results).toEqual([{ foo: "bar" }, { baz: 42 }]);
38+ });
39+
40+ it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
41+ const sseLines = [
42+ 'data: {"foo": "bar"}',
43+ 'data: {"baz": 42}',
44+ "data: [DONE]",
45+ ];
46+ const response = createMockResponse(sseLines);
47+
48+ const results = [];
49+ for await (const data of streamSse(response)) {
50+ results.push(data);
51+ }
52+
53+ expect(results).toEqual([{ foo: "bar" }, { baz: 42 }]);
54+ });
55+
56+ it("throws on malformed JSON", async () => {
57+ const sseLines = ['data: {"foo": "bar"', "data:[DONE]"];
58+ const response = createMockResponse(sseLines);
59+
60+ const iterator = streamSse(response)[Symbol.asyncIterator]();
61+ await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
62+ });
63+});
464
565 describe("parseDataLine", () => {
666 test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => {
modified packages/fetch/src/stream.ts +2 −1
@@ -2,7 +2,7 @@
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
5- // @ts-expect-error
5+ // @ts-ignore
66 yield chunk as Uint8Array;
77 }
88 }
@@ -13,6 +13,7 @@
1313 if (response.status === 499) {
1414 return; // In case of client-side cancellation, just return
1515 }
16+
1617 if (response.status !== 200) {
1718 throw new Error(await response.text());
1819 }
modified packages/fetch/tsconfig.json +1 −1
@@ -19,5 +19,5 @@
1919 "declaration": true
2020 // "sourceMap": true
2121 },
22- "include": ["src/**/*"]
22+ "include": ["src/**/*", "jest.globals.d.ts"]
2323 }
modified packages/openai-adapters/README.md +1 −1
@@ -64,7 +64,7 @@
6464 - [x] Vllm
6565 - [ ] Vertex AI
6666 - [x] Voyage AI
67-- [ ] WatsonX
67+- [x] WatsonX
6868 - [x] xAI
6969 - [x] Fireworks
7070 - [x] Moonshot
modified packages/openai-adapters/package-lock.json +6 −6
@@ -1,18 +1,18 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.22",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/openai-adapters",
9- "version": "1.0.21",
9+ "version": "1.0.22",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@azure/openai": "^1.0.0-beta.12",
1313 "@continuedev/config-types": "^1.0.5",
1414 "@continuedev/config-yaml": "^1.0.51",
15- "@continuedev/fetch": "^1.0.3",
15+ "@continuedev/fetch": "^1.0.10",
1616 "dotenv": "^16.5.0",
1717 "json-schema": "^0.4.0",
1818 "node-fetch": "^3.3.2",
@@ -716,9 +716,9 @@
716716 }
717717 },
718718 "node_modules/@continuedev/fetch": {
719- "version": "1.0.3",
720- "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz",
721- "integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==",
719+ "version": "1.0.10",
720+ "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
721+ "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
722722 "dependencies": {
723723 "@continuedev/config-types": "^1.0.5",
724724 "follow-redirects": "^1.15.6",
modified packages/openai-adapters/package.json +2 −2
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.26",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
@@ -15,7 +15,7 @@
1515 "@azure/openai": "^1.0.0-beta.12",
1616 "@continuedev/config-types": "^1.0.5",
1717 "@continuedev/config-yaml": "^1.0.51",
18- "@continuedev/fetch": "^1.0.3",
18+ "@continuedev/fetch": "^1.0.10",
1919 "dotenv": "^16.5.0",
2020 "json-schema": "^0.4.0",
2121 "node-fetch": "^3.3.2",
modified packages/openai-adapters/src/apis/Anthropic.ts +5 −0
@@ -12,6 +12,7 @@
1212 import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
1313 import { AnthropicConfig } from "../types.js";
1414 import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
15+import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1516 import {
1617 BaseLlmApi,
1718 CreateRerankResponse,
@@ -157,6 +158,10 @@
157158 },
158159 );
159160
161+ if (response.status === 499) {
162+ return EMPTY_CHAT_COMPLETION;
163+ }
164+
160165 const completion = (await response.json()) as any;
161166 return {
162167 id: completion.id,
modified packages/openai-adapters/src/apis/Cohere.ts +5 −0
@@ -15,6 +15,7 @@
1515 } from "openai/resources/index";
1616 import { CohereConfig } from "../types.js";
1717 import { chatCompletion, customFetch, embedding } from "../util.js";
18+import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1819 import {
1920 BaseLlmApi,
2021 CreateRerankResponse,
@@ -77,6 +78,10 @@
7778 },
7879 );
7980
81+ if (resp.status === 499) {
82+ return EMPTY_CHAT_COMPLETION;
83+ }
84+
8085 const data = (await resp.json()) as any;
8186 const { input_tokens, output_tokens } = data.meta.tokens;
8287 return chatCompletion({
modified packages/openai-adapters/src/apis/Relace.ts +4 −0
@@ -105,6 +105,10 @@
105105 signal,
106106 });
107107
108+ if (response.status === 499) {
109+ return; // Aborted by user
110+ }
111+
108112 const result = (await response.json()) as any;
109113 const mergedCode = result.mergedCode;
110114
added packages/openai-adapters/src/apis/WatsonX.ts +314 −0
@@ -0,0 +1,314 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { OpenAI } from "openai/index";
3+import {
4+ ChatCompletion,
5+ ChatCompletionChunk,
6+ ChatCompletionCreateParamsNonStreaming,
7+ ChatCompletionCreateParamsStreaming,
8+ Completion,
9+ CompletionCreateParamsNonStreaming,
10+ CompletionCreateParamsStreaming,
11+} from "openai/resources/index";
12+import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
13+import { WatsonXConfig } from "../types.js";
14+import { chatCompletion, customFetch } from "../util.js";
15+import {
16+ BaseLlmApi,
17+ CreateRerankResponse,
18+ FimCreateParamsStreaming,
19+ RerankCreateParams,
20+} from "./base.js";
21+
22+export class WatsonXApi implements BaseLlmApi {
23+ apiBase: string;
24+ apiVersion: string = "2023-05-29";
25+ projectId?: string;
26+ deploymentId?: string;
27+
28+ constructor(protected config: WatsonXConfig) {
29+ this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
30+ if (!this.apiBase.endsWith("/")) {
31+ this.apiBase += "/";
32+ }
33+ this.apiVersion = config.env.apiVersion ?? this.apiVersion;
34+ this.projectId = config.env.projectId;
35+ this.deploymentId = config.env.deploymentId;
36+ }
37+
38+ private async getHeaders(): Promise<Record<string, string>> {
39+ const bearer = await this.getBearerToken();
40+ return {
41+ "Content-Type": "application/json",
42+ Authorization: `Bearer ${bearer.token}`,
43+ };
44+ }
45+
46+ async getBearerToken(): Promise<{ token: string; expiration: number }> {
47+ if (this.apiBase?.includes("cloud.ibm.com")) {
48+ // watsonx SaaS
49+ const wxToken = (await (
50+ await customFetch(this.config.requestOptions)(
51+ `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
52+ {
53+ method: "POST",
54+ headers: {
55+ "Content-Type": "application/x-www-form-urlencoded",
56+ Accept: "application/json",
57+ },
58+ },
59+ )
60+ ).json()) as any;
61+ return {
62+ token: wxToken["access_token"],
63+ expiration: wxToken["expiration"],
64+ };
65+ } else {
66+ // watsonx Software
67+ if (!this.config.apiKey?.includes(":")) {
68+ // Using ZenApiKey auth
69+ return {
70+ token: this.config.apiKey ?? "",
71+ expiration: -1,
72+ };
73+ } else {
74+ // Using username/password auth
75+ const userPass = this.config.apiKey?.split(":");
76+ const wxToken = (await (
77+ await customFetch(this.config.requestOptions)(
78+ `${this.apiBase}/icp4d-api/v1/authorize`,
79+ {
80+ method: "POST",
81+ headers: {
82+ "Content-Type": "application/json",
83+ Accept: "application/json",
84+ },
85+ body: JSON.stringify({
86+ username: userPass[0],
87+ password: userPass[1],
88+ }),
89+ },
90+ )
91+ ).json()) as any;
92+ const wxTokenExpiry = (await (
93+ await customFetch(this.config.requestOptions)(
94+ `${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
95+ {
96+ method: "GET",
97+ headers: {
98+ Accept: "application/json",
99+ Authorization: `Bearer ${wxToken["token"]}`,
100+ },
101+ },
102+ )
103+ ).json()) as any;
104+ return {
105+ token: wxToken["token"],
106+ expiration: wxTokenExpiry["exp"],
107+ };
108+ }
109+ }
110+ }
111+
112+ private getEndpoint(endpoint: string): string {
113+ return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
114+ }
115+
116+ private _convertBody(oaiBody: ChatCompletionCreateParams) {
117+ const stopSequences = oaiBody.stop
118+ ? Array.isArray(oaiBody.stop)
119+ ? oaiBody.stop.filter((s) => s.trim() !== "")
120+ : [oaiBody.stop]
121+ : undefined;
122+
123+ const payload: any = {
124+ messages: oaiBody.messages,
125+ max_tokens: oaiBody.max_tokens ?? 1024,
126+ stop: stopSequences,
127+ frequency_penalty: oaiBody.frequency_penalty,
128+ presence_penalty: oaiBody.presence_penalty,
129+ };
130+
131+ if (!this.deploymentId) {
132+ payload.model_id = oaiBody.model;
133+ payload.project_id = this.projectId;
134+ }
135+
136+ if (oaiBody.temperature !== undefined) {
137+ payload.temperature = oaiBody.temperature;
138+ }
139+
140+ if (oaiBody.top_p !== undefined) {
141+ payload.top_p = oaiBody.top_p;
142+ }
143+
144+ if (oaiBody.tools) {
145+ payload.tools = oaiBody.tools;
146+ if (oaiBody.tool_choice) {
147+ payload.tool_choice = oaiBody.tool_choice;
148+ } else {
149+ payload.tool_choice_option = "auto";
150+ }
151+ }
152+
153+ return payload;
154+ }
155+
156+ async chatCompletionNonStream(
157+ body: ChatCompletionCreateParamsNonStreaming,
158+ signal: AbortSignal,
159+ ): Promise<ChatCompletion> {
160+ const generator = this.chatCompletionStream(
161+ {
162+ ...body,
163+ stream: true,
164+ },
165+ signal,
166+ );
167+
168+ let content = "";
169+ for await (const chunk of generator) {
170+ content += chunk.choices[0].delta.content ?? "";
171+ }
172+ return chatCompletion({
173+ content,
174+ model: body.model,
175+ });
176+ }
177+
178+ async *chatCompletionStream(
179+ body: ChatCompletionCreateParamsStreaming,
180+ signal: AbortSignal,
181+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
182+ const url = this.getEndpoint("chat");
183+ const headers = await this.getHeaders();
184+ const stringifiedBody = JSON.stringify(this._convertBody(body));
185+ const response = await customFetch(this.config.requestOptions)(url, {
186+ method: "POST",
187+ headers,
188+ body: stringifiedBody,
189+ signal,
190+ });
191+
192+ if (!response.ok || !response.body) {
193+ throw new Error(
194+ `Failed to stream chat completion: ${await response.text()}`,
195+ );
196+ }
197+
198+ for await (const value of streamSse(response as any)) {
199+ if (!value.choices?.[0]) {
200+ continue;
201+ }
202+ yield value;
203+ }
204+ }
205+
206+ async completionNonStream(
207+ body: CompletionCreateParamsNonStreaming,
208+ signal: AbortSignal,
209+ ): Promise<Completion> {
210+ throw new Error("Method not implemented.");
211+ }
212+
213+ async *completionStream(
214+ body: CompletionCreateParamsStreaming,
215+ signal: AbortSignal,
216+ ): AsyncGenerator<Completion, any, unknown> {
217+ const params = {
218+ decoding_method: body.temperature ? "sample" : "greedy",
219+ max_new_tokens: body.max_tokens ?? 1024,
220+ min_new_tokens: 1,
221+ stop_sequences: body.stop
222+ ? Array.isArray(body.stop)
223+ ? body.stop
224+ : [body.stop]
225+ : [],
226+ include_stop_sequence: false,
227+ repetition_penalty: body.frequency_penalty || 1,
228+ temperature: body.temperature,
229+ top_p: body.top_p,
230+ top_k: 100,
231+ };
232+
233+ const payload: any = {
234+ input: body.prompt,
235+ parameters: params,
236+ };
237+
238+ if (!this.deploymentId) {
239+ payload.model_id = body.model;
240+ payload.project_id = this.projectId;
241+ }
242+
243+ const url = this.getEndpoint("generation");
244+ const response = await customFetch(this.config.requestOptions)(url, {
245+ method: "POST",
246+ headers: await this.getHeaders(),
247+ body: JSON.stringify(payload),
248+ signal,
249+ });
250+
251+ if (!response.ok || !response.body) {
252+ throw new Error(`Failed to stream completion: ${await response.text()}`);
253+ }
254+
255+ let generatedText = "";
256+ for await (const value of streamSse(response as any)) {
257+ const lines = value.toString().split("\n");
258+ let generatedChunk = "";
259+
260+ lines.forEach((line: string) => {
261+ if (line.startsWith("data:")) {
262+ const dataStr = line.replace(/^data:\s+/, "");
263+ try {
264+ const data = JSON.parse(dataStr);
265+ data.results.forEach((result: any) => {
266+ generatedChunk += result.generated_text || "";
267+ });
268+ } catch (e) {
269+ // parsing error is expected with streaming response
270+ }
271+ }
272+ });
273+
274+ if (generatedChunk) {
275+ generatedText += generatedChunk;
276+ yield {
277+ id: `watsonx-${Date.now()}`,
278+ object: "text_completion",
279+ created: Date.now(),
280+ model: body.model,
281+ choices: [
282+ {
283+ text: generatedChunk,
284+ index: 0,
285+ logprobs: null,
286+ finish_reason: "stop",
287+ },
288+ ],
289+ };
290+ }
291+ }
292+ }
293+
294+ async *fimStream(
295+ body: FimCreateParamsStreaming,
296+ signal: AbortSignal,
297+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
298+ throw new Error("Method not implemented.");
299+ }
300+
301+ async embed(
302+ body: OpenAI.Embeddings.EmbeddingCreateParams,
303+ ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
304+ throw new Error("Method not implemented.");
305+ }
306+
307+ async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
308+ throw new Error("Method not implemented.");
309+ }
310+
311+ async list(): Promise<OpenAI.Models.Model[]> {
312+ throw new Error("Method not implemented.");
313+ }
314+}
modified packages/openai-adapters/src/index.ts +8 −3
@@ -11,6 +11,7 @@
1111 import { MoonshotApi } from "./apis/Moonshot.js";
1212 import { OpenAIApi } from "./apis/OpenAI.js";
1313 import { RelaceApi } from "./apis/Relace.js";
14+import { WatsonXApi } from "./apis/WatsonX.js";
1415 import { BaseLlmApi } from "./apis/base.js";
1516 import { LLMConfig, OpenAIConfigSchema } from "./types.js";
1617
@@ -48,6 +49,8 @@
4849 return new RelaceApi(config);
4950 case "inception":
5051 return new InceptionApi(config);
52+ case "watsonx":
53+ return new WatsonXApi(config);
5154 case "x-ai":
5255 return openAICompatible("https://api.x.ai/v1/", config);
5356 case "voyage":
@@ -75,7 +78,10 @@
7578 case "nvidia":
7679 return openAICompatible("https://integrate.api.nvidia.com/v1/", config);
7780 case "ovhcloud":
78- return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config);
81+ return openAICompatible(
82+ "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
83+ config,
84+ );
7985 case "scaleway":
8086 return openAICompatible("https://api.scaleway.ai/v1/", config);
8187 case "fireworks":
@@ -111,10 +117,9 @@
111117 type Completion,
112118 type CompletionCreateParams,
113119 type CompletionCreateParamsNonStreaming,
114- type CompletionCreateParamsStreaming
120+ type CompletionCreateParamsStreaming,
115121 } from "openai/resources/index";
116122
117123 // export
118124 export type { BaseLlmApi } from "./apis/base.js";
119125 export type { LLMConfig } from "./types.js";
120-
modified packages/openai-adapters/src/test/main.test.ts +1 −0
@@ -10,6 +10,7 @@
1010 provider: config.provider as any,
1111 apiKey: config.apiKey,
1212 apiBase: config.apiBase,
13+ env: config.env,
1314 });
1415
1516 if (false) {
modified packages/openai-adapters/src/types.ts +12 −0
@@ -99,6 +99,17 @@
9999 });
100100 export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>;
101101
102+export const WatsonXConfigSchema = BasePlusConfig.extend({
103+ provider: z.literal("watsonx"),
104+ apiKey: z.string(),
105+ env: z.object({
106+ apiVersion: z.string().optional(),
107+ projectId: z.string().optional(),
108+ deploymentId: z.string().optional(),
109+ }),
110+});
111+export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>;
112+
102113 export const JinaConfigSchema = OpenAIConfigSchema.extend({
103114 provider: z.literal("jina"),
104115 });
@@ -118,6 +129,7 @@
118129 AzureConfigSchema,
119130 GeminiConfigSchema,
120131 AnthropicConfigSchema,
132+ WatsonXConfigSchema,
121133 JinaConfigSchema,
122134 MockConfigSchema,
123135 InceptionConfigSchema,
added packages/openai-adapters/src/util/emptyChatCompletion.ts +21 −0
@@ -0,0 +1,21 @@
1+import { ChatCompletion } from "openai/resources/index";
2+
3+export const EMPTY_CHAT_COMPLETION: ChatCompletion = {
4+ choices: [
5+ {
6+ finish_reason: "stop",
7+ index: 0,
8+ logprobs: null,
9+ message: {
10+ content: null,
11+ role: "assistant",
12+ refusal: null,
13+ },
14+ },
15+ ],
16+ usage: undefined,
17+ created: Date.now(),
18+ id: "",
19+ model: "UNSPECIFIED",
20+ object: "chat.completion",
21+};