Merge branch 'main' into nate/dev-data-updates

This commit is contained in:
Nate 2025-05-25 18:53:32 -07:00
commit ade15bc7d6
142 changed files with 4381 additions and 2154 deletions

View file

@ -93,6 +93,7 @@
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
"plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
@ -129,6 +130,7 @@
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
@ -2587,9 +2589,9 @@
}
},
"node_modules/axios": {
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",

View file

@ -1,6 +1,6 @@
import { streamResponse } from "@continuedev/fetch";
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamResponse } from "../../llm/stream.js";
const HttpSlashCommand: SlashCommand = {
name: "http",

View file

@ -19,7 +19,7 @@ import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import {
ASSISTANTS,
getAllDotContinueYamlFiles,
getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@ -284,7 +284,7 @@ export class ConfigHandler {
}
if (options.includeWorkspace) {
const assistantFiles = await getAllDotContinueYamlFiles(
const assistantFiles = await getAllDotContinueDefinitionFiles(
this.ide,
options,
ASSISTANTS,

View file

@ -101,7 +101,14 @@ export function resolveSerializedConfig(
const configMergeKeys = {
models: (a: any, b: any) => a.title === b.title,
contextProviders: (a: any, b: any) => a.name === b.name,
contextProviders: (a: any, b: any) => {
// If not HTTP providers, use the name only
if (a.name !== "http" || b.name !== "http") {
return a.name === b.name;
}
// For HTTP providers, consider them different if they have different URLs
return a.name === b.name && a.params?.url === b.params?.url;
},
slashCommands: (a: any, b: any) => a.name === b.name,
customCommands: (a: any, b: any) => a.name === b.name,
};

View file

@ -13,7 +13,7 @@ export const ASSISTANTS = "assistants";
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
export function isLocalAssistantFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
return false;
}
@ -21,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean {
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
}
export async function listYamlFilesInDir(
async function getDefinitionFilesInDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
@ -41,7 +41,7 @@ export async function listYamlFilesInDir(
source: "get assistant files",
});
const assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
(p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
);
const results = assistantFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
@ -86,7 +86,7 @@ export function getDotContinueSubDirs(
* This method searches in both ~/.continue and workspace .continue
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
*/
export async function getAllDotContinueYamlFiles(
export async function getAllDotContinueDefinitionFiles(
ide: IDE,
options: LoadAssistantFilesOptions,
subDirName: string,
@ -103,7 +103,7 @@ export async function getAllDotContinueYamlFiles(
// Get all assistant files from the directories
const assistantFiles = (
await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
).flat();
return await Promise.all(

View file

@ -0,0 +1,47 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
/**
* Loads rules from markdown files in the .continue/rules directory
*/
export async function loadMarkdownRules(ide: IDE): Promise<{
rules: RuleWithSource[];
errors: ConfigValidationError[];
}> {
const errors: ConfigValidationError[] = [];
const rules: RuleWithSource[] = [];
try {
// Get all .md files from .continue/rules
const markdownFiles = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
"rules",
);
// Filter to just .md files
const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
// Process each markdown file
for (const file of mdFiles) {
try {
const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
rules.push(rule);
} catch (e) {
errors.push({
fatal: false,
message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
});
}
}
} catch (e) {
errors.push({
fatal: false,
message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
});
}
return { rules, errors };
}

View file

@ -0,0 +1,174 @@
import {
convertMarkdownRuleToContinueRule,
parseMarkdownRule,
} from "./parseMarkdownRule";
describe("parseMarkdownRule", () => {
it("should correctly parse markdown with YAML frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle missing frontmatter", () => {
const content = `# Test Rule
This is a test rule without frontmatter.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(content);
});
it("should handle empty frontmatter", () => {
const content = `---
---
# Test Rule
This is a test rule with empty frontmatter.`;
const result = parseMarkdownRule(content);
// Log exact strings for debugging
console.log("Actual:", JSON.stringify(result.markdown));
console.log(
"Expected:",
JSON.stringify(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
),
);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
);
});
it("should handle frontmatter with whitespace", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle Windows line endings (CRLF)", () => {
// Using \r\n for CRLF line endings
const content = `---\r
globs: "**/test/**/*.kt"\r
---\r
\r
# Test Rule\r
\r
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
// The result should be normalized to \n
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle malformed frontmatter", () => {
const content = `---
globs: - "**/test/**/*.kt"
invalid: yaml: content
---
# Test Rule
This is a test rule.`;
// Should treat as only markdown when frontmatter is malformed
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(content);
});
});
describe("convertMarkdownRuleToContinueRule", () => {
it("should convert markdown with frontmatter to a rule", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Custom Name
---
# Test Rule
This is a test rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
expect(result.globs).toBe("**/test/**/*.kt");
expect(result.name).toBe("Custom Name");
expect(result.source).toBe("rules-block");
expect(result.ruleFile).toBe("/path/to/rule.md");
});
it("should use the first heading as name if not in frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule Title
This is a test rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.name).toBe("Test Rule Title");
});
it("should use filename as name if no heading or frontmatter name", () => {
const content = `---
globs: "**/test/**/*.kt"
---
This is a test rule without a heading.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/custom-rule.md",
content,
);
expect(result.name).toBe("custom-rule");
});
it("should include description from frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Test Rule
description: This is a rule description from frontmatter
---
# Test Rule
This is the content of the rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.description).toBe(
"This is a rule description from frontmatter",
);
});
});

View file

@ -0,0 +1,69 @@
import { basename } from "path";
import * as YAML from "yaml";
import { RuleWithSource } from "../..";
/**
* Parses markdown content with YAML frontmatter
*/
export function parseMarkdownRule(content: string): {
frontmatter: Record<string, any>;
markdown: string;
} {
// Normalize line endings to \n
const normalizedContent = content.replace(/\r\n/g, "\n");
// More reliable frontmatter detection
const parts = normalizedContent.split(/^---\s*$/m);
// If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
if (parts.length >= 3) {
const frontmatterStr = parts[1];
// Join the remaining parts back together (in case there are more --- in the markdown)
const markdownContent = parts.slice(2).join("---");
try {
// Parse YAML frontmatter
const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
return { frontmatter, markdown: markdownContent.trim() };
} catch (e) {
// Error parsing frontmatter, treat as markdown only
console.warn("Error parsing markdown frontmatter:", e);
return { frontmatter: {}, markdown: normalizedContent };
}
}
// No frontmatter found
return { frontmatter: {}, markdown: normalizedContent };
}
/**
* Converts a markdown file with YAML frontmatter to a RuleWithSource object
*/
export function convertMarkdownRuleToContinueRule(
path: string,
content: string,
): RuleWithSource {
const { frontmatter, markdown } = parseMarkdownRule(content);
// Try to extract title from first heading if no name in frontmatter
let name = frontmatter.name;
if (!name) {
// Look for a heading in the markdown
const headingMatch = markdown.match(/^#\s+(.+)$/m);
if (headingMatch) {
name = headingMatch[1].trim();
} else {
// Fall back to filename
name = basename(path).replace(/\.md$/, "");
}
}
return {
name,
rule: markdown,
globs: frontmatter.globs,
description: frontmatter.description,
source: "rules-block",
ruleFile: path,
};
}

View file

@ -32,6 +32,7 @@ import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
@ -128,6 +129,12 @@ export default async function doLoadConfig(options: {
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
// Add rules from markdown files in .continue/rules
const { rules: markdownRules, errors: markdownRulesErrors } =
await loadMarkdownRules(ide);
newConfig.rules.unshift(...markdownRules);
errors.push(...markdownRulesErrors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);

View file

@ -77,6 +77,7 @@ export function addModel(
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
maxStopWords: model.maxStopWords,
defaultCompletionOptions: model.completionOptions,
};
if (model.systemMessage) {

View file

@ -42,7 +42,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
@ -71,7 +71,7 @@ function convertYamlMcpToContinueMcp(
command: server.command,
args: server.args ?? [],
env: server.env,
},
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
};
}
@ -96,7 +96,7 @@ async function loadConfigYaml(options: {
// Add local .continue blocks
const allLocalBlocks: PackageIdentifier[] = [];
for (const blockType of BLOCK_TYPES) {
const localBlocks = await getAllDotContinueYamlFiles(
const localBlocks = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
blockType,
@ -458,7 +458,7 @@ async function configYamlToContinueConfig(options: {
transport: {
type: "stdio",
args: [],
...server,
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),

View file

@ -26,6 +26,7 @@ const modelDescriptionSchema = z.object({
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: z.number().optional(),
maxStopWords: z.number().optional(),
template: z
.enum([
"llama2",

View file

@ -35,7 +35,6 @@ import { TTS } from "./util/tts";
import {
ContextItemWithId,
DiffLine,
IdeSettings,
ModelDescription,
RangeInFile,
@ -62,61 +61,7 @@ import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
// This function is used for jetbrains inline edit and apply
async function* streamDiffLinesGenerator(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
): AsyncGenerator<DiffLine> {
const {
highlighted,
prefix,
suffix,
input,
language,
modelTitle,
includeRulesInSystemMessage,
} = msg.data;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Failed to load config");
}
// Title can be an edit, chat, or apply model
// Fall back to chat
const llm =
config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
config.selectedModelByRole.chat;
if (!llm) {
throw new Error("No model selected");
}
// rules included for edit, NOT apply
const rules = includeRulesInSystemMessage ? config.rules : undefined;
for await (const diffLine of streamDiffLines({
highlighted,
prefix,
suffix,
llm,
rulesToInclude: rules,
input,
language,
onlyOneInsertion: false,
overridePrompt: undefined,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
}
yield diffLine;
}
}
import { StreamAbortManager } from "./util/abortManager";
export class Core {
configHandler: ConfigHandler;
@ -132,7 +77,18 @@ export class Core {
this.globalContext.get("indexingPaused") === true,
);
private abortedMessageIds: Set<string> = new Set();
private messageAbortControllers = new Map<string, AbortController>();
private addMessageAbortController(id: string): AbortController {
const controller = new AbortController();
this.messageAbortControllers.set(id, controller);
controller.signal.addEventListener("abort", () => {
this.messageAbortControllers.delete(id);
});
return controller;
}
private abortById(messageId: string) {
this.messageAbortControllers.get(messageId)?.abort();
}
invoke<T extends keyof ToCoreProtocol>(
messageType: T,
@ -301,7 +257,7 @@ export class Core {
});
on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
this.abortById(msg.data ?? msg.messageId);
});
on("ping", (msg) => {
@ -470,27 +426,28 @@ export class Core {
}
});
on("llm/streamChat", (msg) =>
llmStreamChat(
on("llm/streamChat", (msg) => {
const abortController = this.addMessageAbortController(msg.messageId);
return llmStreamChat(
this.configHandler,
this.abortedMessageIds,
abortController,
msg,
this.ide,
this.messenger,
),
);
);
});
on("llm/complete", async (msg) => {
const model = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
const { config } = await this.configHandler.loadConfig();
const model = config?.selectedModelByRole.chat;
if (!model) {
throw new Error("No chat model selected");
}
const abortController = this.addMessageAbortController(msg.messageId);
const completion = await model.complete(
msg.data.prompt,
new AbortController().signal,
abortController.signal,
msg.data.completionOptions,
);
return completion;
@ -532,9 +489,47 @@ export class Core {
this.completionProvider.cancel();
});
on("streamDiffLines", (msg) =>
streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
);
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Failed to load config");
}
const { data } = msg;
// Title can be an edit, chat, or apply model
// Fall back to chat
const llm =
config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
config.selectedModelByRole.chat;
if (!llm) {
throw new Error("No model selected");
}
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
llm,
// rules included for edit, NOT apply
rulesToInclude: data.includeRulesInSystemMessage
? config.rules
: undefined,
input: data.input,
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
});
});
on("cancelApply", async (msg) => {
const abortManager = StreamAbortManager.getInstance();
abortManager.clear();
});
on("completeOnboarding", this.handleCompleteOnboarding.bind(this));

View file

@ -16,6 +16,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
abortController: AbortController,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@ -28,7 +29,7 @@ export async function* recursiveStream(
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
if (typeof prompt === "string") {
const generator = llm.streamComplete(prompt, new AbortController().signal, {
const generator = llm.streamComplete(prompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -50,6 +51,7 @@ export async function* recursiveStream(
// // TODO - Prediction capabilities lost because of partial input
// yield* recursiveStream(
// llm,
// abortController,
// continuationPrompt,
// undefined,
// buffer,
@ -60,7 +62,7 @@ export async function* recursiveStream(
}
}
} else {
const generator = llm.streamChat(prompt, new AbortController().signal, {
const generator = llm.streamChat(prompt, abortController.signal, {
prediction,
reasoning: false,
});
@ -90,6 +92,7 @@ export async function* recursiveStream(
// await generator.return(DUD_PROMPT_LOG);
// yield* recursiveStream(
// llm,
// abortController,
// continuationPrompt,
// undefined,
// buffer,

View file

@ -20,6 +20,7 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { StreamAbortManager } from "../util/abortManager";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@ -63,6 +64,7 @@ export async function* streamDiffLines({
highlighted,
suffix,
llm,
abortControllerId,
input,
language,
onlyOneInsertion,
@ -73,12 +75,15 @@ export async function* streamDiffLines({
highlighted: string;
suffix: string;
llm: ILLM;
abortControllerId: string;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
const abortManager = StreamAbortManager.getInstance();
const abortController = abortManager.get(abortControllerId);
void Telemetry.capture(
"inlineEdit",
{
@ -122,6 +127,7 @@ export async function* streamDiffLines({
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
contextItems: [],
})
: undefined;
@ -157,7 +163,7 @@ export async function* streamDiffLines({
content: highlighted,
};
const completion = recursiveStream(llm, prompt, prediction);
const completion = recursiveStream(llm, abortController, prompt, prediction);
let lines = streamLines(completion);

5
core/index.d.ts vendored
View file

@ -1242,6 +1242,7 @@ export interface StreamDiffLinesPayload {
language: string | undefined;
modelTitle: string | undefined;
includeRulesInSystemMessage: boolean;
fileUri?: string;
}
export interface HighlightedCodePayload {
@ -1255,6 +1256,10 @@ export interface AcceptOrRejectDiffPayload {
streamId?: string;
}
export interface ShowFilePayload {
filepath: string;
}
export interface RangeInFileWithContents {
filepath: string;
range: {

View file

@ -1,6 +1,7 @@
import {
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
@ -58,7 +59,7 @@ const EDIT_MESSAGE = `\
at the beginning, middle, or end of files using these "lazy" comments. Only
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
`
`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
@ -77,6 +78,31 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
${EDIT_MESSAGE}
</important_rules>`;
/**
* Helper function to get the context items for a user message
*/
function getUserContextItems(
userMsg: UserChatMessage | ToolResultChatMessage | undefined,
history: ChatHistoryItem[],
): ContextItemWithId[] {
if (!userMsg) return [];
// Find the history item that contains the userMsg
const historyItem = history.find((item) => {
// Check if the message ID matches
if ("id" in userMsg && "id" in item.message) {
return (item.message as any).id === (userMsg as any).id;
}
// Fallback to content comparison
return (
item.message.content === userMsg.content &&
item.message.role === userMsg.role
);
});
return historyItem?.contextItems || [];
}
export function constructMessages(
messageMode: string,
history: ChatHistoryItem[],
@ -92,7 +118,8 @@ export function constructMessages(
const historyItem = filteredHistory[i];
if (messageMode === "chat") {
const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage;
const toolMessage: ToolResultChatMessage =
historyItem.message as ToolResultChatMessage;
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
// remove all tool calls from the history
continue;
@ -127,10 +154,16 @@ export function constructMessages(
| ToolResultChatMessage
| undefined;
// Get context items for the last user message
const lastUserContextItems = getUserContextItems(
lastUserMsg,
filteredHistory,
);
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatOrAgentSystemMessage,
rules,
userMessage: lastUserMsg,
contextItems: lastUserContextItems,
});
if (systemMessage.trim()) {

View file

@ -390,6 +390,9 @@ export abstract class BaseLLM implements ILLM {
// Error mapping to be more helpful
if (!resp.ok) {
if (resp.status === 499) {
return resp; // client side cancellation
}
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
const error = JSON.parse(text)?.error?.replace(/"/g, "'");

View file

@ -1,7 +1,7 @@
import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class Anthropic extends BaseLLM {
static providerName = "anthropic";
@ -213,6 +213,10 @@ class Anthropic extends BaseLLM {
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
if (!response.ok) {
const json = await response.json();
if (json.type === "error") {

View file

@ -134,10 +134,8 @@ class Asksage extends BaseLLM {
body: JSON.stringify(args),
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
if (response.status === 499) {
return ""; // Aborted by user
}
const data = await response.json();
@ -167,10 +165,8 @@ class Asksage extends BaseLLM {
signal,
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();

View file

@ -306,7 +306,7 @@ class Bedrock extends BaseLLM {
}
const supportsTools =
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
(this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
let toolConfig = supportsTools && options.tools
? {

View file

@ -1,7 +1,7 @@
import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
export default class Cloudflare extends BaseLLM {
static providerName = "cloudflare";

View file

@ -1,3 +1,4 @@
import { streamJSON } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
@ -6,7 +7,6 @@ import {
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamJSON } from "../stream.js";
class Cohere extends BaseLLM {
static providerName = "cohere";
@ -84,6 +84,10 @@ class Cohere extends BaseLLM {
signal,
});
if (resp.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await resp.json();
yield { role: "assistant", content: data.text };

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";

View file

@ -132,12 +132,16 @@ class Flowise extends BaseLLM {
): AsyncGenerator<ChatMessage> {
const requestBody = this._getRequestBody(messages, options);
const { socket, socketInfo } = await this._initializeSocket();
const request = this.fetch(this._getChatUrl(), {
const response = await this.fetch(this._getChatUrl(), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal,
}).then((res) => res.json());
});
if (response.status === 499) {
return; // Aborted by user
}
while (await socketInfo.hasNextToken()) {
yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@ -145,7 +149,7 @@ class Flowise extends BaseLLM {
if (socketInfo.error) {
socket.disconnect();
try {
yield { role: "assistant", content: (await request).text };
yield { role: "assistant", content: await response.text() };
} catch (error: any) {
yield { role: "assistant", content: (error as Error).message ?? error };
}

View file

@ -1,3 +1,4 @@
import { streamResponse } from "@continuedev/fetch";
import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@ -8,7 +9,6 @@ import {
LLMOptions,
} from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
class FreeTrial extends BaseLLM {
static providerName = "free-trial";

View file

@ -1,3 +1,4 @@
import { streamResponse } from "@continuedev/fetch";
import { v4 as uuidv4 } from "uuid";
import {
AssistantChatMessage,
@ -10,7 +11,6 @@ import {
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import {
GeminiChatContent,
GeminiChatContentPart,
@ -438,6 +438,9 @@ class Gemini extends BaseLLM {
body: JSON.stringify(body),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };
}

View file

@ -1,6 +1,6 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceInferenceAPI extends BaseLLM {
static providerName = "huggingface-inference-api";

View file

@ -1,6 +1,6 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceTGI extends BaseLLM {
private static MAX_STOP_TOKENS = 4;

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import OpenAI from "./OpenAI.js";

View file

@ -1,6 +1,6 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class LlamaCpp extends BaseLLM {
static providerName = "llama.cpp";

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";

View file

@ -2,6 +2,7 @@ import { Mutex } from "async-mutex";
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import { v4 as uuidv4 } from "uuid";
import { streamResponse } from "@continuedev/fetch";
import {
ChatMessage,
ChatMessageRole,
@ -12,7 +13,6 @@ import {
import { renderChatMessage } from "../../util/messageContent.js";
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
type OllamaChatMessage = {
role: ChatMessageRole;
@ -457,6 +457,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
}
if (chatOptions.stream === false) {
if (response.status === 499) {
return; // Aborted by user
}
const json = (await response.json()) as OllamaChatResponse;
yield convertChatMessage(json);
} else {

View file

@ -0,0 +1,34 @@
import OpenAI from "./OpenAI";
describe("OpenAI", () => {
test("should identify correct o-series models", () => {
const openai = new OpenAI({
model: "o3-mini",
});
expect(openai.isOSeriesModel("o4-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o3-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o1-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o1")).toBeTruthy();
expect(openai.isOSeriesModel("o3")).toBeTruthy();
// artificially correct samples for future models
expect(openai.isOSeriesModel("o5-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o6")).toBeTruthy();
expect(openai.isOSeriesModel("o77")).toBeTruthy();
expect(openai.isOSeriesModel("o54-mini")).toBeTruthy();
});
test("should identify incorrect o-series models", () => {
const openai = new OpenAI({
model: "o3-mini",
});
expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy();
expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy();
expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy();
// artificially wrong samples
expect(openai.isOSeriesModel("os1")).toBeFalsy();
expect(openai.isOSeriesModel("so1")).toBeFalsy();
expect(openai.isOSeriesModel("ao31")).toBeFalsy();
expect(openai.isOSeriesModel("1os")).toBeFalsy();
});
});

View file

@ -3,6 +3,7 @@ import {
ChatCompletionMessageParam,
} from "openai/resources/index";
import { streamSse } from "@continuedev/fetch";
import {
ChatMessage,
CompletionOptions,
@ -16,7 +17,6 @@ import {
LlmApiRequestType,
toChatBody,
} from "../openaiTypeConverters.js";
import { streamSse } from "../stream.js";
const NON_CHAT_MODELS = [
"text-davinci-002",
@ -77,8 +77,8 @@ class OpenAI extends BaseLLM {
return model;
}
private isO3orO1Model(model?: string): boolean {
return !!model && (model.startsWith("o1") || model.startsWith("o3"));
public isOSeriesModel(model?: string): boolean {
return !!model && !!model.match(/^o[0-9]+/);
}
private isFireworksAiModel(model?: string): boolean {
@ -139,7 +139,7 @@ class OpenAI extends BaseLLM {
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
if (this.isO3orO1Model(options.model)) {
if (this.isOSeriesModel(options.model)) {
// a) use max_completion_tokens instead of max_tokens
finalOptions.max_completion_tokens = options.maxTokens;
finalOptions.max_tokens = undefined;
@ -241,7 +241,7 @@ class OpenAI extends BaseLLM {
body.stop = body.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
if (this.isO3orO1Model(body.model)) {
if (this.isOSeriesModel(body.model)) {
// a) use max_completion_tokens instead of max_tokens
body.max_completion_tokens = body.max_tokens;
body.max_tokens = undefined;
@ -352,6 +352,9 @@ class OpenAI extends BaseLLM {
// Handle non-streaming response
if (body.stream === false) {
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield data.choices[0].message;
return;

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
@ -58,7 +58,7 @@ class SiliconFlow extends OpenAI {
console.warn("[SiliconFlow] rerank: query is empty");
return [];
}
if (!chunks || chunks.length === 0) {
console.warn("[SiliconFlow] rerank: chunks is empty");
return [];

View file

@ -1,9 +1,9 @@
import { GoogleAuth } from "google-auth-library";
import { streamResponse, streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse, streamSse } from "../stream.js";
import Anthropic from "./Anthropic.js";
import Gemini from "./Gemini.js";
@ -95,6 +95,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatAnthropic(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
@ -128,8 +129,13 @@ class VertexAI extends BaseLLM {
]
: systemMessage,
}),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
@ -150,6 +156,7 @@ class VertexAI extends BaseLLM {
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
`publishers/google/models/${options.model}:streamGenerateContent`,
@ -160,6 +167,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const message of this.geminiInstance.processGeminiResponse(
streamResponse(response),
@ -171,6 +179,7 @@ class VertexAI extends BaseLLM {
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const instances = messages.map((message) => ({ prompt: message.content }));
@ -193,7 +202,11 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield { role: "assistant", content: data.predictions[0].content };
}
@ -203,6 +216,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatMistral(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const apiBase = this.apiBase!;
const apiURL = new URL(
@ -228,6 +242,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const chunk of streamSse(response)) {
@ -304,6 +319,9 @@ class VertexAI extends BaseLLM {
}),
signal,
});
if (resp.status === 499) {
return; // Aborted by user
}
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
yield (await resp.json()).predictions[0].content;
@ -323,14 +341,14 @@ class VertexAI extends BaseLLM {
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider === "gemini") {
yield* this.streamChatGemini(convertedMsgs, options);
yield* this.streamChatGemini(convertedMsgs, options, signal);
} else if (this.vertexProvider === "mistral") {
yield* this.StreamChatMistral(messages, options);
yield* this.StreamChatMistral(messages, options, signal);
} else if (this.vertexProvider === "anthropic") {
yield* this.StreamChatAnthropic(messages, options);
yield* this.StreamChatAnthropic(messages, options, signal);
} else {
if (options.model.includes("bison")) {
yield* this.streamChatBison(convertedMsgs, options);
yield* this.streamChatBison(convertedMsgs, options, signal);
} else {
throw new Error(`Unsupported model: ${options.model}`);
}

View file

@ -1,15 +1,12 @@
import { streamResponse, streamSse } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
} from "../../index.js";
import {
fromChatCompletionChunk,
} from "../openaiTypeConverters.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse, streamSse } from "../stream.js";
import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
let watsonxToken = {
expiration: 0,
@ -86,7 +83,7 @@ class WatsonX extends BaseLLM {
}
_getEndpoint(endpoint: string): string {
return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
}
static providerName = "watsonx";
@ -182,7 +179,6 @@ class WatsonX extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
await this.updateWatsonxToken();
const stopSequences = options.stop?.slice(0, 6) ?? [];
@ -214,44 +210,38 @@ class WatsonX extends BaseLLM {
payload.project_id = this.projectId;
}
var response = await this.fetch(url, {
const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
if (isNaN(generatedTextIndex)) {
console.error(`Unable to parse stream chunk ID: ${el}`);
}
} else if (el.startsWith("data:")) {
const dataStr = el.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
if (isNaN(generatedTextIndex)) {
console.error(`Unable to parse stream chunk ID: ${el}`);
}
});
yield generatedChunk
}
} else if (el.startsWith("data:")) {
const dataStr = el.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
}
});
yield generatedChunk;
}
}
@ -267,7 +257,7 @@ class WatsonX extends BaseLLM {
const headers = this._getHeaders();
const payload: any = {
messages: messages,
messages: messages,
max_tokens: options.maxTokens ?? 1024,
stop: stopSequences,
frequency_penalty: options.frequencyPenalty || 1,
@ -281,36 +271,30 @@ class WatsonX extends BaseLLM {
if (!!options.temperature) {
payload.temperature = options.temperature;
}
}
if (!!options.topP) {
payload.top_p = options.topP;
}
if (!!options.tools) {
payload.tools = options.tools;
if (options.toolChoice) {
payload.tool_choice = options.toolChoice;
payload.tool_choice = options.toolChoice;
} else {
payload.tool_choice_option = "auto";
payload.tool_choice_option = "auto";
}
}
var response = await this.fetch(url, {
const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
}
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
}
}
}

View file

@ -28,8 +28,12 @@ class ContinueProxy extends OpenAI {
// to call whatever LLM API is chosen
private actualApiBase?: string;
// Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
private configEnv?: Record<string, any>;
constructor(options: LLMOptions) {
super(options);
this.configEnv = options.env;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.orgScopeId = options.orgScopeId;
@ -54,6 +58,7 @@ class ContinueProxy extends OpenAI {
apiKeyLocation: this.apiKeyLocation,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
env: this.configEnv,
};
return {
continueProperties,

View file

@ -1,4 +1,4 @@
import { RuleWithSource, UserChatMessage } from "../..";
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
import { getSystemMessageWithRules } from "./getSystemMessageWithRules";
describe("getSystemMessageWithRules", () => {
@ -25,11 +25,48 @@ describe("getSystemMessageWithRules", () => {
source: "rules-block",
};
// JavaScript rule
const jsRule: RuleWithSource = {
name: "JavaScript Rule",
rule: "Follow JavaScript best practices",
globs: "**/*.js",
source: "rules-block",
};
// Empty context items
const emptyContextItems: ContextItemWithId[] = [];
// Context items with file paths
const tsContextItem: ContextItemWithId = {
content: "TypeScript file content",
name: "Component.tsx",
description: "A TypeScript component",
id: { providerTitle: "file", itemId: "src/Component.tsx" },
uri: { type: "file", value: "src/Component.tsx" },
};
const pyContextItem: ContextItemWithId = {
content: "Python file content",
name: "utils.py",
description: "A Python utility file",
id: { providerTitle: "file", itemId: "utils.py" },
uri: { type: "file", value: "utils.py" },
};
const jsContextItem: ContextItemWithId = {
content: "JavaScript file content",
name: "utils.js",
description: "A JavaScript utility file",
id: { providerTitle: "file", itemId: "src/utils.js" },
uri: { type: "file", value: "src/utils.js" },
};
it("should not include pattern-matched rules when no file paths are mentioned", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [tsRule],
contextItems: emptyContextItems,
});
expect(result).toBe(baseSystemMessage);
@ -40,12 +77,13 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage: undefined,
rules: [generalRule],
contextItems: emptyContextItems,
});
expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`);
});
it("should include only matching rules based on file paths", () => {
it("should include only matching rules based on file paths in message", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
@ -56,6 +94,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
contextItems: emptyContextItems,
});
// Should include TS rule and general rule, but not Python rule
@ -63,7 +102,38 @@ describe("getSystemMessageWithRules", () => {
expect(result).toBe(expected);
});
it("should include multiple matching rules", () => {
it("should include matching rules based on file paths in context items", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [tsRule, pythonRule, generalRule],
contextItems: [tsContextItem],
});
// Should include TS rule and general rule, but not Python rule
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
it("should include matching rules from both message and context items", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```python test.py\nprint('hello')\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
contextItems: [tsContextItem],
});
// Should include TS rule, Python rule, and general rule
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
it("should include multiple matching rules from message", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
@ -74,6 +144,20 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
contextItems: emptyContextItems,
});
// Should include all rules
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
it("should include multiple matching rules from context items", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [tsRule, pythonRule, generalRule],
contextItems: [tsContextItem, pyContextItem],
});
// Should include all rules
@ -91,6 +175,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
contextItems: emptyContextItems,
});
// Should only include the general rule
@ -117,6 +202,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [commaRule],
contextItems: emptyContextItems,
});
// With the current implementation, the comma-separated pattern is treated as a single string,
@ -143,6 +229,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
contextItems: emptyContextItems,
});
// With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts
@ -168,6 +255,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
contextItems: emptyContextItems,
});
// Should match src/main.ts but not config/settings.ts
@ -193,9 +281,125 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
contextItems: emptyContextItems,
});
// Should not match any file paths
expect(result).toBe(baseSystemMessage);
});
// New test for code block with filename only (no language)
it("should handle code blocks with filename only (no language identifier)", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```test.js\nclass Calculator { /* code */ }\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [jsRule, tsRule, generalRule],
contextItems: emptyContextItems,
});
// Should include JS rule and general rule
const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
// New test for code blocks with line ranges
it("should handle code blocks with line ranges", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```js test.js (19-25)\ndivide(number) { /* code */ }\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [jsRule, tsRule, generalRule],
contextItems: emptyContextItems,
});
// Should include JS rule and general rule
const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
// New test for mixed code block formats
it("should handle mixed code block formats in the same message", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```test.js\nclass Calculator { /* code */ }\n```\n" +
"```js utils.js (19-25)\ndivide(number) { /* code */ }\n```\n" +
"```ts config/settings.ts\nconst config = {};\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [jsRule, tsRule, generalRule],
contextItems: emptyContextItems,
});
// Should include JS rule, TS rule, and general rule
const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
// Test for context items when there's no message
it("should apply rules based on context items only when no message is present", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [jsRule, tsRule, generalRule],
contextItems: [jsContextItem],
});
// Should include JS rule and general rule
const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
// Test for non-file context items
it("should ignore non-file context items", () => {
const nonFileContextItem: ContextItemWithId = {
content: "Some search result",
name: "Search result",
description: "A search result",
id: { providerTitle: "search", itemId: "search-result" },
// No uri with type "file"
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [jsRule, tsRule, generalRule],
contextItems: [nonFileContextItem],
});
// Should only include general rule
const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
// Test combining context items with message
it("should match rules from both message code blocks and context items", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```ts src/main.ts\nconsole.log('hello');\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [jsRule, tsRule, pythonRule, generalRule],
contextItems: [jsContextItem, pyContextItem],
});
// Should include JS, TS, Python rules and general rule
const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
});

View file

@ -1,5 +1,10 @@
import { minimatch } from "minimatch";
import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
import {
ContextItemWithId,
RuleWithSource,
ToolResultChatMessage,
UserChatMessage,
} from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
@ -24,21 +29,34 @@ const matchesGlobs = (
};
/**
* Filters rules that apply to the given message
* Filters rules that apply to the given message and/or context items
*
* @param userMessage - The user or tool message to check for file paths in code blocks
* @param rules - The list of rules to filter
* @param contextItems - Context items to check for file paths
* @returns List of applicable rules
*/
export const getApplicableRules = (
userMessage: UserChatMessage | ToolResultChatMessage | undefined,
rules: RuleWithSource[],
contextItems: ContextItemWithId[],
): RuleWithSource[] => {
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
// Extract file paths from context items
const filePathsFromContextItems = contextItems
.filter((item) => item.uri?.type === "file" && item.uri?.value)
.map((item) => item.uri!.value);
// Combine file paths from both sources
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
return rules.filter((rule) => {
// A rule is active if it has no globs (applies to all files)
// or if at least one file path matches its globs
const hasNoGlobs = !rule.globs;
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
const matchesAnyFilePath = allFilePaths.some((path) =>
matchesGlobs(path, rule.globs),
);
@ -46,16 +64,27 @@ export const getApplicableRules = (
});
};
/**
* Creates a system message string with applicable rules appended
*
* @param baseSystemMessage - The base system message to start with
* @param userMessage - The user message to check for file paths
* @param rules - The list of rules to filter
* @param contextItems - Context items to check for file paths
* @returns System message with applicable rules appended
*/
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
contextItems,
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
contextItems: ContextItemWithId[];
}) => {
const applicableRules = getApplicableRules(userMessage, rules);
const applicableRules = getApplicableRules(userMessage, rules, contextItems);
let systemMessage = baseSystemMessage ?? "";
for (const rule of applicableRules) {

View file

@ -1,72 +0,0 @@
import { Readable } from "stream";
import { streamSse } from "./stream";
function createMockResponse(sseLines: string[]): Response {
// Create a Readable stream that emits the SSE lines
const stream = new Readable({
read() {
for (const line of sseLines) {
this.push(line + "\n\n");
}
this.push(null); // End of stream
}
}) as any;
// Minimal Response mock
return {
status: 200,
body: stream,
text: async () => "",
} as unknown as Response;
}
describe("streamSse", () => {
it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
const sseLines = [
'data: {"foo": "bar"}',
'data: {"baz": 42}',
'data:[DONE]'
];
const response = createMockResponse(sseLines);
const results = [];
for await (const data of streamSse(response)) {
results.push(data);
}
expect(results).toEqual([
{ foo: "bar" },
{ baz: 42 }
]);
});
it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
const sseLines = [
'data: {"foo": "bar"}',
'data: {"baz": 42}',
'data: [DONE]'
];
const response = createMockResponse(sseLines);
const results = [];
for await (const data of streamSse(response)) {
results.push(data);
}
expect(results).toEqual([
{ foo: "bar" },
{ baz: 42 }
]);
});
it("throws on malformed JSON", async () => {
const sseLines = [
'data: {"foo": "bar"',
'data:[DONE]'
];
const response = createMockResponse(sseLines);
const iterator = streamSse(response)[Symbol.asyncIterator]();
await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
});
});

View file

@ -1,4 +1,4 @@
async function* toAsyncIterable(
export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator<Uint8Array> {
for await (const chunk of nodeReadable) {

View file

@ -8,7 +8,7 @@ import { TTS } from "../util/tts";
export async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
abortController: AbortController,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
ide: IDE,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
@ -75,52 +75,44 @@ export async function* llmStreamChat(
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
fetchwithRequestOptions(
url,
{
...init,
signal: abortController.signal,
},
config.requestOptions,
),
completionOptions,
});
const checkActiveInterval = setInterval(() => {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
let next = await gen.next();
while (!next.done) {
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}
}, 100);
try {
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return(errorPromptLog);
clearInterval(checkActiveInterval);
break;
}
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
next = await gen.next();
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
next = await gen.next();
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} else {
const gen = model.streamChat(
messages,
new AbortController().signal,
abortController.signal,
completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}

View file

@ -191,6 +191,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("pixtral-12b-2409")).toBe(true);
expect(supportsFn("pixtral-large-latest")).toBe(true);
expect(supportsFn("open-mistral-nemo")).toBe(true);
expect(supportsFn("devstral-latest")).toBe(true);
});
it("should return false for other unsupported models", () => {
@ -206,6 +207,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
expect(supportsFn("DEVSTRAL-LATEST")).toBe(true);
});
});
@ -228,6 +230,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("aya-expanse")).toBe(true);
expect(supportsFn("firefunction-v2")).toBe(true);
expect(supportsFn("mistral-7b")).toBe(true);
expect(supportsFn("devstral-24b")).toBe(true);
});
it("should return false for explicitly unsupported models", () => {

View file

@ -18,6 +18,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3.5",
"claude-3-7",
"claude-3.7",
"claude-4",
"gpt-4",
"o3",
"gemini",
@ -25,9 +26,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
},
anthropic: (model) => {
if (
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
model.toLowerCase().startsWith(part),
)
[
"claude-3-5",
"claude-3.5",
"claude-3-7",
"claude-3.7",
"claude-4",
].some((part) => model.toLowerCase().startsWith(part))
) {
return true;
}
@ -81,9 +86,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
// For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
if (
model.toLowerCase().includes("sonnet") &&
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
model.toLowerCase().includes(part),
)
[
"claude-3-5",
"claude-3.5",
"claude-3-7",
"claude-3.7",
"claude-4",
].some((part) => model.toLowerCase().includes(part))
) {
return true;
}
@ -101,6 +110,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"pixtral",
"ministral",
"mistral-nemo",
"devstral",
].some((part) => model.toLowerCase().includes(part))
);
},
@ -143,6 +153,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"aya-expanse",
"firefunction-v2",
"mistral",
"devstral",
].some((part) => modelName.toLowerCase().includes(part))
) {
return true;
@ -174,9 +185,14 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
}
if (
["llama-3", "llama-4", "mistral", "codestral", "granite-3"].some(
(part) => model.toLowerCase().includes(part),
)
[
"llama-3",
"llama-4",
"mistral",
"codestral",
"granite-3",
"devstral",
].some((part) => model.toLowerCase().includes(part))
) {
return true;
}
@ -200,6 +216,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"openai/o3",
"openai/o4",
"anthropic/claude-3",
"anthropic/claude-4",
"microsoft/phi-3",
"google/gemini-flash-1.5",
"google/gemini-2",
@ -214,6 +231,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"mistralai/codestral",
"mistralai/mixtral",
"mistral/ministral",
"mistral/devstral",
"mistralai/pixtral",
"meta-llama/llama-3.3",
"amazon/nova",

View file

@ -0,0 +1,35 @@
import { extractPathsFromCodeBlocks } from "./extractPathsFromCodeBlocks";
describe("extractPathsFromCodeBlocks", () => {
it("should extract paths from code blocks with language and filepath", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(extractPathsFromCodeBlocks(content)).toEqual(["src/main.ts"]);
});
it("should extract paths from code blocks with filepath only (no language)", () => {
const content = "```test.js\nclass Calculator { }\n```";
expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
});
it("should extract paths from code blocks with line ranges", () => {
const content = "```js test.js (19-25)\nfunction test() {}\n```";
expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
});
it("should handle multiple code blocks with different formats", () => {
const content =
"```typescript src/main.ts\nconst x = 1;\n```\n" +
"```test.js\nclass Calculator { }\n```\n" +
"```js utils.js (19-25)\nfunction test() {}\n```";
const result = extractPathsFromCodeBlocks(content);
expect(result).toContain("src/main.ts");
expect(result).toContain("test.js");
expect(result).toContain("utils.js");
expect(result.length).toBe(3);
});
it("should not extract paths from code blocks without file paths", () => {
const content = "```typescript\nconst x = 1;\n```";
expect(extractPathsFromCodeBlocks(content)).toEqual([]);
});
});

View file

@ -2,21 +2,37 @@
* Extracts file paths from markdown code blocks
*/
export function extractPathsFromCodeBlocks(content: string): string[] {
// Match:
// 1. Starting ```
// 2. Optional language identifier
// 3. Required whitespace
// 4. File path (captured) that must contain a dot and extension
const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
const paths: string[] = [];
let match;
console.log("CONTENT", content);
while ((match = codeBlockRegex.exec(content)) !== null) {
const path = match[1];
if (path && !path.startsWith("```")) {
paths.push(path);
const paths: string[] = [];
// Match code block opening patterns:
// 1. ```language filepath
// 2. ```filepath
// 3. ```language filepath (range)
// First match all code block starts
const codeBlockStarts = content.match(/```[^\n]+/g) || [];
for (const blockStart of codeBlockStarts) {
// Try to extract a valid filename with extension
const filenameMatches = blockStart.match(/([^\s()```]+\.[a-zA-Z0-9]+)/);
if (filenameMatches && filenameMatches[1]) {
const filename = filenameMatches[1];
// Verify this is a legitimate filename (not part of something else)
if (
// Check if valid extension
/\.[a-zA-Z0-9]+$/.test(filename) &&
// Make sure it's not a URL
!filename.includes("://") &&
// Avoid duplicates
!paths.includes(filename)
) {
paths.push(filename);
}
}
}
return paths;
}

22
core/package-lock.json generated
View file

@ -14,9 +14,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -138,7 +138,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -2927,9 +2927,10 @@
"link": true
},
"node_modules/@continuedev/fetch": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.6.tgz",
"integrity": "sha512-QpB9cHgEw5avoouFR0qm7/XTo44SrVfkGAmzbDTui2P9djj+DYvj+0yaJ8e/Ubyc5PUjFTUS2YnRar7NfYpHIg==",
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
"integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
@ -2944,14 +2945,15 @@
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
},
"node_modules/@continuedev/openai-adapters": {
"version": "1.0.19",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz",
"integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==",
"version": "1.0.25",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.25.tgz",
"integrity": "sha512-YG7bcAlUk3BnqIOZw+ClmxmZU6G3OaaZqbhfqgiCnJem5i7oDy0pkAVHjig4iRTQkpvDokKmBXCH9wmQNRbWNw==",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",

View file

@ -49,9 +49,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -46,6 +46,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
// Special
ping: [string, string];
abort: [undefined, void];
cancelApply: [undefined, void];
// History
"history/list": [ListHistoryOptions, SessionMetadata[]];

View file

@ -2,12 +2,13 @@ import { ToIdeFromWebviewOrCoreProtocol } from "./ide";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import {
AcceptOrRejectDiffPayload,
ApplyState,
SetCodeToEditPayload,
HighlightedCodePayload,
MessageContent,
RangeInFileWithContents,
AcceptOrRejectDiffPayload,
SetCodeToEditPayload,
ShowFilePayload,
} from "../";
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
@ -23,7 +24,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
];
overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
showFile: [ShowFilePayload, void];
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
@ -41,7 +42,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
vscMediaUrl: string;
},
];
"jetbrains/getColors": [undefined, Record<string, string>];
"jetbrains/getColors": [undefined, Record<string, string | null | undefined>];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [AcceptOrRejectDiffPayload, void];

View file

@ -40,7 +40,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
getCurrentSessionId: [undefined, string];
"jetbrains/setColors": [Record<string, string>, void];
"jetbrains/setColors": [Record<string, string | null | undefined>, void];
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
};

View file

@ -28,6 +28,10 @@ export const createRuleBlock: Tool = {
description:
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
},
description: {
type: "string",
description: "Short description of the rule",
},
globs: {
type: "string",
description:

View file

@ -1,4 +1,4 @@
import * as YAML from "yaml";
import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
import { createRuleBlockImpl } from "./createRuleBlock";
// Mock the extras parameter with necessary functions
@ -17,33 +17,6 @@ describe("createRuleBlockImpl", () => {
jest.clearAllMocks();
});
it("should create a basic rule with name and rule content", async () => {
const args = {
name: "Test Rule",
rule: "Always write tests",
};
const result = await createRuleBlockImpl(args, mockExtras as any);
// Verify that writeFile was called with the correct YAML
expect(mockIde.writeFile).toHaveBeenCalled();
const yamlContent = mockIde.writeFile.mock.calls[0][1];
const parsedYaml = YAML.parse(yamlContent);
// Verify the structure of the YAML
expect(parsedYaml).toEqual({
name: "Test Rule",
version: "0.0.1",
schema: "v1",
rules: [
{
name: "Test Rule",
rule: "Always write tests",
},
],
});
});
it("should create a rule with glob pattern", async () => {
const args = {
name: "TypeScript Rule",
@ -53,14 +26,16 @@ describe("createRuleBlockImpl", () => {
await createRuleBlockImpl(args, mockExtras as any);
// Verify the YAML structure with globs
const yamlContent = mockIde.writeFile.mock.calls[0][1];
const parsedYaml = YAML.parse(yamlContent);
expect(parsedYaml.rules[0]).toEqual({
name: "TypeScript Rule",
rule: "Use interfaces for object shapes",
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
globs: "**/*.{ts,tsx}",
});
expect(markdown).toContain("# TypeScript Rule");
expect(markdown).toContain("Use interfaces for object shapes");
});
it("should create a filename based on sanitized rule name", async () => {
@ -71,8 +46,51 @@ describe("createRuleBlockImpl", () => {
await createRuleBlockImpl(args, mockExtras as any);
// Check that the filename is sanitized
const fileUri = mockIde.writeFile.mock.calls[0][0];
expect(fileUri).toContain("special-chracters-spaces.yaml");
expect(fileUri).toContain("special-chracters-spaces.md");
});
it("should create a rule with description pattern", async () => {
const args = {
name: "Description Test",
rule: "This is the rule content",
description: "This is a detailed explanation of the rule",
};
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "This is a detailed explanation of the rule",
});
expect(markdown).toContain("# Description Test");
expect(markdown).toContain("This is the rule content");
});
it("should include both globs and description in frontmatter", async () => {
const args = {
name: "Complete Rule",
rule: "Follow this standard",
description: "This rule enforces our team standards",
globs: "**/*.js",
};
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "This rule enforces our team standards",
globs: "**/*.js",
});
expect(markdown).toContain("# Complete Rule");
expect(markdown).toContain("Follow this standard");
});
});

View file

@ -1,4 +1,3 @@
import { ConfigYaml } from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ToolImpl } from ".";
import { joinPathsToUri } from "../../util/uri";
@ -6,6 +5,7 @@ import { joinPathsToUri } from "../../util/uri";
export interface CreateRuleBlockArgs {
name: string;
rule: string;
description: string;
globs?: string;
}
@ -19,41 +19,46 @@ export const createRuleBlockImpl: ToolImpl = async (
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-");
const ruleObject = {
name: args.name,
rule: args.rule,
...(args.globs ? { globs: args.globs.trim() } : {}),
};
const fileExtension = "md";
const ruleBlock: ConfigYaml = {
name: args.name,
version: "0.0.1",
schema: "v1",
rules: [ruleObject],
};
const frontmatter: Record<string, string> = {};
const ruleYaml = YAML.stringify(ruleBlock);
if (args.globs) {
frontmatter.globs = args.globs.trim();
}
if (args.description) {
frontmatter.description = args.description.trim();
}
const frontmatterYaml = YAML.stringify(frontmatter).trim();
let fileContent = `---
${frontmatterYaml}
---
# ${args.name}
${args.rule}
`;
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const rulesDirUri = joinPathsToUri(
localContinueDir,
".continue",
"rules",
`${safeRuleName}.yaml`,
`${safeRuleName}.${fileExtension}`,
);
await extras.ide.writeFile(rulesDirUri, ruleYaml);
await extras.ide.writeFile(rulesDirUri, fileContent);
await extras.ide.openFile(rulesDirUri);
return [
{
name: "New Rule Block",
description: "", // No description throws an error in the GUI
description: args.description || "",
uri: {
type: "file",
value: rulesDirUri,
},
content: "Rule created successfully",
content: `Rule created successfully`,
},
];
};

37
core/util/abortManager.ts Normal file
View file

@ -0,0 +1,37 @@
export class StreamAbortManager {
private static instance: StreamAbortManager;
private controllers: Map<string, AbortController>;
private constructor() {
this.controllers = new Map();
}
public static getInstance(): StreamAbortManager {
if (!StreamAbortManager.instance) {
StreamAbortManager.instance = new StreamAbortManager();
}
return StreamAbortManager.instance;
}
public get(id: string): AbortController {
let controller = this.controllers.get(id);
if (!controller) {
controller = new AbortController();
this.controllers.set(id, controller);
}
return controller;
}
public abort(id: string): void {
const controller = this.controllers.get(id);
if (controller) {
controller.abort();
this.controllers.delete(id);
}
}
public clear(): void {
this.controllers.forEach((controller) => controller.abort());
this.controllers.clear();
}
}

View file

@ -1 +1 @@
!node_modules
node_modules

122
core/vendor/package-lock.json generated vendored
View file

@ -10,6 +10,9 @@
"license": "Apache-2.0",
"dependencies": {
"@xenova/transformers": "^2.14.0"
},
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/@huggingface/jinja": {
@ -105,6 +108,78 @@
"resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz",
"integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw=="
},
"node_modules/bare-events": {
"version": "2.5.4",
"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz",
"integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==",
"license": "Apache-2.0",
"optional": true
},
"node_modules/bare-fs": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz",
"integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"bare-events": "^2.5.4",
"bare-path": "^3.0.0",
"bare-stream": "^2.6.4"
},
"engines": {
"bare": ">=1.16.0"
},
"peerDependencies": {
"bare-buffer": "*"
},
"peerDependenciesMeta": {
"bare-buffer": {
"optional": true
}
}
},
"node_modules/bare-os": {
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
"integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
"license": "Apache-2.0",
"optional": true,
"engines": {
"bare": ">=1.14.0"
}
},
"node_modules/bare-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
"integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"bare-os": "^3.0.1"
}
},
"node_modules/bare-stream": {
"version": "2.6.5",
"resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz",
"integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"streamx": "^2.21.0"
},
"peerDependencies": {
"bare-buffer": "*",
"bare-events": "*"
},
"peerDependenciesMeta": {
"bare-buffer": {
"optional": true
},
"bare-events": {
"optional": true
}
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@ -444,9 +519,10 @@
}
},
"node_modules/prebuild-install/node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
@ -503,11 +579,6 @@
"once": "^1.3.1"
}
},
"node_modules/queue-tick": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
"integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag=="
},
"node_modules/rc": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
@ -642,12 +713,16 @@
}
},
"node_modules/streamx": {
"version": "2.15.6",
"resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz",
"integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==",
"version": "2.22.0",
"resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz",
"integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==",
"license": "MIT",
"dependencies": {
"fast-fifo": "^1.1.0",
"queue-tick": "^1.0.1"
"fast-fifo": "^1.3.2",
"text-decoder": "^1.1.0"
},
"optionalDependencies": {
"bare-events": "^2.2.0"
}
},
"node_modules/string_decoder": {
@ -667,13 +742,17 @@
}
},
"node_modules/tar-fs": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz",
"integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==",
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
"integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
"license": "MIT",
"dependencies": {
"mkdirp-classic": "^0.5.2",
"pump": "^3.0.0",
"tar-stream": "^3.1.5"
},
"optionalDependencies": {
"bare-fs": "^4.0.1",
"bare-path": "^3.0.0"
}
},
"node_modules/tar-stream": {
@ -686,6 +765,15 @@
"streamx": "^2.15.0"
}
},
"node_modules/text-decoder": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz",
"integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==",
"license": "Apache-2.0",
"dependencies": {
"b4a": "^1.6.4"
}
},
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",

View file

@ -188,6 +188,7 @@ chat, editing, and summarizing.
not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
provider and model. Supported capabilities include `tool_use` and `image_input`.
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
`chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@ -406,7 +407,7 @@ Destinations to which [development data](./customize/deep-dives/development-data
- `destination` (**required**): The destination/endpoint that will receive the data. Can be:
- an HTTP endpoint that will receive a POST request with a JSON blob
- a file URL to a directory in which events will be dumpted to `.jsonl` files
- `schema` (**required**): the schema version of the JSON blobs to be sent
- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
- `events`: an array of event names to include. Defaults to all events if not specified.
- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
contents, prompts, and completions. Defaults to `all`

View file

@ -120,6 +120,8 @@ If you're seeing a `fetch failed` error and your network requires custom certifi
You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
#### VS Code Proxy Settings
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.

View file

@ -66,7 +66,9 @@ const config = {
],
scripts: [
'!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)}();',
{
src: "/scripts/custom-reo.js", // it references from static folder
},
],
themeConfig:

1
docs/static/scripts/custom-reo.js vendored Normal file
View file

@ -0,0 +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)}();

View file

@ -11,15 +11,19 @@ import org.jetbrains.annotations.NotNull
class ContinueActionPromote : ActionPromoter {
override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
if (actions.none { it is AcceptAutocompleteAction }) {
return null
} else {
// For autocomplete actions
if (actions.any { it is AcceptAutocompleteAction }) {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
if (!settings.continueState.showIDECompletionSideBySide) {
return null;
if (settings.continueState.showIDECompletionSideBySide) {
return actions.filterIsInstance<AcceptAutocompleteAction>()
}
return actions.filterIsInstance<AcceptAutocompleteAction>()
}
val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
if (rejectDiffActions.isNotEmpty()) {
return rejectDiffActions
}
return null
}
}

View file

@ -1,25 +1,12 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowManager
fun getPluginService(project: Project?): ContinuePluginService? {
if (project == null) {
return null
}
return ServiceManager.getService(
project,
ContinuePluginService::class.java
)
}
class AcceptDiffAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
@ -29,7 +16,7 @@ class AcceptDiffAction : AnAction() {
private fun acceptHorizontalDiff(e: AnActionEvent) {
val continuePluginService = getPluginService(e.project) ?: return
continuePluginService?.diffManager?.acceptDiff(null)
continuePluginService.diffManager?.acceptDiff(null)
}
private fun acceptVerticalDiff(e: AnActionEvent) {
@ -61,28 +48,6 @@ class RejectDiffAction : AnAction() {
}
}
fun getContinuePluginService(project: Project?): ContinuePluginService? {
if (project != null) {
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow("Continue")
if (toolWindow != null) {
if (!toolWindow.isVisible) {
toolWindow.activate(null)
}
}
}
return getPluginService(project)
}
fun focusContinueInput(project: Project?) {
val continuePluginService = getContinuePluginService(project) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
class FocusContinueInputWithoutClearAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
@ -134,8 +99,11 @@ class OpenLogsAction : AnAction() {
if (logFile.exists()) {
val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
if (virtualFile != null) {
com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
}
}

View file

@ -0,0 +1,39 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowManager
fun getContinuePluginService(project: Project?): ContinuePluginService? {
if (project != null) {
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow("Continue")
if (toolWindow != null) {
if (!toolWindow.isVisible) {
toolWindow.activate(null)
}
}
}
return getPluginService(project)
}
fun focusContinueInput(project: Project?) {
val continuePluginService = getContinuePluginService(project) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
fun getPluginService(project: Project?): ContinuePluginService? {
if (project == null) {
return null
}
return ServiceManager.getService(
project,
ContinuePluginService::class.java
)
}

View file

@ -1,29 +0,0 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.components.service
class AutocompleteActionGroup : DefaultActionGroup() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun update(e: AnActionEvent) {
super.update(e)
removeAll()
val continueSettingsService = service<ContinueExtensionSettings>()
if (continueSettingsService.continueState.enableTabAutocomplete) {
addAll(
DisableTabAutocompleteAction(),
)
} else {
addAll(
EnableTabAutocompleteAction(),
)
}
}
}

View file

@ -121,10 +121,10 @@ class ApplyToFileHandler(
val prompt = buildApplyPrompt()
// Extract the code ranges (highlighted or full document)
val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges()
val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
// Get the line range for the diff stream
val rif = editorUtils.getHighlightedCode()
val rif = editorUtils.getHighlightedRIF()
val startLine = rif?.range?.start?.line ?: 0
val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)

View file

@ -108,7 +108,7 @@ class DiffManager(private val project: Project) : DumbAware {
)
continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
cleanUpFile(file)
}

View file

@ -2,11 +2,13 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.CodeInsightColors
import java.awt.Color
import kotlin.math.max
import kotlin.math.min
import com.intellij.ui.JBColor
import com.intellij.ui.ColorUtil
import kotlin.math.roundToInt
class GetTheme {
fun getSecondaryDark(): Color {
@ -38,64 +40,173 @@ class GetTheme {
return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground
}
fun getTheme(): Map<String, String> {
fun toHex(color: Color): String {
return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
fun toHex(color: Color?): String? {
if(color == null) {
return null
}
return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
}
fun namedColor(name: String): Color? {
// JB Color named color will fall back to a default unless we give it a fallback
// We want defaults to be handled on the GUI side, so we give it this filler color
// Which has a very low chance of conflicting with a real one
// And return undefined if it gets the skip color
val SKIP_COLOR = Color (18, 52, 86) // Hex #123456
val color = JBColor.namedColor(name, SKIP_COLOR)
if(toHex(color) == "#123456") {
return null
}
return color
}
fun lighten(color: Color, percentage: Int = 5): Color {
// Increase each RGB component slightly
val factor = 1 + percentage / 100f;
fun lightenInt(value: Int): Int {
return (value * factor).roundToInt().coerceAtMost(255)
}
return Color(
lightenInt(color.red),
lightenInt (color.green),
lightenInt(color.blue),
color.alpha
)
}
fun darken(color: Color, percentage: Int = 5): Color {
// Decrease each RGB component slightly
val factor = 1 - percentage / 100f;
fun darkenInt(value: Int): Int {
return (value * factor).roundToInt().coerceAtLeast(0)
}
return Color(
darkenInt(color.red),
darkenInt(color.green),
darkenInt(color.blue),
color.alpha
)
}
fun slightChange(color: Color?, percentage: Int = 5): Color? {
if(color == null){
return null
}
// If dark, make slightly lighter. If light, make slightly darker
val averageRgb = (color.red + color.green + color.blue) / 3
return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage)
}
fun getTheme(): Map<String, String?> {
try {
val editorScheme = EditorColorsManager.getInstance().globalScheme
val background = JBColor.background()
val foreground = JBColor.foreground()
val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230))
val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0))
val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150))
val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0))
val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255))
val border = JBColor.border()
val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255))
val editorScheme = EditorColorsManager.getInstance().globalScheme
val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor")
val buttonBackground = namedColor("Button.default.startBackground")
?: namedColor("Button.default.background")
val buttonForeground = namedColor("Button.default.startForeground")
?: namedColor("Button.default.foreground")
val buttonHoverBackground = namedColor("Button.default.hoverStartBackground")
?: namedColor("Button.default.hoverBackground")
?: namedColor("Button.default.startHoverBackground")
?: slightChange(buttonBackground)
val secondaryBackground = namedColor("Button.background") ?: background
val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground)
val badgeBackground = namedColor("Badge.background")
val badgeForeground = namedColor("Badge.foreground")
val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background")
val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground")
val inputBackground = namedColor("TextField.background")
val inputForeground = namedColor("TextField.foreground")
val inputPlaceholder = namedColor("TextField.inactiveForeground")
val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background)
val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground")
val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
val listSelectionForeground = namedColor("List.selectionForeground")
val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground")
val mutedDescription = namedColor("Component.infoForeground")
?: namedColor("ContextHelp.foreground")
?: namedColor("TextField.placeholderForeground")
?: namedColor("Label.disabledForeground")
?: namedColor("ToolTip.foreground")
val link = namedColor("Link.activeForeground")
val successColor = namedColor("ValidationSuccess.successColor")
?: namedColor("Component.successForeground")
?: namedColor("Label.successForeground")
val warningColor = namedColor("ValidationWarning.warningColor")
?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor
?: namedColor("Component.warningForeground")
?: namedColor("Label.warningForeground")
val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground")
val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor")
val editorBackground = editorScheme.defaultBackground
val editorForeground = editorScheme.defaultForeground
val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220))
val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0)
val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?:
editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
// These should match the keys in GUI's theme.ts
val theme = mapOf(
"--vscode-editor-foreground" to toHex(editorForeground),
"--vscode-editor-background" to toHex(editorBackground),
"--vscode-button-background" to toHex(buttonBackground),
"--vscode-button-foreground" to toHex(buttonForeground),
"--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50",
"--vscode-quickInputList-focusForeground" to toHex(foreground),
"--vscode-quickInput-background" to toHex(inputBackground),
"--vscode-badge-background" to toHex(badgeBackground),
"--vscode-badge-foreground" to toHex(badgeForeground),
"--vscode-input-background" to toHex(inputBackground),
"--vscode-input-border" to toHex(border),
"--vscode-sideBar-background" to toHex(background),
"--vscode-sideBar-border" to toHex(border),
"--vscode-focusBorder" to toHex(focusBorder),
"--vscode-commandCenter-activeBorder" to toHex(focusBorder),
"--vscode-commandCenter-inactiveBorder" to toHex(border),
"--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40"
)
"background" to background,
"foreground" to foreground,
"editor-background" to editorBackground,
"editor-foreground" to editorForeground,
"primary-background" to buttonBackground,
"primary-foreground" to buttonForeground,
"primary-hover" to buttonHoverBackground,
"secondary-background" to secondaryBackground,
"secondary-foreground" to foreground,
"secondary-hover" to secondaryHoverBackground,
"border" to border,
"border-focus" to focusBorder,
"command-background" to commandBackground,
"command-foreground" to commandForeground,
"command-border" to border,
"command-border-focus" to focusBorder,
"description" to description,
"description-muted" to mutedDescription,
"input-background" to inputBackground,
"input-foreground" to inputForeground,
"input-border" to border,
"input-placeholder" to inputPlaceholder,
"table-oddRow" to tableOddRow,
"badge-background" to badgeBackground,
"badge-foreground" to badgeForeground,
"success" to successColor,
"warning" to warningColor,
"error" to errorColor,
"link" to link,
"accent" to accentColor,
"find-match" to findMatchBackground,
"find-match-selected" to findMatchSelectedBackground,
"list-hover" to listHoverBackground,
"list-active" to actionHoverBackground,
"list-active-foreground" to listSelectionForeground
).mapValues { toHex(it.value) }
return theme
} catch (error: Error) {
return mapOf()
}
}
}

View file

@ -91,6 +91,15 @@ class IdeProtocolClient(
respond(jsonData)
}
"showFile" -> {
val params = Gson().fromJson(
dataElement.toString(),
ShowFilePayload::class.java
)
ide.openFile(params.filepath)
respond(null)
}
"getIdeSettings" -> {
val settings = ide.getIdeSettings()
respond(settings)
@ -438,7 +447,7 @@ class IdeProtocolClient(
"acceptDiff" -> {
val params = Gson().fromJson(
dataElement.toString(),
AcceptDiffParams::class.java
AcceptOrRejectDiffPayload::class.java
)
val filepath = params.filepath;
@ -454,7 +463,7 @@ class IdeProtocolClient(
"rejectDiff" -> {
val params = Gson().fromJson(
dataElement.toString(),
RejectDiffParams::class.java
AcceptOrRejectDiffPayload::class.java
)
val filepath = params.filepath;
@ -493,7 +502,7 @@ class IdeProtocolClient(
fun sendHighlightedCode(edit: Boolean = false) {
val editor = EditorUtils.getEditor(project)
val rif = editor?.getHighlightedCode() ?: return
val rif = editor?.getHighlightedRIF() ?: return
continuePluginService.sendToWebview(
"highlightedCode",

View file

@ -111,7 +111,8 @@ class DiffStreamHandler(
suffix = suffix,
language = virtualFile?.fileType?.name,
modelTitle = modelTitle,
includeRulesInSystemMessage = includeRulesInSystemMessage
includeRulesInSystemMessage = includeRulesInSystemMessage,
fileUri = virtualFile?.url
),
null
) { response ->
@ -289,7 +290,6 @@ class DiffStreamHandler(
}
}
private fun handleFinishedResponse() {
ApplicationManager.getApplication().invokeLater {
// Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
@ -337,6 +337,5 @@ class DiffStreamHandler(
private fun setClosed() {
sendUpdate(ApplyStateStatus.CLOSED)
resetState()
onClose()
}
}

View file

@ -1,7 +1,5 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.Position
import com.github.continuedev.continueintellijextension.Range
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
@ -72,28 +70,33 @@ class EditorUtils(val editor: Editor) {
editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
}
/**
* Remove the selected range in a thread-safe manner
*/
fun removeSelection() {
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
}
/**
* Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
*/
fun extractCodeRanges(): Triple<String, String, String> {
val rif = getHighlightedCode()
fun getHighlightedRangeTriplet(): Triple<String, String, String> {
val rif = getHighlightedRIF()
return if (rif == null) {
// If no highlight, use the whole document as highlighted
Triple("", editor.document.text, "")
} else {
// Use the RangeInFileWithContents to get absolute offsets
val startOffset = rif.getStartOffset(editor.document)
val endOffset = rif.getEndOffset(editor.document)
val (startOffset, endOffset) = rif.offsets
val prefix = editor.document.getText(TextRange(0, startOffset))
val highlighted = rif.contents
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
// Remove the selection after processing
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
removeSelection()
Triple(prefix, highlighted, suffix)
}
@ -103,7 +106,7 @@ class EditorUtils(val editor: Editor) {
* Gets the selected code from the current editor.
* Returns null if there is no selection.
*/
fun getHighlightedCode(): RangeInFileWithContents? {
fun getHighlightedRIF(): RangeInFileWithContents? {
return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
val virtualFile =
FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null

View file

@ -1,337 +1,11 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.awt.event.*
import java.awt.geom.AffineTransform
import java.awt.geom.Path2D
import java.awt.geom.RoundRectangle2D
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.ListDataListener
import javax.swing.plaf.basic.BasicComboBoxUI
import kotlin.math.max
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
const val MAIN_FONT_SIZE = 13
const val DOWN_ARROW = " ▾"
fun makeTextArea(): JTextArea {
val textArea =
CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(6, 8, 2, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
fun makePanel(
project: Project,
customPanelRef: Ref<CustomPanel>,
textArea: JTextArea,
inlayRef: Ref<Disposable>,
comboBoxRef: Ref<JComboBox<String>>,
leftInset: Int,
modelTitles: List<String>,
onEnter: () -> Unit,
onCancel: () -> Unit,
onAccept: () -> Unit,
onReject: () -> Unit
): JPanel {
val topPanel =
ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
background = JBColor(0x20888888, 0x20888888)
isOpaque = false
}
val panel =
CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
)
.apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
setup()
}
customPanelRef.set(panel)
textArea.addComponentListener(
object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
topPanel.add(panel, "grow, gap 0!")
return topPanel
}
fun openInlineEdit(project: Project?, editor: Editor) {
if (project == null) return
// Don't open in terminal
if (EditorUtils(editor).isTerminal()) {
return
}
val manager = EditorComponentInlaysManager.from(editor, true)
// Get list of model titles
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val modelsByRole =
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
modelsByRole.castNestedOrNull<List<*>>(role)
?.mapNotNull { it.castNestedOrNull<String>("title") }
?.let(modelTitles::addAll)
}
// This is a hacky way to not complicate getting model titles with coroutines
// 1500 feels like way upper limit of "would be weird if panel showed up after that long"
// And should always allow enough time to load config
val maxWaitTime = 1500
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
Thread.sleep(20)
}
// Get highlighted range
val selectionModel = editor.selectionModel
val startOffset = selectionModel.selectionStart
val endOffset = selectionModel.selectionEnd
val startLineNumber = editor.document.getLineNumber(startOffset)
var endLineNumber = editor.document.getLineNumber(endOffset)
// Doesn't seem to be any built-in methods to check for a line selection that contains trailing
// newlines.
// The only case this matters is when a user double-clicks to highlight a full line. Without this
// check.
// the highlighted range will continue to the following line.
val isSingleLineSelection =
endLineNumber > startLineNumber &&
endLineNumber < editor.document.lineCount &&
editor.document.getLineStartOffset(endLineNumber) == endOffset
if (isSingleLineSelection) {
endLineNumber--
}
val prefix = editor.document.getText(TextRange(0, startOffset))
val highlighted = editor.document.getText(TextRange(startOffset, endOffset))
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
// Un-highlight the selected text
selectionModel.removeSelection()
// Get indentation width in pixels
val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
val lineStart = editor.document.getLineStartOffset(indentationLineNum)
val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth =
editor.contentComponent
.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
.charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
val customPanelRef = Ref<CustomPanel>()
// Create text area, attach key listener
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
startLineNumber,
endLineNumber,
{
inlayRef.get()?.dispose()
},
{
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
},
null,
null
)
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
customPanelRef.get().enter()
diffStreamHandler.streamDiffLinesToEditor(
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
)
}
val panel =
makePanel(
project,
customPanelRef,
textArea,
inlayRef,
comboBoxRef,
leftInset,
modelTitles,
{ onEnter() },
{
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
},
{
diffStreamService.accept(editor)
inlayRef.get().dispose()
},
{
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNumber, panel, true)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
// Add key listener to text area
textArea.addKeyListener(
object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an
// unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
})
// Listen for changes to textarea line count
textArea.document.addDocumentListener(
object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
textArea.requestFocus()
}
/**
* Adapted from
* https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
*/
class InlineEditAction : AnAction(), DumbAware {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = true
@ -347,417 +21,4 @@ class InlineEditAction : AnAction(), DumbAware {
val project = e.getData(PlatformDataKeys.PROJECT) ?: return
openInlineEdit(project, editor)
}
}
class CustomPanel(
layout: MigLayout,
project: Project,
modelTitles: List<String>,
comboBoxRef: Ref<JComboBox<String>>,
private val onEnter: () -> Unit,
private val onCancel: () -> Unit,
private val onAccept: () -> Unit,
private val onReject: () -> Unit,
private val textArea: JTextArea
) : JPanel(layout) {
private val shadowSize = 5
private val cornerRadius = 8
private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
private val borderColor = Color(128, 128, 128, 128)
private val borderThickness = 1
private val triangleSize = 6
private val rightMargin = 3.0
private val closeButton: JComponent = createCloseButton()
private val originalTextColor: Color = textArea.foreground
private val greyTextColor: Color = Color(128, 128, 128, 200)
var isFinished = false
init {
isOpaque = false
add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
background = Color(0, 0, 0, 0)
border = JBUI.Borders.empty(2, 6, 2, 0)
toolTipText = "`esc` to cancel"
isOpaque = false
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
cursor = Cursor(Cursor.HAND_CURSOR)
}
override fun mouseExited(e: MouseEvent) {
cursor = Cursor.getDefaultCursor()
}
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
}
}
private val subPanelA: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown =
JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
border = JBUI.Borders.empty(8)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
preferredSize = Dimension(200, 30)
renderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val component =
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (component is JLabel) {
component.border = JBUI.Borders.empty(4, 6)
}
return component
}
}.apply {
horizontalAlignment = SwingConstants.LEFT
}
selectedIndex =
if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)
if (index != -1) index else 0
}
} ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel =
(selectedItem as String).removeSuffix(DOWN_ARROW)
}
}
comboBoxRef.set(dropdown)
val rightButton =
CustomButton("⏎ Enter") { onEnter() }
.apply {
background = globalScheme.defaultForeground
foreground = globalScheme.defaultBackground
border = JBUI.Borders.empty(2, 6)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(rightButton, "align right")
}
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
add(dropdown, "align left")
add(rightPanel, "align right")
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel =
JPanel(BorderLayout()).apply {
isOpaque = false
val progressBar = JProgressBar().apply { isIndeterminate = true }
add(progressBar, BorderLayout.CENTER)
border = JBUI.Borders.empty(0, 0, 16, 12)
}
private val subPanelC: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel =
JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.emptyLeft(4)
}
val leftButton =
CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
.apply {
background = JBColor(0x30FF0000, 0x30FF0000)
}
val rightButton =
CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
.apply {
background = JBColor(0x3000FF00, 0x3000FF00)
}
val rightPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = JBUI.Borders.empty()
}
add(leftLabel, "align left")
add(rightPanel, "align right")
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
}
fun setup() {
remove(subPanelB)
remove(subPanelC)
add(subPanelA, "grow, gap 0!")
isFinished = false
revalidate()
repaint()
textArea.foreground = originalTextColor
}
fun enter() {
remove(subPanelA)
remove(subPanelC)
add(subPanelB, "grow, gap 0!")
revalidate()
repaint()
}
fun finish() {
remove(subPanelB)
add(subPanelC, "grow, gap 0!")
revalidate()
repaint()
isFinished = true
textArea.foreground = greyTextColor
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val w = width - shadowSize
val h = height - shadowSize
// Create the shape for the tooltip/triangle
val shape = Path2D.Double()
shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
shape.quadTo(
borderThickness / 2.0,
borderThickness / 2.0,
cornerRadius.toDouble(),
borderThickness / 2.0
)
shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
borderThickness / 2.0,
w - borderThickness / 2.0 - rightMargin,
cornerRadius.toDouble()
)
shape.lineTo(
w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
h - triangleSize.toDouble(),
w - cornerRadius.toDouble() - rightMargin,
h - triangleSize.toDouble()
)
shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
shape.lineTo(borderThickness / 2.0, h.toDouble())
shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
// Draw shadow
g2.color = shadowColor
g2.fill(
shape.createTransformedShape(
AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
)
)
// Draw main shape
g2.color = background
g2.fill(shape)
// Draw border
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.draw(shape)
}
}
class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
private var isHovered = false
init {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.empty(2, 6)
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect =
RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
g2.color = background
g2.fill(roundRect)
g2.color = foreground
g2.drawString(
text,
(width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat()
)
}
}
class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
init {
setRows(rows)
setColumns(columns)
}
override fun paintComponent(g: Graphics) {
// Draw placeholder
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions...", 8, 20)
}
super.paintComponent(g)
}
}
class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
override fun getPreferredSize(): Dimension {
val prefSize = super.getPreferredSize()
val insets = getInsets()
prefSize.width += insets.left + insets.right
prefSize.height += insets.top + insets.bottom
return prefSize
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
}
}
class TransparentArrowButtonUI : BasicComboBoxUI() {
override fun createArrowButton() =
JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun getInsets(): Insets {
return JBUI.insetsLeft(6)
}
override fun installUI(c: JComponent?) {
super.installUI(c)
comboBox.isOpaque = false
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
comboBox.background = defaultBackground
// Modify the ComboBoxModel to include the down symbol
val originalModel = comboBox.model
comboBox.model =
object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item$DOWN_ARROW"
}
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
}
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
// Do nothing to prevent painting the background
}
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
val renderer = comboBox.renderer
val item = comboBox.selectedItem
if (item != null) {
val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
c.font = comboBox.font
c.foreground = Color(156, 163, 175) // text-gray-400
c.background = comboBox.background
if (c is JComponent) {
c.isOpaque = false
}
val currentValuePane = currentValuePane
currentValuePane.paintComponent(
g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
)
}
}
}
}

View file

@ -0,0 +1,746 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.awt.event.*
import java.awt.geom.AffineTransform
import java.awt.geom.Path2D
import java.awt.geom.RoundRectangle2D
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.ListDataListener
import javax.swing.plaf.basic.BasicComboBoxUI
import kotlin.math.max
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
const val MAIN_FONT_SIZE = 13
const val DOWN_ARROW = " ▾"
const val MAX_MODEL_WAIT_TIME = 1500
/**
* Fetches and combines available model titles from both "edit" and "chat" roles.
* Edit models are prioritized and appear first in the returned list.
* Handles duplicate models by only including them once (prioritizing edit role).
*
* @param continuePluginService The service used to fetch config information
* @return List of model titles with edit models first, duplicates removed
* @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds
*/
fun getModelTitles(continuePluginService: ContinuePluginService): List<String> {
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val modelsByRole =
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
// Get edit models first
val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
// Then get chat models
val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
// Add edit models first, then chat models (avoiding duplicates)
modelTitles.addAll(editModels)
modelTitles.addAll(chatModels.filter { it !in editModels })
}
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) {
Thread.sleep(20)
}
return modelTitles
}
fun makeTextArea(): JTextArea {
val textArea =
CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(6, 8, 2, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
fun makePanel(
project: Project,
customPanelRef: Ref<CustomPanel>,
textArea: JTextArea,
inlayRef: Ref<Disposable>,
comboBoxRef: Ref<JComboBox<String>>,
leftInset: Int,
modelTitles: List<String>,
onEnter: () -> Unit,
onCancel: () -> Unit,
onAccept: () -> Unit,
onReject: () -> Unit
): JPanel {
val topPanel =
ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
background = JBColor(0x20888888, 0x20888888)
isOpaque = false
}
val panel =
CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
)
.apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
setup()
}
customPanelRef.set(panel)
textArea.addComponentListener(
object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
topPanel.add(panel, "grow, gap 0!")
return topPanel
}
fun openInlineEdit(project: Project?, editor: Editor) {
if (project == null) return
val editorUtils = EditorUtils(editor)
// Don't open in terminal
if (editorUtils.isTerminal()) {
return
}
val manager = EditorComponentInlaysManager.from(editor, true)
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = getModelTitles(continuePluginService)
val highlightedRIF = editorUtils.getHighlightedRIF() ?: return
val (startLineNumber, endLineNumber) = highlightedRIF.lines
val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets
val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
editorUtils.removeSelection()
// Get indentation width in pixels
val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
val lineStart = editor.document.getLineStartOffset(indentationLineNum)
val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth =
editor.contentComponent
.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
.charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
val customPanelRef = Ref<CustomPanel>()
// Create text area, attach key listener
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
startLineNumber,
endLineNumber,
{
inlayRef.get()?.dispose()
},
{
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
},
null,
null
)
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
customPanelRef.get().enter()
diffStreamHandler.streamDiffLinesToEditor(
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
)
}
val panel =
makePanel(
project,
customPanelRef,
textArea,
inlayRef,
comboBoxRef,
leftInset,
modelTitles,
{ onEnter() },
{
diffStreamService.reject(editor)
editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset)
},
{
diffStreamService.accept(editor)
inlayRef.get().dispose()
},
{
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNumber, panel, true)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
// Add key listener to text area
textArea.addKeyListener(
object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
editorUtils.editor.selectionModel.setSelection(
highlightedStartOffset,
highlightedEndOffset
)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an
// unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
})
// Listen for changes to textarea line count
textArea.document.addDocumentListener(
object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
textArea.requestFocus()
}
class CustomPanel(
layout: MigLayout,
project: Project,
modelTitles: List<String>,
comboBoxRef: Ref<JComboBox<String>>,
private val onEnter: () -> Unit,
private val onCancel: () -> Unit,
private val onAccept: () -> Unit,
private val onReject: () -> Unit,
private val textArea: JTextArea
) : JPanel(layout) {
private val shadowSize = 5
private val cornerRadius = 8
private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
private val borderColor = Color(128, 128, 128, 128)
private val borderThickness = 1
private val triangleSize = 6
private val rightMargin = 3.0
private val closeButton: JComponent = createCloseButton()
private val originalTextColor: Color = textArea.foreground
private val greyTextColor: Color = Color(128, 128, 128, 200)
var isFinished = false
init {
isOpaque = false
add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
background = Color(0, 0, 0, 0)
border = JBUI.Borders.empty(2, 6, 2, 0)
toolTipText = "`esc` to cancel"
isOpaque = false
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
cursor = Cursor(Cursor.HAND_CURSOR)
}
override fun mouseExited(e: MouseEvent) {
cursor = Cursor.getDefaultCursor()
}
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
}
}
private val subPanelA: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown =
JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
border = JBUI.Borders.empty(8)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
preferredSize = Dimension(200, 30)
renderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val component =
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (component is JLabel) {
component.border = JBUI.Borders.empty(4, 6)
}
return component
}
}.apply {
horizontalAlignment = SwingConstants.LEFT
}
selectedIndex =
if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)
if (index != -1) index else 0
}
} ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel =
(selectedItem as String).removeSuffix(DOWN_ARROW)
}
}
comboBoxRef.set(dropdown)
val rightButton =
CustomButton("⏎ Enter") { onEnter() }
.apply {
background = JBColor.namedColor("Button.startBackground")
foreground = JBColor.namedColor("Button.foreground")
border = JBUI.Borders.empty(2, 6)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(rightButton, "align right")
}
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
add(dropdown, "align left")
add(rightPanel, "align right")
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel =
JPanel(BorderLayout()).apply {
isOpaque = false
val progressBar = JProgressBar().apply { isIndeterminate = true }
add(progressBar, BorderLayout.CENTER)
border = JBUI.Borders.empty(0, 0, 16, 12)
}
private val subPanelC: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel =
JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.emptyLeft(4)
}
val leftButton =
CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
.apply {
background = Color(0, 0, 0, 0)
foreground = JBColor.foreground()
border = JBUI.Borders.empty(2, 6)
}
val rightButton =
CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
.apply {
background = JBColor.namedColor("Button.startBackground")
foreground = JBColor.namedColor("Button.foreground")
border = JBUI.Borders.empty(2, 6)
}
val rightPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = JBUI.Borders.empty()
}
add(leftLabel, "align left")
add(rightPanel, "align right")
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
}
fun setup() {
remove(subPanelB)
remove(subPanelC)
add(subPanelA, "grow, gap 0!")
isFinished = false
revalidate()
repaint()
textArea.foreground = originalTextColor
}
fun enter() {
remove(subPanelA)
remove(subPanelC)
add(subPanelB, "grow, gap 0!")
revalidate()
repaint()
}
fun finish() {
remove(subPanelB)
add(subPanelC, "grow, gap 0!")
revalidate()
repaint()
isFinished = true
textArea.foreground = greyTextColor
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val w = width - shadowSize
val h = height - shadowSize
// Create the shape for the tooltip/triangle
val shape = Path2D.Double()
shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
shape.quadTo(
borderThickness / 2.0,
borderThickness / 2.0,
cornerRadius.toDouble(),
borderThickness / 2.0
)
shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
borderThickness / 2.0,
w - borderThickness / 2.0 - rightMargin,
cornerRadius.toDouble()
)
shape.lineTo(
w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
h - triangleSize.toDouble(),
w - cornerRadius.toDouble() - rightMargin,
h - triangleSize.toDouble()
)
shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
shape.lineTo(borderThickness / 2.0, h.toDouble())
shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
// Draw shadow
g2.color = shadowColor
g2.fill(
shape.createTransformedShape(
AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
)
)
// Draw main shape
g2.color = background
g2.fill(shape)
// Draw border
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.draw(shape)
}
}
class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
private var isHovered = false
init {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.empty(2, 6)
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect =
RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
g2.color = background
g2.fill(roundRect)
g2.color = foreground
g2.drawString(
text,
(width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat()
)
}
}
class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
init {
setRows(rows)
setColumns(columns)
}
override fun paintComponent(g: Graphics) {
// Draw placeholder
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions...", 8, 20)
}
super.paintComponent(g)
}
}
class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
override fun getPreferredSize(): Dimension {
val prefSize = super.getPreferredSize()
val insets = getInsets()
prefSize.width += insets.left + insets.right
prefSize.height += insets.top + insets.bottom
return prefSize
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
}
}
class TransparentArrowButtonUI : BasicComboBoxUI() {
override fun createArrowButton() =
JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun getInsets(): Insets {
return JBUI.insetsLeft(6)
}
override fun installUI(c: JComponent?) {
super.installUI(c)
comboBox.isOpaque = false
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
comboBox.background = defaultBackground
// Modify the ComboBoxModel to include the down symbol
val originalModel = comboBox.model
comboBox.model =
object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item$DOWN_ARROW"
}
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
}
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
// Do nothing to prevent painting the background
}
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
val renderer = comboBox.renderer
val item = comboBox.selectedItem
if (item != null) {
val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
c.font = comboBox.font
c.foreground = Color(156, 163, 175) // text-gray-400
c.background = comboBox.background
if (c is JComponent) {
c.isOpaque = false
}
val currentValuePane = currentValuePane
currentValuePane.paintComponent(
g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
)
}
}
}

View file

@ -12,22 +12,43 @@ import com.intellij.openapi.util.TextRange
class RangeInFileWithContents(
val filepath: String,
val range: Range,
val contents: String
val contents: String,
val document: Document
) {
/**
* Returns the absolute document offset for the start position
* The absolute document offset for the start position
*/
fun getStartOffset(document: Document): Int {
return document.getLineStartOffset(range.start.line) + range.start.character
}
val startOffset: Int
get() = document.getLineStartOffset(range.start.line) + range.start.character
/**
* Returns the absolute document offset for the end position
* The absolute document offset for the end position
*/
fun getEndOffset(document: Document): Int {
return document.getLineStartOffset(range.end.line) + range.end.character
}
val endOffset: Int
get() = document.getLineStartOffset(range.end.line) + range.end.character
/**
* The line number where the highlighted range starts (zero-based)
*/
val startLine: Int
get() = range.start.line
/**
* The line number where the highlighted range ends (zero-based)
* This already accounts for proper line ending calculations.
*/
val endLine: Int
get() = range.end.line
/**
* Both the start and end line numbers of the highlighted range as a pair
*/
val lines: Pair<Int, Int>
get() = Pair(startLine, endLine)
val offsets: Pair<Int, Int>
get() = Pair(startOffset, endOffset)
companion object {
/**
@ -45,6 +66,13 @@ class RangeInFileWithContents(
val startChar = selectionStart - document.getLineStartOffset(startLine)
val endChar = selectionEnd - document.getLineStartOffset(endLine)
// Adjust end line if it's a single line selection with trailing newlines
val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) {
endLine - 1
} else {
endLine
}
val selectedText = document.getText(
TextRange(selectionStart, selectionEnd)
)
@ -53,10 +81,30 @@ class RangeInFileWithContents(
filepath,
Range(
Position(startLine, startChar),
Position(endLine, endChar)
Position(adjustedEndLine, endChar)
),
selectedText
selectedText,
document
)
}
/**
* Checks if the selection spans to the next line only because of trailing newlines.
* This matters when a user double-clicks to highlight a full line.
*
* @return true if the selection is actually a single line selection with trailing newline
*/
fun isSelectionWithTrailingNewline(
document: Document,
selectionStart: Int,
selectionEnd: Int
): Boolean {
val startLine = document.getLineNumber(selectionStart)
val endLine = document.getLineNumber(selectionEnd)
return endLine > startLine &&
endLine < document.lineCount &&
document.getLineStartOffset(endLine) == selectionEnd
}
}
}

View file

@ -166,7 +166,7 @@ class VerticalDiffBlock(
val rejectBtn =
createButton(
"${getAltKeyLabel()}${getShiftKeyLabel()}N",
JBColor(0x77FF0000, 0x77FF0000)
JBColor(0xFF0000, 0xFF0000)
).apply {
addActionListener {
handleReject()
@ -178,13 +178,14 @@ class VerticalDiffBlock(
createButton(
"${getAltKeyLabel()}${
getShiftKeyLabel()
}Y", JBColor(0x7700BB00, 0x7700BB00)
}Y", JBColor(0x00BB00, 0x00BB00)
).apply {
addActionListener {
handleAccept()
}
}
return Pair(acceptBtn, rejectBtn)
}

View file

@ -15,16 +15,6 @@ data class ApplyToFileParams(
val toolCallId: String?
)
data class AcceptDiffParams(
val filepath: String,
val streamId: String
)
data class RejectDiffParams(
val filepath: String,
val streamId: String
)
data class InsertAtCursorParams(
val text: String
)

View file

@ -244,10 +244,15 @@ data class StreamDiffLinesPayload(
val input: String,
val language: String?,
val modelTitle: String?,
val includeRulesInSystemMessage: Boolean
val includeRulesInSystemMessage: Boolean,
val fileUri: String?
)
data class AcceptOrRejectDiffPayload(
val filepath: String,
val streamId: String? = null
)
data class ShowFilePayload(
val filepath: String
)

View file

@ -78,9 +78,9 @@
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
text="Reject Diff" description="Reject Diff">
<keyboard-shortcut keymap="$default"
first-keystroke="shift ctrl DELETE"/>
first-keystroke="shift ctrl BACK_SPACE"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="shift meta DELETE"/>
first-keystroke="shift meta BACK_SPACE"/>
<override-text place="GoToAction" text="Continue: Reject Diff"/>
</action>

View file

@ -1,16 +1,16 @@
{
"name": "continue",
"version": "1.1.36",
"version": "1.1.39",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.36",
"version": "1.1.39",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",
"@types/node-fetch": "^2.6.11",
@ -64,7 +64,7 @@
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@nestjs/common": "^11.0.16",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@openapitools/openapi-generator-cli": "^2.20.0",
"@types/chai": "^5.0.1",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
@ -107,9 +107,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -708,9 +708,10 @@
}
},
"node_modules/@continuedev/fetch": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz",
"integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==",
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
"integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
@ -1444,14 +1445,28 @@
"resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz",
"integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg=="
},
"node_modules/@nestjs/axios": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz",
"integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@nestjs/common": "^10.0.0 || ^11.0.0",
"axios": "^1.3.1",
"rxjs": "^7.0.0"
}
},
"node_modules/@nestjs/common": {
"version": "11.0.16",
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.16.tgz",
"integrity": "sha512-agvuQ8su4aZ+PVxAmY89odG1eR97HEQvxPmTMdDqyvDWzNerl7WQhUEd+j4/UyNWcF1or1UVcrtPj52x+eUSsA==",
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.1.tgz",
"integrity": "sha512-crzp+1qeZ5EGL0nFTPy9NrVMAaUWewV5AwtQyv6SQ9yQPXwRl9W9hm1pt0nAtUu5QbYMbSuo7lYcF81EjM+nCA==",
"dev": true,
"license": "MIT",
"dependencies": {
"file-type": "20.5.0",
"iterare": "1.2.1",
"load-esm": "1.0.2",
"tslib": "2.8.1",
"uid": "2.0.2"
},
@ -1460,9 +1475,8 @@
"url": "https://opencollective.com/nest"
},
"peerDependencies": {
"class-transformer": "*",
"class-validator": "*",
"file-type": "^20.4.1",
"class-transformer": ">=0.4.1",
"class-validator": ">=0.13.2",
"reflect-metadata": "^0.1.12 || ^0.2.0",
"rxjs": "^7.1.0"
},
@ -1475,6 +1489,58 @@
}
}
},
"node_modules/@nestjs/core": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.1.tgz",
"integrity": "sha512-UFoUAgLKFT+RwHTANJdr0dF7p0qS9QjkaUPjg8aafnjM/qxxxrUVDB49nVvyMlk+Hr1+vvcNaOHbWWQBxoZcHA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@nuxt/opencollective": "0.4.1",
"fast-safe-stringify": "2.1.1",
"iterare": "1.2.1",
"path-to-regexp": "8.2.0",
"tslib": "2.8.1",
"uid": "2.0.2"
},
"engines": {
"node": ">= 20"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/nest"
},
"peerDependencies": {
"@nestjs/common": "^11.0.0",
"@nestjs/microservices": "^11.0.0",
"@nestjs/platform-express": "^11.0.0",
"@nestjs/websockets": "^11.0.0",
"reflect-metadata": "^0.1.12 || ^0.2.0",
"rxjs": "^7.1.0"
},
"peerDependenciesMeta": {
"@nestjs/microservices": {
"optional": true
},
"@nestjs/platform-express": {
"optional": true
},
"@nestjs/websockets": {
"optional": true
}
}
},
"node_modules/@nestjs/core/node_modules/path-to-regexp": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz",
"integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=16"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@ -1567,11 +1633,29 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@nuxt/opencollective": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz",
"integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"consola": "^3.2.3"
},
"bin": {
"opencollective": "bin/opencollective.js"
},
"engines": {
"node": "^14.18.0 || >=16.10.0",
"npm": ">=5.10.0"
}
},
"node_modules/@nuxtjs/opencollective": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz",
"integrity": "sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"chalk": "^4.1.0",
"consola": "^2.15.0",
@ -1585,11 +1669,19 @@
"npm": ">=5.0.0"
}
},
"node_modules/@nuxtjs/opencollective/node_modules/consola": {
"version": "2.15.3",
"resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz",
"integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==",
"dev": true,
"license": "MIT"
},
"node_modules/@nuxtjs/opencollective/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dev": true,
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
@ -1609,48 +1701,52 @@
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/@nuxtjs/opencollective/node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"dev": true
"dev": true,
"license": "BSD-2-Clause"
},
"node_modules/@nuxtjs/opencollective/node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/@openapitools/openapi-generator-cli": {
"version": "2.15.3",
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.15.3.tgz",
"integrity": "sha512-2UBnsDlMt36thhdXxisbA1qReVtbCaw+NCvXoslRXlaJBL4qkAmZUhNeDLNu3LCbwA2PASMWhJSqeLwgwMCitw==",
"version": "2.20.2",
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.20.2.tgz",
"integrity": "sha512-dNFwQcQu6+rmEWSJj4KUx468+p6Co7nfpVgi5QEfVhzKj7wBytz9GEhCN2qmVgtg3ZX8H6nxbXI8cjh7hAxAqg==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@nestjs/axios": "3.1.1",
"@nestjs/common": "10.4.6",
"@nestjs/core": "10.4.6",
"@nestjs/axios": "4.0.0",
"@nestjs/common": "11.1.1",
"@nestjs/core": "11.1.1",
"@nuxtjs/opencollective": "0.3.2",
"axios": "1.7.7",
"axios": "1.9.0",
"chalk": "4.1.2",
"commander": "8.3.0",
"compare-versions": "4.1.4",
"concurrently": "6.5.1",
"console.table": "0.10.0",
"fs-extra": "10.1.0",
"fs-extra": "11.3.0",
"glob": "9.3.5",
"inquirer": "8.2.6",
"lodash": "4.17.21",
"proxy-agent": "6.4.0",
"reflect-metadata": "0.1.13",
"rxjs": "7.8.1",
"proxy-agent": "6.5.0",
"reflect-metadata": "0.2.2",
"rxjs": "7.8.2",
"tslib": "2.8.1"
},
"bin": {
@ -1664,97 +1760,6 @@
"url": "https://opencollective.com/openapi_generator"
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/axios": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz",
"integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
"axios": "^1.3.1",
"rxjs": "^6.0.0 || ^7.0.0"
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common": {
"version": "10.4.6",
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.6.tgz",
"integrity": "sha512-KkezkZvU9poWaNq4L+lNvx+386hpOxPJkfXBBeSMrcqBOx8kVr36TGN2uYkF4Ta4zNu1KbCjmZbc0rhHSg296g==",
"dev": true,
"dependencies": {
"iterare": "1.2.1",
"tslib": "2.7.0",
"uid": "2.0.2"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/nest"
},
"peerDependencies": {
"class-transformer": "*",
"class-validator": "*",
"reflect-metadata": "^0.1.12 || ^0.2.0",
"rxjs": "^7.1.0"
},
"peerDependenciesMeta": {
"class-transformer": {
"optional": true
},
"class-validator": {
"optional": true
}
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common/node_modules/tslib": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
"dev": true
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/core": {
"version": "10.4.6",
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-10.4.6.tgz",
"integrity": "sha512-zXVPxCNRfO6gAy0yvEDjUxE/8gfZICJFpsl2lZAUH31bPb6m+tXuhUq2mVCTEltyMYQ+DYtRe+fEYM2v152N1g==",
"dev": true,
"hasInstallScript": true,
"dependencies": {
"@nuxtjs/opencollective": "0.3.2",
"fast-safe-stringify": "2.1.1",
"iterare": "1.2.1",
"path-to-regexp": "3.3.0",
"tslib": "2.7.0",
"uid": "2.0.2"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/nest"
},
"peerDependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/microservices": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/websockets": "^10.0.0",
"reflect-metadata": "^0.1.12 || ^0.2.0",
"rxjs": "^7.1.0"
},
"peerDependenciesMeta": {
"@nestjs/microservices": {
"optional": true
},
"@nestjs/platform-express": {
"optional": true
},
"@nestjs/websockets": {
"optional": true
}
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/core/node_modules/tslib": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
"dev": true
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
@ -1764,6 +1769,21 @@
"balanced-match": "^1.0.0"
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/fs-extra": {
"version": "11.3.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz",
"integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==",
"dev": true,
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=14.14"
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/glob": {
"version": "9.3.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz",
@ -1806,18 +1826,6 @@
"node": ">=8"
}
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/path-to-regexp": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz",
"integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==",
"dev": true
},
"node_modules/@openapitools/openapi-generator-cli/node_modules/reflect-metadata": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz",
"integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==",
"dev": true
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@ -1959,7 +1967,6 @@
"integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"debug": "^4.4.0",
"fflate": "^0.8.2",
@ -1974,12 +1981,11 @@
}
},
"node_modules/@tokenizer/inflate/node_modules/debug": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
"integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
"integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ms": "^2.1.3"
},
@ -1997,8 +2003,7 @@
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
"integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@tootallnate/once": {
"version": "2.0.0",
@ -2012,7 +2017,8 @@
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
"integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/@types/body-parser": {
"version": "1.19.5",
@ -3078,12 +3084,10 @@
}
},
"node_modules/agent-base": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
"integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==",
"dependencies": {
"debug": "^4.3.4"
},
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz",
"integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==",
"license": "MIT",
"engines": {
"node": ">= 14"
}
@ -3343,6 +3347,7 @@
"resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz",
"integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==",
"dev": true,
"license": "MIT",
"dependencies": {
"tslib": "^2.0.1"
},
@ -3377,9 +3382,10 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
"version": "1.7.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
"integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==",
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
@ -3434,6 +3440,7 @@
"resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz",
"integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
@ -4606,10 +4613,14 @@
}
},
"node_modules/consola": {
"version": "2.15.3",
"resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz",
"integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==",
"dev": true
"version": "3.4.2",
"resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",
"integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^14.18.0 || >=16.10.0"
}
},
"node_modules/console-control-strings": {
"version": "1.1.0",
@ -4972,6 +4983,7 @@
"resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz",
"integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ast-types": "^0.13.4",
"escodegen": "^2.1.0",
@ -5460,6 +5472,7 @@
"resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",
"integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"esprima": "^4.0.1",
"estraverse": "^5.2.0",
@ -5481,6 +5494,7 @@
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
"integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=4.0"
}
@ -5649,6 +5663,7 @@
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"dev": true,
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
@ -5956,7 +5971,8 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/fastq": {
"version": "1.17.1",
@ -6001,8 +6017,7 @@
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/figures": {
"version": "3.2.0",
@ -6041,12 +6056,11 @@
}
},
"node_modules/file-type": {
"version": "20.4.1",
"resolved": "https://registry.npmjs.org/file-type/-/file-type-20.4.1.tgz",
"integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==",
"version": "20.5.0",
"resolved": "https://registry.npmjs.org/file-type/-/file-type-20.5.0.tgz",
"integrity": "sha512-BfHZtG/l9iMm4Ecianu7P8HRD2tBHLtjXinm4X62XBOYzi7CYA7jyqfJzOvXHqzVrVPYqBo2/GvbARMaaJkKVg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@tokenizer/inflate": "^0.2.6",
"strtok3": "^10.2.0",
@ -6491,15 +6505,15 @@
}
},
"node_modules/get-uri": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz",
"integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==",
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.4.tgz",
"integrity": "sha512-E1b1lFFLvLgak2whF2xDBcOy6NLVGZBqqjJjsIhvopKfWWEi64pLVTWWehV8KlLerZkfNTA95sTe2OdJKm1OzQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"basic-ftp": "^5.0.2",
"data-uri-to-buffer": "^6.0.2",
"debug": "^4.3.4",
"fs-extra": "^11.2.0"
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
@ -6510,24 +6524,11 @@
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
"integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/get-uri/node_modules/fs-extra": {
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz",
"integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==",
"dev": true,
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=14.14"
}
},
"node_modules/getpass": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
@ -6986,11 +6987,12 @@
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz",
"integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"license": "MIT",
"dependencies": {
"agent-base": "^7.0.2",
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
@ -7921,6 +7923,26 @@
"uc.micro": "^1.0.1"
}
},
"node_modules/load-esm": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.2.tgz",
"integrity": "sha512-nVAvWk/jeyrWyXEAs84mpQCYccxRqgKY4OznLuJhJCa0XsPSfdOIr2zvBZEj3IHEHbX97jjscKRRV539bW0Gpw==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/Borewit"
},
{
"type": "buymeacoffee",
"url": "https://buymeacoffee.com/borewit"
}
],
"license": "MIT",
"engines": {
"node": ">=13.2.0"
}
},
"node_modules/locate-path": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
@ -9267,6 +9289,7 @@
"resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz",
"integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
@ -9965,31 +9988,33 @@
}
},
"node_modules/pac-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.0.2.tgz",
"integrity": "sha512-BFi3vZnO9X5Qt6NRz7ZOaPja3ic0PhlsmCRYLOpN11+mWBCR6XJDqW5RF3j8jm4WGGQZtBA+bTfxYzeKW73eHg==",
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz",
"integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@tootallnate/quickjs-emscripten": "^0.23.0",
"agent-base": "^7.0.2",
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"get-uri": "^6.0.1",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.5",
"https-proxy-agent": "^7.0.6",
"pac-resolver": "^7.0.1",
"socks-proxy-agent": "^8.0.4"
"socks-proxy-agent": "^8.0.5"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/pac-proxy-agent/node_modules/socks-proxy-agent": {
"version": "8.0.4",
"resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz",
"integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==",
"version": "8.0.5",
"resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
"integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.1",
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"socks": "^2.8.3"
},
@ -10002,6 +10027,7 @@
"resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz",
"integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==",
"dev": true,
"license": "MIT",
"dependencies": {
"degenerator": "^5.0.0",
"netmask": "^2.0.2"
@ -10194,7 +10220,6 @@
"integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@ -10680,19 +10705,20 @@
}
},
"node_modules/proxy-agent": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.4.0.tgz",
"integrity": "sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==",
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz",
"integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.0.2",
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"https-proxy-agent": "^7.0.6",
"lru-cache": "^7.14.1",
"pac-proxy-agent": "^7.0.1",
"pac-proxy-agent": "^7.1.0",
"proxy-from-env": "^1.1.0",
"socks-proxy-agent": "^8.0.2"
"socks-proxy-agent": "^8.0.5"
},
"engines": {
"node": ">= 14"
@ -10703,17 +10729,19 @@
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
"integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/proxy-agent/node_modules/socks-proxy-agent": {
"version": "8.0.4",
"resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz",
"integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==",
"version": "8.0.5",
"resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
"integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.1",
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"socks": "^2.8.3"
},
@ -11077,11 +11105,11 @@
}
},
"node_modules/reflect-metadata": {
"version": "0.1.14",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.14.tgz",
"integrity": "sha512-ZhYeb6nRaXCfhnndflDK8qI6ZQ/YcWZCISRAWICW9XYqMUwjZM9Z0DveWX/ABN01oxSHwVxKQmxeYZSsm0jh5A==",
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"dev": true,
"peer": true
"license": "Apache-2.0"
},
"node_modules/regenerator-runtime": {
"version": "0.14.1",
@ -11418,10 +11446,11 @@
"integrity": "sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA=="
},
"node_modules/rxjs": {
"version": "7.8.1",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz",
"integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==",
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
}
@ -12168,7 +12197,6 @@
"integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@tokenizer/token": "^0.3.0",
"peek-readable": "^7.0.0"
@ -12824,7 +12852,6 @@
"integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@tokenizer/token": "^0.3.0",
"ieee754": "^1.2.1"
@ -13082,7 +13109,6 @@
"integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.38",
"version": "1.1.39",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -105,7 +105,7 @@
"continue.enableQuickActions": {
"type": "boolean",
"default": false,
"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)"
"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)"
},
"continue.enableTabAutocomplete": {
"type": "boolean",
@ -631,7 +631,7 @@
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@nestjs/common": "^11.0.16",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@openapitools/openapi-generator-cli": "^2.20.0",
"@types/chai": "^5.0.1",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
@ -661,7 +661,7 @@
},
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",
"@types/node-fetch": "^2.6.11",

View file

@ -97,6 +97,7 @@ async function processDiff(
action: "accept" | "reject",
sidebar: ContinueGUIWebviewViewProvider,
ide: VsCodeIde,
core: Core,
verticalDiffManager: VerticalDiffManager,
newFileUri?: string,
streamId?: string,
@ -121,6 +122,9 @@ async function processDiff(
// Clear vertical diffs depending on action
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
if (action === "reject") {
core.invoke("cancelApply", undefined);
}
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
@ -236,18 +240,20 @@ const getCommandsMap: (
"accept",
sidebar,
ide,
core,
verticalDiffManager,
newFileUri,
streamId,
),
"continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
processDiff(
"reject",
sidebar,
ide,
core,
verticalDiffManager,
newFilepath,
newFileUri,
streamId,
),
"continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
@ -573,11 +579,15 @@ const getCommandsMap: (
await addEntireFileToContext(
vscode.Uri.parse(fileUri),
sidebar.webviewProtocol,
ide.ideUtils
ide.ideUtils,
);
}
} else {
await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
await addEntireFileToContext(
uri,
sidebar.webviewProtocol,
ide.ideUtils,
);
}
}
},

View file

@ -1,5 +1,4 @@
import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { streamDiffLines } from "core/edit/streamDiffLines";
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
import { getMarkdownLanguageTagForFile } from "core/util";
@ -31,7 +30,6 @@ export class VerticalDiffManager {
logDiffs: DiffLine[] | undefined;
constructor(
private readonly configHandler: ConfigHandler,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly editDecorationManager: EditDecorationManager,
) {
@ -43,12 +41,12 @@ export class VerticalDiffManager {
startLine: number,
endLine: number,
options: VerticalDiffHandlerOptions,
) {
): VerticalDiffHandler | undefined {
if (this.fileUriToHandler.has(fileUri)) {
this.fileUriToHandler.get(fileUri)?.clear(false);
this.fileUriToHandler.delete(fileUri);
}
const editor = vscode.window.activeTextEditor; // TODO
const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
const handler = new VerticalDiffHandler(
startLine,
@ -453,6 +451,7 @@ export class VerticalDiffManager {
language: getMarkdownLanguageTagForFile(fileUri),
onlyOneInsertion: !!onlyOneInsertion,
overridePrompt,
abortControllerId: fileUri,
});
for await (const line of stream) {

View file

@ -130,7 +130,6 @@ export class VsCodeExtension {
this.configHandler.loadConfig();
this.verticalDiffManager = new VerticalDiffManager(
this.configHandler,
this.sidebar.webviewProtocol,
this.editDecorationManager,
);

6
gui/package-lock.json generated
View file

@ -111,9 +111,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -211,7 +211,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -9,6 +9,7 @@ import ErrorPage from "./pages/error";
import Chat from "./pages/gui";
import History from "./pages/history";
import Stats from "./pages/stats";
import ThemePage from "./styles/ThemePage";
import { ROUTES } from "./util/navigation";
const router = createMemoryRouter([
@ -37,6 +38,10 @@ const router = createMemoryRouter([
path: ROUTES.CONFIG,
element: <ConfigPage />,
},
{
path: ROUTES.THEME,
element: <ThemePage />,
},
],
},
]);

View file

@ -3,6 +3,7 @@ import { useContext } from "react";
import { lightGray, vscForeground } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { isJetBrains } from "../../../util";
import { extractCommand } from "../utils/commandExtractor";
interface RunInTerminalButtonProps {
command: string;
@ -16,18 +17,6 @@ export function RunInTerminalButton({ command }: RunInTerminalButtonProps) {
return null;
}
// Extract just the command line (the line after $ or the first line)
function extractCommand(cmd: string): string {
// If the command contains a $ prompt, extract the line after it
if (cmd.includes("$")) {
const match = cmd.match(/\$\s*([^\n]+)/);
return match ? match[1].trim() : "";
}
// Otherwise, just take the first line
return cmd.split("\n")[0].trim();
}
function runInTerminal() {
// Extract just the command line
const extractedCommand = extractCommand(command);

View file

@ -44,14 +44,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) {
data-tooltip-id={id}
data-tooltip-delay-show={500}
>
<code
className="align-middle"
style={{
color: "var(--vscode-textLink-foreground)",
}}
>
{content}
</code>
<code className="text-link align-middle">{content}</code>
</span>
<ToolTip id={id} place="top" className="m-0 p-0">
<pre className="text-left">{processedContent ?? symbol.filepath}</pre>

View file

@ -0,0 +1,80 @@
import { extractCommand } from './commandExtractor';
describe('extractCommand', () => {
// Test basic command extraction
it('should extract command from $ prompt', () => {
expect(extractCommand('$ echo hello')).toBe('echo hello');
expect(extractCommand('$ echo hello')).toBe('echo hello');
expect(extractCommand('$echo hello')).toBe('echo hello');
});
// Test comment removal
it('should remove comments at beginning of lines', () => {
expect(extractCommand('# shell comment\necho hello')).toBe('echo hello');
expect(extractCommand('// js comment\necho hello')).toBe('echo hello');
expect(extractCommand('/* multi-line\ncomment */\necho hello')).toBe('echo hello');
});
// Test multiline comment removal
it('should remove multiline comments anywhere in the text', () => {
expect(extractCommand('echo /* comment */ hello')).toBe('echo hello');
expect(extractCommand('echo hello /* comment */')).toBe('echo hello');
expect(extractCommand('echo /* multiple\nline\ncomment */ hello')).toBe('echo hello');
});
// Test line continuation handling
it('should handle line continuations correctly', () => {
expect(extractCommand('echo hello && \\\necho world')).toBe('echo hello && echo world');
expect(extractCommand('echo hello | \\\ngrep h')).toBe('echo hello | grep h');
expect(extractCommand('echo hello \\\nworld')).toBe('echo hello world');
});
// Test complex command combinations
it('should handle complex command combinations', () => {
expect(extractCommand(`
# shell comment
echo hello /* inline comment */ && \\
// js comment
echo world
`)).toBe('echo hello && echo world');
});
// Test empty and whitespace handling
it('should handle empty and whitespace inputs', () => {
expect(extractCommand('')).toBe('');
expect(extractCommand(' \n \t ')).toBe('');
});
// Test comment-only inputs
it('should handle comment-only inputs', () => {
expect(extractCommand('/* comment */')).toBe('');
expect(extractCommand('# comment')).toBe('');
expect(extractCommand('// comment')).toBe('');
expect(extractCommand('/* multi\nline\ncomment */')).toBe('');
});
// Test inline comments
it('should handle inline comments correctly according to implementation', () => {
// But removes multiline comments even when inline
expect(extractCommand('/* inline */ echo hello world')).toBe('echo hello world');
});
// Test multiple line continuations
it('should handle multiple line continuations', () => {
expect(extractCommand(`
echo hello && \\
echo world && \\
echo test
`)).toBe('echo hello && echo world && echo test');
});
// Test nested line continuations
it('should handle nested line continuations', () => {
expect(extractCommand(`
echo hello && \\
(echo nested && \\
echo more) && \\
echo final
`)).toBe('echo hello && (echo nested && echo more) && echo final');
});
});

View file

@ -0,0 +1,50 @@
/**
* Extracts and processes command strings, handling comments and line continuations.
* @param cmd The command string to process
* @returns The processed command string
*/
export function extractCommand(cmd: string): string {
if (!cmd || cmd.trim() === '') {
return '';
}
// Remove multi-line comments (/* ... */) and replace with a single space
cmd = cmd.replace(/\/\*[\s\S]*?\*\//g, " ");
// Handle the $ prompt case first
if (cmd.includes("$")) {
const match = cmd.match(/\$\s*([^\n]+)/);
if (match) {
// Return just the command after $ without further processing
return match[1].trim();
}
}
// Process lines - remove single-line comments only at beginning of lines
const lines = cmd.split('\n')
.map(line => line.replace(/^\s*#.*$/, '').replace(/^\s*\/\/.*$/, ''))
.map(line => line.trim())
.filter(line => line);
// Join lines with proper handling of continuations
let result = '';
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
// Remove trailing continuation characters and join with next line
while (
(line.endsWith('&&') || line.endsWith('|') || line.endsWith('\\')) &&
i < lines.length - 1
) {
// Remove the continuation character(s) and any trailing spaces
line = line.replace(/(&&|\||\\)\s*$/, '').trim();
// Join with the next line
i++;
line += ' ' + lines[i];
}
result += line + ' ';
}
return result.trim().replace(/\s+/g, ' ');
}

View file

@ -1,5 +1,5 @@
import { XMarkIcon } from "@heroicons/react/24/outline";
import { useCallback, useEffect } from "react";
import React, { useCallback, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius } from "..";
@ -13,16 +13,30 @@ import {
} from "../../redux/slices/tabsSlice";
import { AppDispatch, RootState } from "../../redux/store";
import { loadSession, saveCurrentSession } from "../../redux/thunks/session";
import { varWithFallback } from "../../styles/theme";
// Haven't set up theme colors for tabs yet
// Will keep it simple and choose from existing ones. Comments show vars we could use
const tabBorderVar = varWithFallback("border"); // --vscode-tab-border
const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground
const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground
const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground
const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground
const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground
const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground
const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop
const TabBarContainer = styled.div`
display: flex;
flex-wrap: wrap;
flex-shrink: 0;
flex-grow: 0;
background-color: var(--vscode-tab-inactiveBackground);
background-color: ${tabBackgroundVar};
border-bottom: none;
position: relative;
margin-top: 2px;
max-height: 100px;
overflow: auto;
/* Hide scrollbar but keep functionality */
scrollbar-width: none;
@ -41,24 +55,18 @@ const Tab = styled.div<{ isActive: boolean }>`
max-width: 150px;
height: 25px;
background-color: ${(props) =>
props.isActive
? "var(--vscode-tab-activeBackground)"
: "var(--vscode-tab-inactiveBackground)"};
props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar};
color: ${(props) =>
props.isActive
? "var(--vscode-tab-activeForeground)"
: "var(--vscode-tab-inactiveForeground)"};
props.isActive ? tabSelectedForegroundVar : tabForegroundVar};
cursor: pointer;
border: 1px solid var(--vscode-tab-border);
border: 1px solid ${tabBorderVar};
border-bottom: ${(props) =>
props.isActive ? "none" : `1px solid var(--vscode-tab-border)`};
props.isActive ? "none" : `1px solid ${tabBorderVar}`};
user-select: none;
position: relative;
transition: background-color 0.2s;
border-top: ${(props) =>
props.isActive
? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)`
: `1px solid var(--vscode-tab-border)`};
props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`};
&:first-child {
border-left: none;
}
@ -68,13 +76,9 @@ const Tab = styled.div<{ isActive: boolean }>`
&:hover {
background-color: ${(props) =>
props.isActive
? "var(--vscode-tab-activeBackground)"
: "var(--vscode-tab-hoverBackground)"};
props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar};
color: ${(props) =>
props.isActive
? "var(--vscode-tab-activeForeground)"
: "var(--vscode-tab-hoverForeground)"};
props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar};
}
`;
@ -104,7 +108,7 @@ const CloseButton = styled.button`
&:hover {
opacity: 1;
background-color: var(--vscode-tab-hoverBackground);
background-color: ${tabHoverBackgroundVar};
}
${Tab}:hover & {
@ -119,33 +123,12 @@ const CloseButton = styled.button`
const TabBarSpace = styled.div`
flex: 1;
display: flex;
border-bottom: 1px solid var(--vscode-tab-border);
background-color: var(--vscode-tab-inactiveBackground);
border-bottom: 1px solid ${tabBorderVar};
background-color: ${tabBackgroundVar};
`;
const NewTabButton = styled.button`
display: flex;
align-items: center;
justify-content: center;
width: 35px;
height: 100%;
border: none;
background: transparent;
color: var(--vscode-tab-inactiveForeground);
cursor: pointer;
opacity: 0.7;
transition: opacity 0.2s;
&:hover {
opacity: 1;
background-color: var(--vscode-tab-hoverBackground);
color: var(--vscode-tab-hoverForeground);
}
`;
export function TabBar() {
export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
const dispatch = useDispatch<AppDispatch>();
const currentSession = useSelector((state: RootState) => state.session);
const currentSessionId = useSelector((state: RootState) => state.session.id);
const currentSessionTitle = useSelector(
(state: RootState) => state.session.title,
@ -160,7 +143,6 @@ export function TabBar() {
return Date.now().toString(36) + Math.random().toString(36).substring(2);
}, []);
// Handle session changes
useEffect(() => {
if (!currentSessionId) return;
@ -243,10 +225,13 @@ export function TabBar() {
}
};
return tabs.length === 1 ? (
<></>
) : (
<TabBarContainer>
return (
<TabBarContainer
ref={ref}
style={{
display: tabs.length === 1 ? "none" : "flex",
}}
>
{tabs.map((tab) => (
<Tab
key={tab.id}
@ -272,4 +257,4 @@ export function TabBar() {
</TabBarSpace>
</TabBarContainer>
);
}
});

View file

@ -4,12 +4,11 @@ import ReactMarkdown from "react-markdown";
import styled from "styled-components";
import {
CloseButton,
VSC_BACKGROUND_VAR,
defaultBorderRadius,
parseColorForHex,
vscBackground,
vscForeground,
} from "..";
import { varWithFallback } from "../../styles/theme";
interface TextDialogProps {
showDialog: boolean;
@ -22,7 +21,7 @@ const ScreenCover = styled.div`
position: fixed;
width: 100%;
height: 100%;
background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa;
background-color: ${varWithFallback("background")}aa;
z-index: 100000;
flex-direction: column;
`;

View file

@ -13,35 +13,24 @@ import {
} from "react";
import { HeaderButton, Input } from "..";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { useAppSelector } from "../../redux/hooks";
import {
Rectangle,
SearchMatch,
searchWithinContainer,
} from "./findWidgetSearch";
import useDebounceValue from "./useDebounce";
import { useElementSize } from "./useElementSize";
interface SearchMatch {
index: number;
textNode: Text;
overlayRectangle: Rectangle;
}
type ScrollToMatchOption = "closest" | "first" | "none";
const SEARCH_DEBOUNCE = 300;
const RESIZE_DEBOUNCE = 200;
interface Rectangle {
top: number;
left: number;
width: number;
height: number;
}
interface HighlightOverlayProps extends Rectangle {
interface HighlightOverlayProps {
rectangle: Rectangle;
isCurrent: boolean;
}
const HighlightOverlay = (props: HighlightOverlayProps) => {
const { isCurrent, top, left, width, height } = props;
const { top, left, width, height } = props.rectangle;
return (
<div
className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work
className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
key={`highlight-${top}-${left}`}
style={{
position: "absolute",
@ -56,6 +45,8 @@ const HighlightOverlay = (props: HighlightOverlayProps) => {
);
};
type ScrollToMatchOption = "closest" | "first" | "none";
/*
useFindWidget takes a container ref and returns
1. A widget that can be placed anywhere to search the contents of that container
@ -64,18 +55,22 @@ const HighlightOverlay = (props: HighlightOverlayProps) => {
Container must have relative positioning
*/
export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
export const useFindWidget = (
searchRef: RefObject<HTMLDivElement>,
headerRef: RefObject<HTMLDivElement>,
disabled: boolean,
) => {
// Search input, debounced
const [input, setInput] = useState<string>("");
const debouncedInput = useRef<string>("");
const inputRef = useRef<HTMLInputElement>(null);
const [currentValue, setCurrentValue] = useState<string>("");
const searchTerm = useDebounceValue(currentValue, 300);
// Widget open/closed state
const [open, setOpen] = useState<boolean>(false);
const openWidget = useCallback(() => {
setOpen(true);
inputRef?.current?.select();
}, [setOpen, inputRef]);
}, [inputRef]);
// Search settings and results
const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
@ -97,7 +92,7 @@ export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
behavior: "smooth",
});
},
[searchRef.current],
[searchRef],
);
const nextMatch = useCallback(() => {
@ -143,327 +138,166 @@ export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
}, [inputRef, matches, nextMatch]);
// Handle container resize changes - highlight positions must adjust
const [isResizing, setIsResizing] = useState(false);
useEffect(() => {
let timeoutId: NodeJS.Timeout | null = null;
if (!searchRef?.current) return;
const resizeObserver = new ResizeObserver((entries) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
setIsResizing(true);
timeoutId = setTimeout(() => {
setIsResizing(false);
}, RESIZE_DEBOUNCE);
});
resizeObserver.observe(searchRef.current);
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (searchRef.current) resizeObserver.unobserve(searchRef.current);
};
}, [searchRef.current]);
const { clientHeight: headerHeight, isResizing: headerResizing } =
useElementSize(headerRef);
const { isResizing: containerResizing } = useElementSize(searchRef);
const isResizing = useMemo(() => {
return containerResizing || headerResizing;
}, [containerResizing, headerResizing]);
// Main function for finding matches and generating highlight overlays
const refreshSearch = useCallback(
(scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
if (clearFirst) setMatches([]);
const searchContainer = searchRef.current;
const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
if (!searchContainer || !_query) {
setMatches([]);
return;
}
const query = caseSensitive ? _query : _query.toLowerCase();
// First grab all text nodes
// Skips any elements with the "find-widget-skip" class
const textNodes: Text[] = [];
const walker = document.createTreeWalker(
searchRef.current,
NodeFilter.SHOW_ALL,
(scrollTo: ScrollToMatchOption = "none") => {
const { results, closestToMiddle } = searchWithinContainer(
searchRef,
searchTerm,
{
acceptNode: (node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).classList.contains("find-widget-skip"))
return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
} else if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
const nodeValue = caseSensitive
? node.nodeValue
: node.nodeValue.toLowerCase();
if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
},
caseSensitive,
useRegex,
offsetHeight: headerHeight,
},
);
while (walker.nextNode()) {
if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
textNodes.push(walker.currentNode as Text);
}
// Now walk through each node match and extract search results
// One node can have several matches
const newMatches: SearchMatch[] = [];
textNodes.forEach((textNode, idx) => {
// Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
const highlightFullLine =
textNode.parentElement?.className.includes("hljs");
let nodeTextValue = caseSensitive
? textNode.nodeValue
: textNode.nodeValue.toLowerCase();
let startIndex = 0;
while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
// Create a range to measure the size and position of the match
const range = document.createRange();
range.setStart(textNode, startIndex);
const endIndex = startIndex + query.length;
range.setEnd(textNode, endIndex);
const rect = range.getBoundingClientRect();
range.detach();
startIndex = endIndex;
const top =
rect.top + searchContainer.clientTop + searchContainer.scrollTop;
const left =
rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
// Build a match result and push to matches
const newMatch: SearchMatch = {
index: 0, // will set later
textNode,
overlayRectangle: {
top,
left: highlightFullLine ? 2 : left,
width: highlightFullLine
? searchContainer.clientWidth - 4
: rect.width, // equivalent of adding 2 px x padding
height: rect.height,
},
};
newMatches.push(newMatch);
if (highlightFullLine) {
break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
}
}
});
// There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
// Filter them out by using the overlay rectangle as a hash key
const matchHash = Object.fromEntries(
newMatches.map((match) => [
JSON.stringify(match.overlayRectangle),
match,
]),
);
const filteredMatches = Object.values(matchHash).map((match, index) => ({
...match,
index,
}));
setMatches(results);
// Find match closest to the middle of the view
const verticalMiddle =
searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
let closestDist = Infinity;
let closestMatchToMiddle: SearchMatch | null = null;
filteredMatches.forEach((match) => {
const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
if (dist < closestDist) {
closestDist = dist;
closestMatchToMiddle = match;
}
});
// Update matches and scroll to the closest or first match
setMatches(filteredMatches);
if (query.length > 1 && filteredMatches.length) {
if (searchTerm.length > 1 && results.length) {
if (scrollTo === "first") {
scrollToMatch(filteredMatches[0]);
scrollToMatch(results[0]);
}
if (scrollTo === "closest") {
if (closestMatchToMiddle) {
scrollToMatch(closestMatchToMiddle);
if (closestToMiddle) {
scrollToMatch(closestToMiddle);
}
}
if (scrollTo === "none") {
if (closestMatchToMiddle) {
setCurrentMatch(closestMatchToMiddle);
if (closestToMiddle) {
setCurrentMatch(closestToMiddle);
} else {
setCurrentMatch(filteredMatches[0]);
setCurrentMatch(results[0]);
}
}
}
},
[searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex],
[
searchTerm,
caseSensitive,
useRegex,
searchRef,
headerHeight,
scrollToMatch,
],
);
// Triggers that should cause immediate refresh of results to closest search value:
// Input change (debounced) and window click
const lastUpdateRef = useRef(0);
useEffect(() => {
const debounce = () => {
debouncedInput.current = input;
lastUpdateRef.current = Date.now();
refreshSearch("closest");
};
const timeSinceLastUpdate = Date.now() - lastUpdateRef.current;
if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) {
debounce();
if (disabled || isResizing || !open) {
setMatches([]);
} else {
const handler = setTimeout(() => {
debounce();
}, SEARCH_DEBOUNCE - timeSinceLastUpdate);
return () => {
clearTimeout(handler);
};
refreshSearch("closest");
}
}, [refreshSearch, input]);
}, [refreshSearch, open, disabled, isResizing]);
// Could consider doing any window click but I only handled search div here
// Since usually only clicks in search div will cause content changes in search div
// Clicks in search div can cause content changes that for some reason don't trigger resize
// Refresh clicking within container
useEffect(() => {
const searchContainer = searchRef.current;
if (!open || !searchContainer) return;
const handleSearchRefClick = () => {
refreshSearch("none");
setTimeout(() => {
refreshSearch("none");
}, 150);
};
searchContainer.addEventListener("click", handleSearchRefClick);
return () => {
searchContainer.removeEventListener("click", handleSearchRefClick);
};
}, [searchRef.current, refreshSearch, open]);
// Triggers that should cause results to temporarily disappear and then reload
// Active = LLM is generating, etc.
const active = useAppSelector((state) => state.session.isStreaming);
useEffect(() => {
if (active || isResizing) setMatches([]);
else refreshSearch("none");
}, [refreshSearch, active]);
useEffect(() => {
if (!open) setMatches([]);
else refreshSearch("closest");
}, [refreshSearch, open]);
useEffect(() => {
refreshSearch("closest");
}, [refreshSearch, caseSensitive, useRegex]);
}, [searchRef, refreshSearch, open]);
// Find widget component
const widget = useMemo(() => {
return (
<div
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`}
>
<Input
disabled={active}
type="text"
ref={inputRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
}}
placeholder="Search..."
/>
<p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
{matches.length === 0
? "No results"
: `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
</p>
<div className="hidden flex-row gap-0.5 sm:flex">
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={"Previous Match"}
onClick={(e) => {
e.stopPropagation();
previousMatch();
}}
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || active}
>
<ArrowUpIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={"Next Match"}
onClick={(e) => {
e.stopPropagation();
nextMatch();
}}
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || active}
>
<ArrowDownIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
</div>
const widget = (
<div
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`}
>
<Input
disabled={disabled}
type="text"
ref={inputRef}
value={currentValue}
onChange={(e) => {
setCurrentValue(e.target.value);
}}
placeholder="Search..."
/>
<p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
{matches.length === 0
? "No results"
: `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
</p>
<div className="hidden flex-row gap-0.5 sm:flex">
<HeaderButtonWithToolTip
disabled={active}
inverted={caseSensitive}
tooltipPlacement="top-end"
text={
caseSensitive
? "Turn off case sensitivity"
: "Turn on case sensitivity"
}
text={"Previous Match"}
onClick={(e) => {
e.stopPropagation();
setCaseSensitive((curr) => !curr);
previousMatch();
}}
className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || disabled}
>
Aa
<ArrowUpIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
{/* TODO - add useRegex functionality */}
<HeaderButton
inverted={false}
onClick={() => setOpen(false)}
className="focus:ring"
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={"Next Match"}
onClick={(e) => {
e.stopPropagation();
nextMatch();
}}
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || disabled}
>
<XMarkIcon className="h-4 w-4" />
</HeaderButton>
<ArrowDownIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
</div>
);
}, [
open,
input,
inputRef,
caseSensitive,
matches,
currentMatch,
previousMatch,
nextMatch,
]);
<HeaderButtonWithToolTip
disabled={disabled}
inverted={caseSensitive}
tooltipPlacement="top-end"
text={
caseSensitive
? "Turn off case sensitivity"
: "Turn on case sensitivity"
}
onClick={(e) => {
e.stopPropagation();
setCaseSensitive((curr) => !curr);
}}
className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
>
Aa
</HeaderButtonWithToolTip>
{/* TODO - add useRegex functionality */}
<HeaderButton
inverted={false}
onClick={() => setOpen(false)}
className="focus:ring"
>
<XMarkIcon className="h-4 w-4" />
</HeaderButton>
</div>
);
// Generate the highlight overlay elements
const highlights = useMemo(() => {
return matches.map((match) => (
<HighlightOverlay
{...match.overlayRectangle}
rectangle={match.overlayRectangle}
isCurrent={currentMatch?.index === match.index}
/>
));
}, [matches, currentMatch]);
return {
matches,
highlights,
inputRef,
input: debouncedInput,
setInput,
open,
setOpen,
widget,
};
};

View file

@ -0,0 +1,146 @@
export interface Rectangle {
top: number;
left: number;
width: number;
height: number;
}
export interface SearchMatch {
index: number;
textNode: Text;
overlayRectangle: Rectangle;
}
interface SearchOptions {
caseSensitive: boolean;
useRegex: boolean;
offsetHeight: number;
}
export const searchWithinContainer = (
containerRef: React.RefObject<HTMLDivElement>,
searchQuery: string,
options: SearchOptions,
): {
results: SearchMatch[];
closestToMiddle: SearchMatch | null;
} => {
const searchContainer = containerRef.current;
if (!searchContainer || !searchQuery) {
return {
results: [],
closestToMiddle: null,
};
}
const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase();
// First grab all text nodes
// Skips any elements with the "find-widget-skip" class
const textNodes: Text[] = [];
const walker = document.createTreeWalker(
searchContainer,
NodeFilter.SHOW_ALL,
{
acceptNode: (node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).classList.contains("find-widget-skip"))
return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
} else if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
const nodeValue = options.caseSensitive
? node.nodeValue
: node.nodeValue.toLowerCase();
if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
},
},
);
while (walker.nextNode()) {
if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
textNodes.push(walker.currentNode as Text);
}
// Now walk through each node match and extract search results
// One node can have several matches
const newMatches: SearchMatch[] = [];
textNodes.forEach((textNode, idx) => {
// Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
const highlightFullLine =
textNode.parentElement?.className.includes("hljs");
let nodeTextValue = options.caseSensitive
? textNode.nodeValue
: textNode.nodeValue.toLowerCase();
let startIndex = 0;
while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
// Create a range to measure the size and position of the match
const range = document.createRange();
range.setStart(textNode, startIndex);
const endIndex = startIndex + query.length;
range.setEnd(textNode, endIndex);
const rect = range.getBoundingClientRect();
range.detach();
startIndex = endIndex;
const top =
rect.top +
searchContainer.clientTop +
searchContainer.scrollTop -
options.offsetHeight;
const left =
rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
// Build a match result and push to matches
const newMatch: SearchMatch = {
index: 0, // will set later
textNode,
overlayRectangle: {
top,
left: highlightFullLine ? 2 : left,
width: highlightFullLine
? searchContainer.clientWidth - 4
: rect.width, // equivalent of adding 2 px x padding
height: rect.height,
},
};
newMatches.push(newMatch);
if (highlightFullLine) {
break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
}
}
});
// There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
// Filter them out by using the overlay rectangle as a hash key
const matchHash = Object.fromEntries(
newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]),
);
const filteredMatches = Object.values(matchHash).map((match, index) => ({
...match,
index,
}));
// Find the match closest to the vertical middle of the container
const verticalMiddle =
searchContainer.scrollTop + searchContainer.clientHeight / 2;
let closestDist = Infinity;
let closestMatchToMiddle: SearchMatch | null = null;
filteredMatches.forEach((match) => {
const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
if (dist < closestDist) {
closestDist = dist;
closestMatchToMiddle = match;
}
});
return {
results: filteredMatches,
closestToMiddle: closestMatchToMiddle,
};
};

View file

@ -0,0 +1,19 @@
import { useEffect, useState } from "react";
function useDebounceValue<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounceValue;

View file

@ -0,0 +1,81 @@
import { RefObject, useCallback, useEffect, useState } from "react";
interface ElementSize {
clientWidth: number;
clientHeight: number;
scrollWidth: number;
scrollHeight: number;
isResizing: boolean;
}
interface UseElementSizeOptions {
debounceMs?: number;
}
export const useElementSize = (
ref: RefObject<HTMLElement>,
debounceMs = 250,
): ElementSize => {
const [size, setSize] = useState<ElementSize>({
clientWidth: 0,
clientHeight: 0,
scrollWidth: 0,
scrollHeight: 0,
isResizing: false,
});
// Debounced update function
const debouncedSetSize = useCallback(
(measurements: Omit<ElementSize, "isResizing">) => {
let timeoutId: NodeJS.Timeout;
setSize((prev) => ({ ...prev, isResizing: true }));
timeoutId = setTimeout(() => {
setSize({
...measurements,
isResizing: false,
});
}, debounceMs);
return () => clearTimeout(timeoutId);
},
[debounceMs],
);
useEffect(() => {
if (!ref.current) return;
const updateSize = () => {
const element = ref.current;
if (!element) return;
const measurements = {
clientWidth: element.clientWidth,
clientHeight: element.clientHeight,
scrollWidth: element.scrollWidth,
scrollHeight: element.scrollHeight,
};
debouncedSetSize(measurements);
};
// Create ResizeObserver instance
const resizeObserver = new ResizeObserver(() => {
updateSize();
});
// Start observing the element
resizeObserver.observe(ref.current);
// Initial size calculation
updateSize();
// Cleanup
return () => {
resizeObserver.disconnect();
};
}, [ref, debouncedSetSize]);
return size;
};

View file

@ -39,7 +39,7 @@ function Alert({ children, type = "info" }: AlertProps) {
const { Icon } = ALERT_CONFIGS[type];
return (
<div className="rounded-lg border-l-4 bg-[color:var(--vscode-editor-foreground)] p-4 opacity-70 shadow-none">
<div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none">
<div className="flex items-start">
<Icon
className="h-6 min-h-5 w-6 min-w-5"

View file

@ -1,114 +1,31 @@
import styled from "styled-components";
import { getFontSize } from "../util";
export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground";
export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background";
export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground";
export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background";
export const VSC_LIST_SELECTION_BACKGROUND_VAR =
"--vscode-list-activeSelectionBackground";
export const VSC_FOCUS_BORDER_VAR = "--vscode-focusBorder";
export const VSC_LIST_ACTIVE_FOREGROUND_VAR =
"--vscode-quickInputList-focusForeground";
export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground";
export const VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR =
"--vscode-commandCenter-activeBorder";
export const VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR =
"--vscode-commandCenter-inactiveBorder";
export const VSC_FIND_MATCH_SELECTED_VAR =
"--vscode-editor-findMatchHighlightBackground";
export const VSC_THEME_COLOR_VARS = [
VSC_INPUT_BACKGROUND_VAR,
VSC_BACKGROUND_VAR,
VSC_FOREGROUND_VAR,
VSC_BUTTON_BACKGROUND_VAR,
VSC_BUTTON_FOREGROUND_VAR,
VSC_EDITOR_BACKGROUND_VAR,
VSC_LIST_SELECTION_BACKGROUND_VAR,
VSC_FOCUS_BORDER_VAR,
VSC_LIST_ACTIVE_FOREGROUND_VAR,
VSC_QUICK_INPUT_BACKGROUND_VAR,
VSC_INPUT_BORDER_VAR,
VSC_BADGE_BACKGROUND_VAR,
VSC_BADGE_FOREGROUND_VAR,
VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR,
VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR,
VSC_FIND_MATCH_SELECTED_VAR,
];
import { varWithFallback } from "../styles/theme";
// DEPRECATED - avoid using these where possible, use tailwind classes instead
export const defaultBorderRadius = "5px";
export const lightGray = "#999998";
export const greenButtonColor = "#189e72";
export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`;
export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`;
export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`;
export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
export const vscListActiveBackground = `var(${VSC_LIST_SELECTION_BACKGROUND_VAR}, #1bbe84)`;
export const vscFocusBorder = `var(${VSC_FOCUS_BORDER_VAR}, #1bbe84)`;
export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`;
export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`;
export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`;
export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`;
export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`;
export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`;
export function parseHexColor(hexColor: string): {
r: number;
g: number;
b: number;
} {
if (hexColor.startsWith("#")) {
hexColor = hexColor.slice(1);
}
if (hexColor.length > 6) {
hexColor = hexColor.slice(0, 6);
}
const r = parseInt(hexColor.substring(0, 2), 16);
const g = parseInt(hexColor.substring(2, 4), 16);
const b = parseInt(hexColor.substring(4, 6), 16);
return { r, g, b };
}
export function parseColorForHex(colorVar: string): string {
const value = getComputedStyle(document.documentElement).getPropertyValue(
colorVar,
);
if (value.startsWith("#")) {
return value.slice(0, 7);
}
// Parse rgb/rgba
const rgbValues = value
.slice(value.startsWith("rgba") ? 5 : 4, -1)
.split(",")
.map((x) => x.trim())
.filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
.map((x) => parseInt(x, 10));
let hex =
"#" +
rgbValues
.map((x) => x.toString(16))
.map((x) => (x.length === 1 ? "0" + x : x))
.join("");
return hex;
}
export const vscInputBackground = varWithFallback("input-background");
export const vscQuickInputBackground = varWithFallback("input-background");
export const vscBackground = varWithFallback("background");
export const vscForeground = varWithFallback("foreground");
export const vscButtonBackground = varWithFallback("primary-background");
export const vscButtonForeground = varWithFallback("primary-foreground");
export const vscEditorBackground = varWithFallback("editor-background");
export const vscListActiveBackground = varWithFallback("list-active");
export const vscFocusBorder = varWithFallback("border-focus");
export const vscListActiveForeground = varWithFallback(
"list-active-foreground",
);
export const vscInputBorder = varWithFallback("input-border");
export const vscInputBorderFocus = varWithFallback("border-focus");
export const vscBadgeBackground = varWithFallback("badge-background");
export const vscBadgeForeground = varWithFallback("badge-foreground");
export const vscCommandCenterActiveBorder = varWithFallback(
"command-border-focus",
);
export const vscCommandCenterInactiveBorder = varWithFallback("command-border");
export const Button = styled.button`
padding: 6px 12px;
@ -158,7 +75,7 @@ export const GhostButton = styled.button`
border: none;
color: ${vscForeground};
background-color: rgba(255, 255, 255, 0.08);
background-color: rgba(128, 128, 128, 0.4);
&:disabled {
color: gray;
pointer-events: none;
@ -226,10 +143,6 @@ export const Input = styled.input`
}
`;
export const Label = styled.label<{ fontSize?: number }>`
font-size: ${(props) => props.fontSize || getFontSize()}px;
`;
export const HeaderButton = styled.button<{
inverted: boolean | undefined;
backgroundColor?: string;

View file

@ -1,4 +1,4 @@
import { useContext, useEffect } from "react";
import { useContext, useEffect, useMemo } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { AnimatedEllipsis } from "../..";
@ -40,12 +40,27 @@ function GeneratingIndicator() {
);
}
function ApplyingIndicator() {
return (
<div className="text-xs text-gray-400">
<span>Applying</span>
<AnimatedEllipsis />
</div>
);
}
export function LumpToolbar() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const jetbrains = isJetBrains();
const applyStates = useAppSelector(
(store) => store.session.codeBlockApplyStates.states,
);
const isApplying = useMemo(() => {
return applyStates.find((state) => state.status === "streaming");
}, [applyStates]);
const toolCallState = useSelector(selectCurrentToolCall);
@ -89,6 +104,26 @@ export function LumpToolbar() {
);
}
if (isApplying) {
return (
<Container>
<ApplyingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {
// Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
// Apply is prioritized because it can be more catastrophic
// Intentional to be more WYSIWYG for now
ideMessenger.post("cancelApply", undefined);
}}
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
}
if (isStreaming) {
return (
<Container>

Some files were not shown because too many files have changed in this diff Show more