diff --git a/README.md b/README.md index fc07289d7..dffa26b4f 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## Actions +## Agent -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases +[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif) diff --git a/binary/package-lock.json b/binary/package-lock.json index 85720e9fd..51ea6b1f1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -67,6 +67,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 79b598f1e..7a29f8a8f 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -88,7 +88,6 @@ export class RootPathContextService { default: // const type = node.type; // console.log(getSyntaxTreeString(node)); - // debugger; query = await getQueryForFile( filepath, @@ -165,7 +164,6 @@ export class RootPathContextService { )) { const key = RootPathContextService.keyFromNode(parentKey, astNode); // const type = astNode.type; - // debugger; const foundInCache = this.cache.get(key); const newSnippets = diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f2fefbb39..f157bf21d 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -127,7 +127,7 @@ async function configYamlToContinueConfig( models: [], tools: [...allTools], mcpServerStatuses: [], - systemMessage: config.rules?.join("\n"), + systemMessage: undefined, experimental: { modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ transport: { @@ -211,15 +211,15 @@ async function configYamlToContinueConfig( for (const model of config.models ?? []) { model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified try { - const llms = await llmsFromModelConfig( + const llms = await llmsFromModelConfig({ model, ide, uniqueId, ideSettings, writeLog, platformConfigMetadata, - continueConfig.systemMessage, - ); + config: continueConfig, + }); if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { continueConfig.models.push(...llms); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index e9d5bd55c..6eabfd040 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -1,6 +1,6 @@ import { ModelConfig } from "@continuedev/config-yaml"; -import { IDE, IdeSettings, LLMOptions } from "../.."; +import { ContinueConfig, IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; @@ -13,22 +13,29 @@ function getModelClass( return LLMClasses.find((llm) => llm.providerName === model.provider); } -function getContinueProxyModelName( - ownerSlug: string, - packageSlug: string, - model: ModelConfig, -): string { - return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; -} +// function getContinueProxyModelName( +// ownerSlug: string, +// packageSlug: string, +// model: ModelConfig, +// ): string { +// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; +// } -async function modelConfigToBaseLLM( - model: ModelConfig, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function modelConfigToBaseLLM({ + model, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { const cls = getModelClass(model); if (!cls) { @@ -50,7 +57,8 @@ async function modelConfigToBaseLLM( writeLog, uniqueId, title: model.name, - systemMessage, + systemMessage: config.systemMessage, + rules: config.rules, promptTemplates: model.promptTemplates, capabilities: { tools: model.capabilities?.includes("tool_use"), @@ -127,16 +135,25 @@ async function modelConfigToBaseLLM( return llm; } -async function autodetectModels( - llm: BaseLLM, - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function autodetectModels({ + llm, + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + llm: BaseLLM; + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { try { const modelNames = await llm.listModels(); const detectedModels = await Promise.all( @@ -146,8 +163,8 @@ async function autodetectModels( return undefined; } - return await modelConfigToBaseLLM( - { + return await modelConfigToBaseLLM({ + model: { ...model, model: modelName, name: modelName, @@ -156,8 +173,8 @@ async function autodetectModels( ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); }), ); return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[]; @@ -167,38 +184,46 @@ async function autodetectModels( } } -export async function llmsFromModelConfig( - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { - const baseLlm = await modelConfigToBaseLLM( +export async function llmsFromModelConfig({ + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { + const baseLlm = await modelConfigToBaseLLM({ model, uniqueId, ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); if (!baseLlm) { return []; } if (model.model === AUTODETECT) { - const models = await autodetectModels( - baseLlm, + const models = await autodetectModels({ + llm: baseLlm, model, ide, uniqueId, ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); return models; } else { return [baseLlm]; diff --git a/core/index.d.ts b/core/index.d.ts index 5078dcca3..dd96d1699 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,6 +1,7 @@ -import { DataDestination, ModelRole } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; + declare global { interface Window { ide?: "vscode"; @@ -497,6 +498,7 @@ export interface LLMOptions { templateMessages?: (messages: ChatMessage[]) => string; writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; + rules?: Rule[]; apiKey?: string; // continueProperties @@ -1143,6 +1145,7 @@ export interface ApplyState { numDiffs?: number; filepath?: string; fileContent?: string; + toolCallId?: string; } export interface RangeInFileWithContents { @@ -1314,7 +1317,7 @@ export interface ContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1337,7 +1340,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts index 6895e9269..92f9d92c5 100644 --- a/core/llm/countTokens.test.ts +++ b/core/llm/countTokens.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck // Generated by continue import { ChatMessage, MessagePart } from "../index.js"; import { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2973cba20..2fc01f9b8 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,7 +1,13 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { + ChatMessage, + MessageContent, + MessagePart, + UserChatMessage, +} from "../index.js"; +import { Rule } from "@continuedev/config-yaml"; import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, @@ -11,6 +17,8 @@ import { import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; +import { isRuleActive } from "./rules/isRuleActive.js"; +import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -399,16 +407,127 @@ function chatMessageIsEmpty(message: ChatMessage): boolean { } } -function compileChatMessages( - modelName: string, - msgs: ChatMessage[] | undefined, - contextLength: number, - maxTokens: number, - supportsImages: boolean, - prompt: string | undefined = undefined, - functions: any[] | undefined = undefined, - systemMessage: string | undefined = undefined, -): ChatMessage[] { +function addSystemMessage({ + messages, + systemMessage, + originalMessages, +}: { + messages: ChatMessage[]; + systemMessage: string | undefined; + originalMessages: ChatMessage[] | undefined; +}): ChatMessage[] { + if ( + !(systemMessage && systemMessage.trim() !== "") && + originalMessages?.[0]?.role !== "system" + ) { + return messages; + } + + let content = ""; + if (originalMessages?.[0]?.role === "system") { + content = renderChatMessage(originalMessages[0]); + } + if (systemMessage && systemMessage.trim() !== "") { + const shouldAddNewLines = content !== ""; + if (shouldAddNewLines) { + content += "\n\n"; + } + content += systemMessage; + } + + const systemChatMsg: ChatMessage = { + role: "system", + content, + }; + // Insert as second to last + messages.splice(-1, 0, systemChatMsg); + return messages; +} + +function getMessageStringContent(message?: UserChatMessage): string { + if (!message) { + return ""; + } + + if (typeof message.content === "string") { + return message.content; + } + + // Handle MessagePart array + return message.content + .map((part) => { + if (part.type === "text") { + return part.text; + } + + return ""; + }) + .join("\n"); +} + +const getSystemMessage = ({ + userMessage, + rules, + currentModel, +}: { + userMessage?: UserChatMessage; + rules: Rule[]; + currentModel: string; +}) => { + const messageStringContent = getMessageStringContent(userMessage); + const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); + + return rules + .filter((rule) => { + return isRuleActive({ + rule, + activePaths: filePathsFromMessage, + currentModel, + }); + }) + .map((rule) => { + if (typeof rule === "string") { + return rule; + } + return rule.rule; + }) + .join("\n"); +}; + +function getLastUserMessage( + messages: ChatMessage[], +): UserChatMessage | undefined { + // Iterate backwards through messages to find the last user message + for (let i = messages.length - 1; i >= 0; i--) { + if (messages[i].role === "user") { + return messages[i] as UserChatMessage; + } + } + + return undefined; +} + +function compileChatMessages({ + modelName, + msgs, + contextLength, + maxTokens, + supportsImages, + prompt, + functions, + systemMessage, + rules, +}: { + modelName: string; + msgs: ChatMessage[] | undefined; + contextLength: number; + maxTokens: number; + supportsImages: boolean; + prompt: string | undefined; + functions: any[] | undefined; + systemMessage: string | undefined; + rules: Rule[]; +}): ChatMessage[] { let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) @@ -425,29 +544,19 @@ function compileChatMessages( msgsCopy.push(promptMsg); } - if ( - (systemMessage && systemMessage.trim() !== "") || - msgs?.[0]?.role === "system" - ) { - let content = ""; - if (msgs?.[0]?.role === "system") { - content = renderChatMessage(msgs?.[0]); - } - if (systemMessage && systemMessage.trim() !== "") { - const shouldAddNewLines = content !== ""; - if (shouldAddNewLines) { - content += "\n\n"; - } - content += systemMessage; - } - const systemChatMsg: ChatMessage = { - role: "system", - content, - }; - // Insert as second to last - // Later moved to top, but want second-priority to last user message - msgsCopy.splice(-1, 0, systemChatMsg); - } + const lastUserMessage = getLastUserMessage(msgsCopy); + + msgsCopy = addSystemMessage({ + messages: msgsCopy, + systemMessage: + systemMessage ?? + getSystemMessage({ + userMessage: lastUserMessage, + rules, + currentModel: modelName, + }), + originalMessages: msgs, + }); let functionTokens = 0; if (functions) { diff --git a/core/llm/index.ts b/core/llm/index.ts index 028bc42c3..cc7d7123c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,4 +1,4 @@ -import { ModelRole } from "@continuedev/config-yaml"; +import { ModelRole, Rule } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; import { @@ -143,6 +143,7 @@ export abstract class BaseLLM implements ILLM { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; + rules?: Rule[]; deployment?: string; apiVersion?: string; @@ -242,6 +243,7 @@ export abstract class BaseLLM implements ILLM { this.accountId = options.accountId; this.capabilities = options.capabilities; this.roles = options.roles; + this.rules = options.rules; this.deployment = options.deployment; this.apiVersion = options.apiVersion; @@ -286,21 +288,17 @@ export abstract class BaseLLM implements ILLM { CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; } - return compileChatMessages( - options.model, - messages, + return compileChatMessages({ + modelName: options.model, + msgs: messages, contextLength, - options.maxTokens ?? DEFAULT_MAX_TOKENS, - this.supportsImages(), - undefined, + maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + prompt: undefined, functions, - this.systemMessage, - ); - } - - private _getSystemMessage(): string | undefined { - // TODO: Merge with config system message - return this.systemMessage; + systemMessage: this.systemMessage, + rules: this.rules ?? [], + }); } private _templatePromptLikeMessages(prompt: string): string { @@ -310,7 +308,7 @@ export abstract class BaseLLM implements ILLM { const msgs: ChatMessage[] = [{ role: "user", content: prompt }]; - const systemMessage = this._getSystemMessage(); + const systemMessage = this.systemMessage; if (systemMessage) { msgs.unshift({ role: "system", content: systemMessage }); } diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 573170ece..7fefbd329 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -4,7 +4,7 @@ import { ConverseStreamCommand, ConverseStreamCommandOutput, InvokeModelCommand, - Message + Message, } from "@aws-sdk/client-bedrock-runtime"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; @@ -12,7 +12,7 @@ import { ChatMessage, Chunk, CompletionOptions, - LLMOptions + LLMOptions, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -52,10 +52,14 @@ class Bedrock extends BaseLLM { private _currentToolResponse: Partial | null = null; private _promptCachingMetrics: PromptCachingMetrics = { cacheReadInputTokens: 0, - cacheWriteInputTokens: 0 + cacheWriteInputTokens: 0, }; - public requestOptions: { region?: string; credentials?: any; headers?: Record }; + public requestOptions: { + region?: string; + credentials?: any; + headers?: Record; + }; constructor(options: LLMOptions) { super(options); @@ -121,12 +125,17 @@ class Bedrock extends BaseLLM { }, ); - const input = this._generateConverseInput(messages, { ...options, stream: true }); + const input = this._generateConverseInput(messages, { + ...options, + stream: true, + }); const command = new ConverseStreamCommand(input); let response: ConverseStreamCommandOutput; try { - response = await client.send(command, { abortSignal: signal }) as ConverseStreamCommandOutput; + response = (await client.send(command, { + abortSignal: signal, + })) as ConverseStreamCommandOutput; } catch (error: unknown) { console.error(error); const message = error instanceof Error ? error.message : "Unknown error"; @@ -140,9 +149,9 @@ class Bedrock extends BaseLLM { // Reset cache metrics for new request this._promptCachingMetrics = { cacheReadInputTokens: 0, - cacheWriteInputTokens: 0 + cacheWriteInputTokens: 0, }; - + try { for await (const chunk of response.stream) { if (chunk.metadata?.usage) { @@ -150,47 +159,69 @@ class Bedrock extends BaseLLM { } if (chunk.contentBlockDelta?.delta) { - - const delta: any = chunk.contentBlockDelta.delta + const delta: any = chunk.contentBlockDelta.delta; // Handle text content if (chunk.contentBlockDelta.delta.text) { - yield { role: "assistant", content: chunk.contentBlockDelta.delta.text }; + yield { + role: "assistant", + content: chunk.contentBlockDelta.delta.text, + }; continue; } // Handle text content if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { - yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text }; + yield { + role: "thinking", + content: (chunk.contentBlockDelta.delta as any).reasoningContent + .text, + }; continue; } // Handle signature for thinking if (delta.reasoningContent?.signature) { - yield { role: "thinking", content: "", signature: delta.reasoningContent.signature }; + yield { + role: "thinking", + content: "", + signature: delta.reasoningContent.signature, + }; continue; } // Handle redacted thinking if (delta.redactedReasoning?.data) { - yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data }; + yield { + role: "thinking", + content: "", + redactedThinking: delta.redactedReasoning.data, + }; continue; } - if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) { + if ( + chunk.contentBlockDelta.delta.toolUse?.input && + this._currentToolResponse + ) { // Append the new input to the existing string if (this._currentToolResponse.input === undefined) { this._currentToolResponse.input = ""; } - this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; + this._currentToolResponse.input += + chunk.contentBlockDelta.delta.toolUse.input; continue; } } if (chunk.contentBlockStart?.start) { - const start: any = chunk.contentBlockStart.start + const start: any = chunk.contentBlockStart.start; if (start.redactedReasoning) { - yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data }; + yield { + role: "thinking", + content: "", + redactedThinking: start.redactedReasoning.data, + }; continue; } @@ -199,7 +230,7 @@ class Bedrock extends BaseLLM { this._currentToolResponse = { toolUseId: toolUse.toolUseId, name: toolUse.name, - input: "" + input: "", }; } continue; @@ -210,14 +241,16 @@ class Bedrock extends BaseLLM { yield { role: "assistant", content: "", - toolCalls: [{ - id: this._currentToolResponse.toolUseId, - type: "function", - function: { - name: this._currentToolResponse.name, - arguments: this._currentToolResponse.input - } - }], + toolCalls: [ + { + id: this._currentToolResponse.toolUseId, + type: "function", + function: { + name: this._currentToolResponse.name, + arguments: this._currentToolResponse.input, + }, + }, + ], }; this._currentToolResponse = null; } @@ -229,13 +262,16 @@ class Bedrock extends BaseLLM { if (error instanceof Error) { if ("code" in error) { // AWS SDK specific errors - throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`); + throw new Error( + `AWS Bedrock stream error (${(error as any).code}): ${error.message}`, + ); } throw new Error(`Error processing Bedrock stream: ${error.message}`); } - throw new Error("Error processing Bedrock stream: Unknown error occurred"); + throw new Error( + "Error processing Bedrock stream: Unknown error occurred", + ); } - } /** @@ -252,39 +288,41 @@ class Bedrock extends BaseLLM { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const enablePromptCaching = shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; + const enablePromptCaching = + shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; // Add header for prompt caching if (enablePromptCaching) { this.requestOptions.headers = { ...this.requestOptions.headers, - "x-amzn-bedrock-enablepromptcaching": "true" + "x-amzn-bedrock-enablepromptcaching": "true", }; } - const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; + const supportsTools = + PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; return { modelId: options.model, messages: convertedMessages, - system: this.systemMessage ? ( - shouldCacheSystemMessage ? - [ - { text: this.systemMessage }, - { cachePoint: { type: "default" } } - ] : - [{ text: this.systemMessage }] - ) : undefined, - toolConfig: supportsTools && options.tools ? { - tools: options.tools.map(tool => ({ - toolSpec: { - name: tool.function.name, - description: tool.function.description, - inputSchema: { - json: tool.function.parameters + system: this.systemMessage + ? shouldCacheSystemMessage + ? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }] + : [{ text: this.systemMessage }] + : undefined, + toolConfig: + supportsTools && options.tools + ? { + tools: options.tools.map((tool) => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters, + }, + }, + })), } - } - })) - } : undefined, + : undefined, inferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature, @@ -302,21 +340,28 @@ class Bedrock extends BaseLLM { .slice(0, 4), }, additionalModelRequestFields: { - "thinking": options.reasoning ? { - "type": "enabled", - "budget_tokens": options.reasoningBudgetTokens - } : undefined, - } + thinking: options.reasoning + ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } + : undefined, + }, }; } - private _convertMessage(message: ChatMessage, addCaching: boolean = false): Message | null { + private _convertMessage( + message: ChatMessage, + addCaching: boolean = false, + ): Message | null { // Handle system messages explicitly if (message.role === "system") { return null; } - const cachePoint = addCaching ? { cachePoint: { type: "default" } } : undefined; + const cachePoint = addCaching + ? { cachePoint: { type: "default" } } + : undefined; // Tool response handling if (message.role === "tool") { @@ -328,12 +373,12 @@ class Bedrock extends BaseLLM { toolUseId: message.toolCallId, content: [ { - text: message.content || "" - } - ] - } - } - ] + text: message.content || "", + }, + ], + }, + }, + ], }; } @@ -346,8 +391,8 @@ class Bedrock extends BaseLLM { toolUseId: toolCall.id, name: toolCall.function?.name, input: JSON.parse(toolCall.function?.arguments || "{}"), - } - })) + }, + })), }; } @@ -355,26 +400,27 @@ class Bedrock extends BaseLLM { if (message.redactedThinking) { const content: ContentBlock.ReasoningContentMember = { reasoningContent: { - redactedContent: new Uint8Array(Buffer.from(message.redactedThinking)) - } + redactedContent: new Uint8Array( + Buffer.from(message.redactedThinking), + ), + }, }; return { role: "assistant", - content: [content] + content: [content], }; } else { const content: ContentBlock.ReasoningContentMember = { reasoningContent: { reasoningText: { text: (message.content as string) || "", - signature: message.signature - } - - } + signature: message.signature, + }, + }, }; return { role: "assistant", - content: [content] + content: [content], }; } } @@ -387,7 +433,7 @@ class Bedrock extends BaseLLM { } return { role: message.role, - content + content, }; } @@ -396,7 +442,7 @@ class Bedrock extends BaseLLM { const content: any[] = []; // Process all parts first - message.content.forEach(part => { + message.content.forEach((part) => { if (part.type === "text") { content.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { @@ -407,9 +453,9 @@ class Bedrock extends BaseLLM { image: { format, source: { - bytes: Buffer.from(base64Data, "base64") - } - } + bytes: Buffer.from(base64Data, "base64"), + }, + }, }); } catch (error) { console.warn(`Failed to process image: ${error}`); @@ -424,7 +470,7 @@ class Bedrock extends BaseLLM { return { role: message.role, - content + content, } as Message; } return null; @@ -439,22 +485,24 @@ class Bedrock extends BaseLLM { .filter((index) => index !== -1) .slice(-2); - const converted = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); + const converted = filteredmessages + .map((message, filteredMsgIdx) => { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + const addCaching = + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(filteredMsgIdx); - try { - return this._convertMessage(message, addCaching); - } catch (error) { - console.error(`Failed to convert message: ${error}`); - return null; - } - }).filter(Boolean); + try { + return this._convertMessage(message, addCaching); + } catch (error) { + console.error(`Failed to convert message: ${error}`); + return null; + } + }) + .filter(Boolean); return converted; } @@ -520,7 +568,6 @@ class Bedrock extends BaseLLM { return modelConfig.extractEmbeddings(responseBody); } - private _getModelConfig() { const modelConfigs: { [key: string]: ModelConfig } = { cohere: { @@ -558,7 +605,11 @@ class Bedrock extends BaseLLM { const credentials = await this._getCredentials(); const client = new BedrockRuntimeClient({ region: this.region, - credentials, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, }); // Base payload for both models @@ -597,11 +648,15 @@ class Bedrock extends BaseLLM { if (error instanceof Error) { if ("code" in error) { // AWS SDK specific errors - throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`); + throw new Error( + `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`, + ); } throw new Error(`Error in BedrockReranker.rerank: ${error.message}`); } - throw new Error("Error in BedrockReranker.rerank: Unknown error occurred"); + throw new Error( + "Error in BedrockReranker.rerank: Unknown error occurred", + ); } } } diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts new file mode 100644 index 000000000..f50b9972a --- /dev/null +++ b/core/llm/rules/isRuleActive.test.ts @@ -0,0 +1,59 @@ +import { isRuleActive } from "./isRuleActive"; + +describe("isRuleActive", () => { + const rule = { + name: "My Rule", + rule: "Do no harm", + if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', + }; + + it("should return false when activePaths is empty", () => { + expect( + isRuleActive({ + rule, + activePaths: [], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); + + it("should return false when no matching paths exist", () => { + expect( + isRuleActive({ + rule, + activePaths: ["test.py", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); + + it("should return true when both conditions are met", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(true); + }); + + it("should return false when only glob matches but model doesn't", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx"], + currentModel: "gpt-4", + }), + ).toBe(false); + }); + + it("should return false when model matches but glob doesn't", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.ts"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); +}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts new file mode 100644 index 000000000..47125c644 --- /dev/null +++ b/core/llm/rules/isRuleActive.ts @@ -0,0 +1,68 @@ +import { Rule } from "@continuedev/config-yaml"; +import { compileExpression } from "filtrex"; +import { minimatch } from "minimatch"; + +const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; + +const createGlobFunction = (activePaths: string[]) => { + return (pattern: string) => { + const result = activePaths.some((path) => minimatch(path, pattern)); + return result; + }; +}; + +const contains = (str: string, searchStr: string): boolean => { + return str.includes(searchStr); +}; + +const evaluateIf = ({ + condition, + activePaths, + currentModel, +}: { + condition: string; + activePaths: string[]; + currentModel: string; +}) => { + const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); + if (!expression) { + return true; + } + + try { + const evaluate = compileExpression(expression, { + extraFunctions: { + glob: createGlobFunction(activePaths), + contains, + }, + constants: { + "current.model.model": currentModel, + }, + }); + + return evaluate({}); + } catch (error) { + console.error("Error evaluating rule condition:", error); + return false; + } +}; + +export const isRuleActive = ({ + rule, + activePaths, + currentModel, +}: { + rule: Rule; + activePaths: string[]; + currentModel: string; +}): boolean => { + if (typeof rule === "string") { + return true; + } + + if (rule.if) { + return evaluateIf({ condition: rule.if, activePaths, currentModel }); + } + + return true; +}; diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts new file mode 100644 index 000000000..7573a1f6f --- /dev/null +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -0,0 +1,22 @@ +/** + * 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; + + while ((match = codeBlockRegex.exec(content)) !== null) { + const path = match[1]; + if (path && !path.startsWith("```")) { + paths.push(path); + } + } + + return paths; +} diff --git a/core/package-lock.json b/core/package-lock.json index f56faf7e8..24aeb4f18 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -32,6 +32,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -2976,9 +2977,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", + "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -8587,6 +8588,11 @@ "node": ">=8" } }, + "node_modules/filtrex": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz", + "integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A==" + }, "node_modules/find-replace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", diff --git a/core/package.json b/core/package.json index b6067afae..a405bad55 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -66,6 +66,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..6aae337f0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, - ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -20,6 +19,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { streamId: string; curSelectedModelTitle: string; filepath?: string; + toolCallId?: string; }, void, ]; diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index fac75090b..7cff1c70e 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,5 +1,6 @@ export enum BuiltInToolNames { ReadFile = "builtin_read_file", + EditExistingFile = "builtin_edit_existing_file", ReadCurrentlyOpenFile = "builtin_read_currently_open_file", CreateNewFile = "builtin_create_new_file", RunTerminalCommand = "builtin_run_terminal_command", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index cf8874533..28a8f8c30 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -139,6 +139,7 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + // Note: Custom GUI handling for edit case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.GrepSearch: diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts new file mode 100644 index 000000000..6ee5cee6b --- /dev/null +++ b/core/tools/definitions/editFile.ts @@ -0,0 +1,37 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export interface EditToolArgs { + filepath: string; + new_contents: string; +} + +export const editFileTool: Tool = { + type: "function", + displayTitle: "Edit File", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + function: { + name: BuiltInToolNames.EditExistingFile, + description: + "Use this tool to edit an existing file. If you don't know the contents of the file, read it first.", + parameters: { + type: "object", + required: ["filepath", "new_contents"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to edit, relative to the root of the workspace.", + }, + new_contents: { + type: "string", + description: "The new file contents", + }, + }, + }, + }, +}; diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index b5d5e6c1b..5a89141eb 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -1,6 +1,7 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; +import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; export const createNewFileImpl: ToolImpl = async (args, extras) => { const resolvedFileUri = await inferResolvedUriFromRelativePath( @@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { extras.ide, ); if (resolvedFileUri) { + const exists = await extras.ide.fileExists(resolvedFileUri); + if (exists) { + throw new Error( + `File ${args.filepath} already exists. Use the edit tool to edit this file`, + ); + } await extras.ide.writeFile(resolvedFileUri, args.contents); await extras.ide.openFile(resolvedFileUri); + return [ + { + name: getUriPathBasename(resolvedFileUri), + description: getCleanUriPath(resolvedFileUri), + content: "File created successfuly", + uri: { + type: "file", + value: resolvedFileUri, + }, + }, + ]; + } else { + throw new Error("Failed to resolve path"); } - return []; }; diff --git a/core/tools/index.ts b/core/tools/index.ts index eb4d156d9..c9875c5eb 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { createNewFileTool } from "./definitions/createNewFile"; +import { editFileTool } from "./definitions/editFile"; import { globSearchTool } from "./definitions/globSearch"; import { grepSearchTool } from "./definitions/grepSearch"; import { lsTool } from "./definitions/lsTool"; @@ -10,6 +11,7 @@ import { viewDiffTool } from "./definitions/viewDiff"; export const allTools = [ readFileTool, + editFileTool, createNewFileTool, runTerminalCommandTool, diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index dccf4a7f1..45a1f05f0 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -28,11 +28,11 @@ To enable it, simply click the "Continue" button in the status bar at the bottom Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. -## Actions +## Agent -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases. +[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -For example, you might want to review code, write tests, or add a docstring. +Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index b9c409a6d..506f6bf62 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.10 +pluginVersion=1.0.11 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index f820084a0..ed6879bd7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager @@ -432,11 +433,43 @@ class IdeProtocolClient( dataElement.toString(), ApplyToFileParams::class.java ) + val filepath = params.filepath - val editor = FileEditorManager.getInstance(project).selectedTextEditor + continuePluginService.sendToWebview("updateApplyState", mapOf( + "streamId" to params.streamId, + "status" to "streaming", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + + + fun closeStream () { + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to 0, + "streamId" to params.streamId, + "status" to "closed", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + } + + var editor: Editor? = null; + + if (!filepath.isNullOrEmpty()) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() + } + } + } + editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + closeStream() respond(null) return@launch } @@ -445,6 +478,7 @@ class IdeProtocolClient( WriteCommandAction.runWriteCommandAction(project) { editor.document.insertString(0, params.text) } + closeStream() respond(null) return@launch } @@ -490,6 +524,7 @@ class IdeProtocolClient( ToastType.ERROR, "Failed to fetch model configuration" ) } + closeStream() respond(null) return@launch } @@ -528,7 +563,11 @@ class IdeProtocolClient( editor, rif?.range?.start?.line ?: 0, rif?.range?.end?.line ?: (editor.document.lineCount - 1), - {}, {}) + {}, + {}, + params.streamId, + params.toolCallId + ) diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 55df303a8..f6cf5972f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -27,14 +27,15 @@ class DiffStreamHandler( private val startLine: Int, private val endLine: Int, private val onClose: () -> Unit, - private val onFinish: () -> Unit + private val onFinish: () -> Unit, + private val streamId: String?, + private val toolCallId: String? ) { private data class CurLineState( var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null ) private var curLine = CurLineState(startLine) - private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false @@ -48,8 +49,26 @@ class DiffStreamHandler( initUnfinishedRangeHighlights() } + private fun sendUpdate(status: String) { + if(this.streamId == null) { + return + } + val virtualFile = getVirtualFile() + val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to this.diffBlocks.size, + "streamId" to this.streamId, + "status" to status, + "fileContent" to "not implemented", + "toolCallId" to this.toolCallId, + "filepath" to virtualFile?.url + )) + } + fun acceptAll() { - editor.markupModel.removeAllHighlighters() + editor.markupModel.removeAllHighlighters(); + sendUpdate("closed") + resetState() } @@ -62,6 +81,7 @@ class DiffStreamHandler( } else { undoChanges() } + sendUpdate("closed") resetState() } @@ -70,6 +90,7 @@ class DiffStreamHandler( input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String ) { isRunning = true + this.sendUpdate("streaming") val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) val virtualFile = getVirtualFile() @@ -83,6 +104,7 @@ class DiffStreamHandler( if (response["done"] as? Boolean == true) { handleFinishedResponse() + sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") return@request } @@ -133,7 +155,10 @@ class DiffStreamHandler( } if (diffBlocks.isEmpty()) { + sendUpdate("closed") onClose() + } else { + sendUpdate("done") } } @@ -144,6 +169,7 @@ class DiffStreamHandler( ) diffBlocks.add(diffBlock) + sendUpdate("streaming") return diffBlock } @@ -234,6 +260,7 @@ class DiffStreamHandler( undoManager.undo(fileEditor) } } + sendUpdate("done") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index faaf7d058..fd910308d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) { textArea.document.insertString(textArea.caretPosition, ", ", null) textArea.requestFocus() customPanelRef.get().finish() - }) + }, + null, + null + ) val diffStreamService = project.service() diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 07988ad0e..5c587c54d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -12,7 +12,8 @@ data class ApplyToFileParams( val text: String, val streamId: String, val curSelectedModelTitle: String, - val filepath: String? + val filepath: String?, + val toolCallId: String? ) data class InsertAtCursorParams( diff --git a/extensions/vscode/README.md b/extensions/vscode/README.md index 9470b2d5e..1bc087276 100644 --- a/extensions/vscode/README.md +++ b/extensions/vscode/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## Actions +## Agent -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases. +[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index a26290f1a..c03168bf9 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.19", + "version": "1.1.20", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.19", + "version": "1.1.20", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -88,7 +88,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.3.9", + "vite": "^4.5.12", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -125,6 +125,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -13321,9 +13322,9 @@ } }, "node_modules/vite": { - "version": "4.5.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", - "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", + "version": "4.5.12", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz", + "integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 769ed476b..4167b8dcc 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.19", + "version": "1.1.20", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -625,7 +625,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.3.9", + "vite": "^4.5.12", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index 35ad7d24f..2fd5177eb 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -1,6 +1,10 @@ const { exec } = require("child_process"); const fs = require("fs"); +const version = JSON.parse( + fs.readFileSync("./package.json", { encoding: "utf-8" }), +).version; + const args = process.argv.slice(2); let target; @@ -27,6 +31,6 @@ exec(command, (error) => { throw error; } console.log( - "vsce package completed - extension created at extensions/vscode/build/continue-{version}.vsix", + `vsce package completed - extension created at extensions/vscode/build/continue-${version}.vsix`, ); }); diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 836360e51..32d240d5f 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -247,6 +247,7 @@ async function processDiff( verticalDiffManager: VerticalDiffManager, newFileUri?: string, streamId?: string, + toolCallId?: string, ) { captureCommandTelemetry(`${action}Diff`); @@ -280,6 +281,7 @@ async function processDiff( streamId, status: "closed", numDiffs: 0, + toolCallId, }); } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 34c3345ac..4d4256a1f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -190,6 +190,7 @@ export class VerticalDiffManager { diffStream: AsyncGenerator, instant: boolean, streamId: string, + toolCallId?: string, ) { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -226,6 +227,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); @@ -276,6 +278,7 @@ export class VerticalDiffManager { quickEdit?: string, range?: vscode.Range, newCode?: string, + toolCallId?: string, ): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -351,6 +354,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index e0dc9ebef..9563eb8a9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -133,6 +133,7 @@ export class VsCodeMessenger { streamId: data.streamId, status: "streaming", fileContent: data.text, + toolCallId: data.toolCallId, }); if (data.filepath) { @@ -164,6 +165,7 @@ export class VsCodeMessenger { status: "closed", numDiffs: 0, fileContent: data.text, + toolCallId: data.toolCallId, }); return; @@ -211,6 +213,7 @@ export class VsCodeMessenger { diffLines, instant, data.streamId, + data.toolCallId, ); } else { const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; @@ -232,6 +235,7 @@ export class VsCodeMessenger { undefined, rangeToApplyTo, data.text, + data.toolCallId, ); } }); diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b35899669..a7a58f894 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -9,6 +9,7 @@ "strict": true, "esModuleInterop": true, "resolveJsonModule": true, + "skipLibCheck": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], diff --git a/gui/package-lock.json b/gui/package-lock.json index 0feba0d10..df7ea183b 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -111,7 +111,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -130,6 +130,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -554,9 +555,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", + "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/gui/package.json b/gui/package.json index 3210a55f5..fa4b439af 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 8f7725db9..18c68721f 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,5 +1,6 @@ import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; +import { MainEditorProvider } from "./components/mainInput/TipTapEditor"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; @@ -57,9 +58,11 @@ function SetupListeners() { function App() { return ( - - - + + + + + ); diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 7e0e2e183..776c0721b 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -2,14 +2,17 @@ import { SlashCommandDescription } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice"; -import { getParagraphNodeFromString } from "../mainInput/utils"; +import { useMainEditor } from "../mainInput/TipTapEditor"; import { ConversationStarterCard } from "./ConversationStarterCard"; const NUM_CARDS_TO_RENDER = 5; +/** + * Displays a grid of conversation starter cards for bookmarked slash commands + */ export function ConversationStarterCards() { const dispatch = useAppDispatch(); + const { mainEditor } = useMainEditor(); const [showAll, setShowAll] = useState(false); const { isCommandBookmarked } = useBookmarkedSlashCommands(); const slashCommands = useAppSelector( @@ -21,11 +24,7 @@ export function ConversationStarterCards() { ); function onClick(command: SlashCommandDescription) { - if (command.prompt) { - dispatch( - setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)), - ); - } + mainEditor?.commands.insertPrompt(command); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 6f96e498d..24003595a 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -5,9 +5,10 @@ import { themeIcons } from "seti-file-icons"; export interface FileIconProps { filename: string; - height: string; - width: string; + height: `${number}px`; + width: `${number}px`; } + export default function FileIcon({ filename, height, width }: FileIconProps) { const file = useMemo(() => { if (filename.includes(" (")) { @@ -45,7 +46,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { height: height, fill: color, flexShrink: 0, - display: "block", + display: "flex", }} /> ); diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 5b70f2e62..0f52d3d0b 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,7 +12,6 @@ import { newSession, selectIsInEditMode, setMode, - updateApplyState, } from "../redux/slices/sessionSlice"; import { setShowDialog } from "../redux/slices/uiSlice"; import { exitEditMode } from "../redux/thunks"; @@ -125,20 +124,6 @@ const Layout = () => { [], ); - useWebviewListener( - "updateApplyState", - async (state) => { - // dispatch( - // updateCurCheckpoint({ - // filepath: state.filepath, - // content: state.fileContent, - // }), - // ); - dispatch(updateApplyState(state)); - }, - [], - ); - useWebviewListener( "openOnboardingCard", async () => { diff --git a/gui/src/components/gui/HeaderButtonWithToolTip.tsx b/gui/src/components/gui/HeaderButtonWithToolTip.tsx index 8c357d5ea..2ee4496fe 100644 --- a/gui/src/components/gui/HeaderButtonWithToolTip.tsx +++ b/gui/src/components/gui/HeaderButtonWithToolTip.tsx @@ -48,7 +48,7 @@ const HeaderButtonWithToolTip = React.forwardRef< - {props.text} + {props.text} ); diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index cf2b4cf46..14777acb6 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -8,7 +8,7 @@ import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import ContextItemsPeek from "./belowMainInput/ContextItemsPeek"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; -import TipTapEditor from "./tiptap/TipTapEditor"; +import { TipTapEditor } from "./TipTapEditor"; interface ContinueInputBoxProps { isEditMode?: boolean; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 3d0a38cec..20e40d9a9 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -98,11 +98,16 @@ function InputToolbar(props: InputToolbarProps) { const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + const activeToolCallStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit || - toolCallState?.status === "generated"; + toolCallState?.status === "generated" || + !!activeToolCallStreamId; + const toolsSupported = defaultModel && modelSupportsTools(defaultModel); const supportsImages = diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index ebef0251b..64a477cbb 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -9,11 +9,10 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { vscBadgeBackground, vscBadgeForeground } from "../.."; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; +import { useLump } from "./LumpContext"; interface BlockSettingsToolbarIcon { tooltip: string; @@ -81,21 +80,19 @@ function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) { ); } -interface BlockSettingsTopToolbarProps { - selectedSection: string | null; - setSelectedSection: (value: string | null) => void; -} +export function BlockSettingsTopToolbar() { + const { + isToolbarExpanded, + toggleToolbar, + selectedSection, + setSelectedSection, + } = useLump(); -export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) { - const isExpanded = useAppSelector( - (state) => state.ui.isBlockSettingsToolbarExpanded, - ); - const dispatch = useAppDispatch(); const handleEllipsisClick = () => { - if (isExpanded) { - props.setSelectedSection(null); + if (isToolbarExpanded) { + setSelectedSection(null); } - dispatch(toggleBlockSettingsToolbar()); + toggleToolbar(); }; return ( @@ -103,14 +100,14 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
{sections.map((section) => ( @@ -118,10 +115,10 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) { key={section.id} icon={section.icon} tooltip={section.tooltip} - isSelected={props.selectedSection === section.id} + isSelected={selectedSection === section.id} onClick={() => - props.setSelectedSection( - props.selectedSection === section.id ? null : section.id, + setSelectedSection( + selectedSection === section.id ? null : section.id, ) } /> diff --git a/gui/src/components/mainInput/Lump/LumpContext.tsx b/gui/src/components/mainInput/Lump/LumpContext.tsx new file mode 100644 index 000000000..92c5dbd6c --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpContext.tsx @@ -0,0 +1,115 @@ +/** + * Provides context for controlling the Lump component's visibility state + */ +import { + createContext, + ReactNode, + useCallback, + useContext, + useEffect, + useState, +} from "react"; +import { useAppSelector } from "../../../redux/hooks"; + +interface LumpContextType { + isLumpVisible: boolean; + selectedSection: string | null; + displayedSection: string | null; + isToolbarExpanded: boolean; + hideLump: () => void; + setSelectedSection: (section: string | null) => void; + toggleToolbar: () => void; +} + +const LumpContext = createContext(undefined); + +interface LumpProviderProps { + children: ReactNode; +} + +/** + * Provider component that makes Lump state available to any child component + */ +export function LumpProvider({ children }: LumpProviderProps) { + const [selectedSection, setSelectedSection] = useState(null); + const [displayedSection, setDisplayedSection] = useState(null); + const [isVisible, setIsVisible] = useState(false); + const [isToolbarExpanded, setIsToolbarExpanded] = useState(true); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + + // Handle keyboard escape + const handleKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === "Escape" && selectedSection) { + setSelectedSection(null); + } + }, + [selectedSection], + ); + + // Function to hide the lump + const hideLump = useCallback(() => { + setSelectedSection(null); + }, []); + + // Function to toggle toolbar expanded state + const toggleToolbar = useCallback(() => { + setIsToolbarExpanded((prev) => !prev); + }, []); + + // Update displayedSection and visibility when selectedSection changes + useEffect(() => { + if (selectedSection) { + setDisplayedSection(selectedSection); + setIsVisible(true); + } else { + setIsVisible(false); + const timeout = setTimeout(() => { + setDisplayedSection(null); + }, 300); + return () => clearTimeout(timeout); + } + }, [selectedSection]); + + // Reset when streaming starts + useEffect(() => { + if (isStreaming && selectedSection) { + setSelectedSection(null); + } + }, [isStreaming, selectedSection]); + + // Set up keyboard listener + useEffect(() => { + if (selectedSection) { + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); + } + }, [selectedSection, handleKeyDown]); + + return ( + + {children} + + ); +} + +/** + * Hook that lets any component access the Lump context + */ +export function useLump() { + const context = useContext(LumpContext); + if (context === undefined) { + throw new Error("useLump must be used within a LumpProvider"); + } + return context; +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index 6abe4525e..2cac02cbb 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -21,11 +21,6 @@ const StopButton = styled.div` cursor: pointer; `; -interface TopToolbarProps { - selectedSection: string | null; - setSelectedSection: (value: string | null) => void; -} - function GeneratingIndicator() { return (
@@ -35,7 +30,7 @@ function GeneratingIndicator() { ); } -export function LumpToolbar(props: TopToolbarProps) { +export function LumpToolbar() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const ttsActive = useAppSelector((state) => state.ui.ttsActive); @@ -73,10 +68,5 @@ export function LumpToolbar(props: TopToolbarProps) { ); } - return ( - - ); + return ; } diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index 57276ad56..de432f1d1 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -1,11 +1,10 @@ -import { useEffect, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, vscCommandCenterInactiveBorder, vscInputBackground, } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; +import { LumpProvider, useLump } from "./LumpContext"; import { LumpToolbar } from "./LumpToolbar"; import { SelectedSection } from "./sections/SelectedSection"; @@ -30,62 +29,34 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>` overflow-y: auto; `; +/** + * Main component that displays the toolbar and selected content section + */ export function Lump() { - const [selectedSection, setSelectedSection] = useState(null); - const [displayedSection, setDisplayedSection] = useState(null); - const [isVisible, setIsVisible] = useState(false); - const isStreaming = useAppSelector((state) => state.session.isStreaming); + return ( + + + + ); +} - useEffect(() => { - if (!selectedSection) { - return; - } - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Escape") { - setSelectedSection(null); - } - }; - document.addEventListener("keydown", handleKeyDown); - return () => { - document.removeEventListener("keydown", handleKeyDown); - }; - }, [selectedSection]); - - useEffect(() => { - if (isStreaming) { - setSelectedSection(null); - } - }, [isStreaming]); - - useEffect(() => { - if (selectedSection) { - setDisplayedSection(selectedSection); - setIsVisible(true); - } else { - setIsVisible(false); - const timeout = setTimeout(() => { - setDisplayedSection(null); - }, 300); - return () => { - clearTimeout(timeout); - }; - } - }, [selectedSection]); +/** + * Internal component that consumes the LumpContext + */ +function LumpContent() { + const { isLumpVisible, selectedSection } = useLump(); return (
- + - +
diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx index ad2212ac7..6885870df 100644 --- a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -50,7 +50,7 @@ export function ExploreBlocksButton(props: { blockType: string }) { return (
- {text} + + {text}
); diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index 6ad536809..8ea7a37d3 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -3,44 +3,74 @@ import { PencilIcon, } from "@heroicons/react/24/outline"; import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid"; +import { SlashCommandDescription } from "core"; import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands"; import { useAppSelector } from "../../../../redux/hooks"; import { fontSize } from "../../../../util"; +import { useMainEditor } from "../../TipTapEditor"; +import { useLump } from "../LumpContext"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; interface PromptRowProps { - command: string; - description: string; + prompt: SlashCommandDescription; isBookmarked: boolean; setIsBookmarked: (isBookmarked: boolean) => void; onEdit?: () => void; } +/** + * Displays a single prompt row with bookmark and edit controls + */ function PromptRow({ - command, - description, + prompt, isBookmarked, setIsBookmarked, onEdit, }: PromptRowProps) { + const { mainEditor } = useMainEditor(); + const { hideLump } = useLump(); + + const handlePromptClick = (e: React.MouseEvent) => { + e.stopPropagation(); + mainEditor?.commands.insertPrompt(prompt); + hideLump(); + }; + + const handleBookmarkClick = (e: React.MouseEvent) => { + e.stopPropagation(); + setIsBookmarked(!isBookmarked); + }; + + const handleEditClick = (e: React.MouseEvent) => { + e.stopPropagation(); + if (onEdit) { + onEdit(); + } + }; + return (
-
- {command} - {description} +
+ + {prompt.name} + + + {prompt.description} +
setIsBookmarked(!isBookmarked)} + onClick={handleBookmarkClick} className="cursor-pointer pt-0.5 text-gray-400 hover:brightness-125" > {isBookmarked ? ( @@ -54,8 +84,12 @@ function PromptRow({ ); } +/** + * Section that displays all available prompts with bookmarking functionality + */ export function PromptsSection() { const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands(); + const slashCommands = useAppSelector( (state) => state.config.config.slashCommands ?? [], ); @@ -78,8 +112,7 @@ export function PromptsSection() { {sortedCommands.map((prompt) => ( toggleBookmark(prompt)} onEdit={() => handleEdit(prompt)} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 4cb7b0051..62a073824 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -1,4 +1,4 @@ -import { parseConfigYaml } from "@continuedev/config-yaml"; +import { parseConfigYaml, Rule } from "@continuedev/config-yaml"; import { ArrowsPointingOutIcon, PencilIcon } from "@heroicons/react/24/outline"; import { useContext, useMemo } from "react"; import { useSelector } from "react-redux"; @@ -13,11 +13,12 @@ import { import { RootState } from "../../../../redux/store"; import { fontSize } from "../../../../util"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; +import { useLump } from "../LumpContext"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; interface RuleCardProps { index: number; - rule: string; + rule: Rule; onClick: () => void; title: string; } @@ -31,12 +32,32 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { setDialogMessage(

{title}

-
{rule}
+
+            {/** TODO: Render the rule in a more readable way */}
+            {JSON.stringify(rule)}
+          
, ), ); } + const renderRuleContent = () => { + if (typeof rule === "string") { + return
{rule}
; + } + + if (rule.rule) { + return ( +
+
{rule.rule}
+ {rule.if &&
if: {rule.if}
} +
+ ); + } + + return
{JSON.stringify(rule)}
; + }; + return (
= ({ index, rule, onClick, title }) => { }} className="line-clamp-3 text-gray-400" > - {rule} + {renderRuleContent()}
@@ -82,6 +103,7 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { export function RulesSection() { const ideMessenger = useContext(IdeMessengerContext); const { selectedProfile } = useAuth(); + const { hideLump } = useLump(); const rules = useSelector( (state: RootState) => state.config.config.rules ?? [], @@ -97,11 +119,13 @@ export function RulesSection() { })); }, [rules]); - const openUrl = (path: string) => + const openUrl = (path: string) => { ideMessenger.request("controlPlane/openUrl", { path, orgSlug: undefined, }); + hideLump(); + }; return (
@@ -113,11 +137,12 @@ export function RulesSection() { key={index} index={index} rule={rule.unrolledRule} - onClick={() => + onClick={() => { ideMessenger.post("config/openProfile", { profileId: undefined, - }) - } + }); + hideLump(); + }} title="Locally Defined Rule" /> ); @@ -137,27 +162,25 @@ export function RulesSection() { ); } - if (!rule.ruleFromYaml?.uses) { - return null; + if ("uses" in rule.ruleFromYaml) { + const ruleSlug = rule.ruleFromYaml?.uses; + + return ( + openUrl(`${ruleSlug}/new-version`)} + title={ruleSlug} + /> + ); } - const ruleSlug = rule.ruleFromYaml?.uses; - - return ( - openUrl(`${ruleSlug}/new-version`)} - title={ruleSlug} - /> - ); + // TODO: Handle rules as object with 'if' + return null; })}
); } -function useTypedDispatch() { - throw new Error("Function not implemented."); -} diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 4b133e77d..0465e1f74 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,3 +1,4 @@ +import { useLump } from "../LumpContext"; import { ContextSection } from "./ContextSection"; import DocsSection from "./docs/DocsSection"; import { MCPSection } from "./MCPSection"; @@ -6,12 +7,13 @@ import { PromptsSection } from "./PromptsSection"; import { RulesSection } from "./RulesSection"; import { ToolPoliciesSection } from "./tool-policies/ToolPoliciesSection"; -interface SelectedSectionProps { - selectedSection: string | null; -} +/** + * Renders the appropriate section based on the selected section in the Lump context + */ +export function SelectedSection() { + const { displayedSection } = useLump(); -export function SelectedSection(props: SelectedSectionProps) { - switch (props.selectedSection) { + switch (displayedSection) { case "models": return ; case "rules": diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx index 51b9d35c3..9189a794c 100644 --- a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx @@ -12,6 +12,7 @@ import { import { fontSize } from "../../../../../util"; import ConfirmationDialog from "../../../../dialogs/ConfirmationDialog"; import EditBlockButton from "../../EditBlockButton"; +import { useLump } from "../../LumpContext"; import { StatusIndicator } from "./StatusIndicator"; interface IndexingStatusViewerProps { docConfig: SiteIndexingConfig; @@ -24,6 +25,7 @@ function DocsIndexingStatus({ }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); const dispatch = useAppDispatch(); + const { hideLump } = useLump(); const status = useAppSelector( (store) => store.indexing.indexing.statuses[docConfig.startUrl], @@ -78,7 +80,7 @@ function DocsIndexingStatus({ if (hasDeleted) return null; return ( -
+
@@ -87,16 +89,10 @@ function DocsIndexingStatus({ onClick={() => { if (status?.url) { ideMessenger.post("openUrl", status.url); + hideLump(); } }} > - {docConfig.faviconUrl ? ( - doc icon - ) : null}

store.indexing.indexing.statuses, ); const { selectedProfile } = useAuth(); - const mergedDocs = useMemo(() => { const parsed = selectedProfile?.rawYaml ? parseConfigYaml(selectedProfile?.rawYaml ?? "") diff --git a/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx b/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx new file mode 100644 index 000000000..874640aa5 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx @@ -0,0 +1,117 @@ +import { Editor } from "@tiptap/react"; +import { InputModifiers } from "core"; +import React, { + createContext, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { setMainEditorContentTrigger } from "../../../redux/slices/sessionSlice"; +import { useMainEditorWebviewListeners } from "./useMainEditorWebviewListeners"; + +/** + * Context for accessing the main editor instance + */ +interface MainEditorContextType { + /** The current main editor instance */ + mainEditor: Editor | null; + /** Set the current main editor instance */ + setMainEditor: (editor: Editor | null) => void; + /** The current input ID */ + inputId: string | null; + /** Set the current input ID */ + setInputId: (id: string) => void; + /** Reference to the execute content function */ + onEnterRef: React.MutableRefObject<(modifiers: InputModifiers) => void>; +} + +const MainEditorContext = createContext( + undefined, +); + +/** + * Provider component that maintains a reference to the main editor + */ +export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { + const dispatch = useAppDispatch(); + const [mainEditor, setMainEditorInternal] = useState(null); + const [inputId, setInputId] = useState(null); + const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {}); + const editorFocusedRef = useRef(false); + const historyLength = useAppSelector((store) => store.session.history.length); + + // Listen for changes to mainEditorContentTrigger in Redux + const mainEditorContentTrigger = useAppSelector( + (store) => store.session.mainEditorContentTrigger, + ); + + useEffect(() => { + if (mainEditor && mainEditorContentTrigger) { + queueMicrotask(() => { + mainEditor.commands.setContent(mainEditorContentTrigger); + }); + // Clear the trigger after using it + dispatch(setMainEditorContentTrigger(undefined)); + } + }, [mainEditor, mainEditorContentTrigger, dispatch]); + + // Update focused ref when editor focus state changes + useEffect(() => { + if (mainEditor) { + const updateFocus = () => { + editorFocusedRef.current = mainEditor.isFocused || false; + }; + + mainEditor.on("focus", updateFocus); + mainEditor.on("blur", updateFocus); + + return () => { + mainEditor.off("focus", updateFocus); + mainEditor.off("blur", updateFocus); + }; + } + }, [mainEditor]); + + // Set up main editor webview listeners when we have a valid editor and input ID + useMainEditorWebviewListeners({ + editor: mainEditor, + onEnterRef, + dispatch, + historyLength, + inputId: inputId || "", + editorFocusedRef, + }); + + const setMainEditor = (newEditor: Editor | null) => { + setMainEditorInternal(newEditor); + }; + + const value: MainEditorContextType = { + mainEditor, + setMainEditor, + inputId, + setInputId, + onEnterRef, + }; + + return ( + + {children} + + ); +}; + +/** + * Hook to access the main editor context + */ +export const useMainEditor = (): MainEditorContextType => { + const context = useContext(MainEditorContext); + if (context === undefined) { + throw new Error("useMainEditor must be used within a MainEditorProvider"); + } + return context; +}; diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.css b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.css similarity index 100% rename from gui/src/components/mainInput/tiptap/TipTapEditor.css rename to gui/src/components/mainInput/TipTapEditor/TipTapEditor.css diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx similarity index 86% rename from gui/src/components/mainInput/tiptap/TipTapEditor.tsx rename to gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 7a287660d..3e52cfe8f 100644 --- a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -7,19 +7,15 @@ import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectDefaultModel } from "../../../redux/slices/configSlice"; -import { - selectIsInEditMode, - setMainEditorContentTrigger, -} from "../../../redux/slices/sessionSlice"; +import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; -import { DragOverlay } from "./DragOverlay"; -import { createEditorConfig, getPlaceholderText } from "./editorConfig"; -import { handleImageFile } from "./imageUtils"; -import { useEditorEventHandlers } from "./keyHandlers"; -import { InputBoxDiv } from "./StyledComponents"; +import { DragOverlay, InputBoxDiv } from "./components"; +import { useMainEditor } from "./MainEditorProvider"; import "./TipTapEditor.css"; -import { useWebviewListeners } from "./useWebviewListeners"; +import { handleImageFile } from "./utils"; +import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig"; +import { useEditorEventHandlers } from "./utils/keyHandlers"; export interface TipTapEditorProps { availableContextProviders: ContextProviderDescription[]; @@ -34,13 +30,17 @@ export interface TipTapEditorProps { toolbarOptions?: ToolbarOptions; placeholder?: string; historyKey: string; + + // TODO: This isn't actually used anywhere in this component, but it appears + // to be pulled into some of our TipTap extensions. inputId: string; } export const TIPPY_DIV_ID = "tippy-js-div"; -function TipTapEditor(props: TipTapEditorProps) { +export function TipTapEditor(props: TipTapEditorProps) { const dispatch = useAppDispatch(); + const mainEditorContext = useMainEditor(); const ideMessenger = useContext(IdeMessengerContext); @@ -57,6 +57,15 @@ function TipTapEditor(props: TipTapEditorProps) { dispatch, }); + // Register the main editor with the provider + useEffect(() => { + if (props.isMainInput && editor) { + mainEditorContext.setMainEditor(editor); + mainEditorContext.setInputId(props.inputId); + mainEditorContext.onEnterRef.current = onEnterRef.current; + } + }, [editor, props.isMainInput, props.inputId, mainEditorContext, onEnterRef]); + const [shouldHideToolbar, setShouldHideToolbar] = useState(true); useEffect(() => { @@ -101,30 +110,6 @@ function TipTapEditor(props: TipTapEditorProps) { } }, [props.isMainInput, isStreaming, editor]); - // This allows anywhere in the app to set the content of the main input - const mainInputContentTrigger = useAppSelector( - (store) => store.session.mainEditorContentTrigger, - ); - useEffect(() => { - if (!props.isMainInput || !mainInputContentTrigger) { - return; - } - queueMicrotask(() => { - editor?.commands.setContent(mainInputContentTrigger); - }); - dispatch(setMainEditorContentTrigger(undefined)); - }, [editor, props.isMainInput, mainInputContentTrigger]); - - // IDE event listeners - useWebviewListeners({ - editor, - onEnterRef, - dispatch, - historyLength, - props, - editorFocusedRef, - }); - const [showDragOverMsg, setShowDragOverMsg] = useState(false); const [activeKey, setActiveKey] = useState(null); @@ -150,7 +135,6 @@ function TipTapEditor(props: TipTapEditorProps) { editor, isOSREnabled: isOSREnabled, editorFocusedRef, - isInEditMode, setActiveKey, }); @@ -187,9 +171,6 @@ function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(false); }, [cancelBlurTimeout]); - // TODO pass clear blur timeout to model and mode selectors - // Seems like unnecessary for now? - return ( ); } - -export default TipTapEditor; diff --git a/gui/src/components/mainInput/tiptap/DragOverlay.tsx b/gui/src/components/mainInput/TipTapEditor/components/DragOverlay.tsx similarity index 100% rename from gui/src/components/mainInput/tiptap/DragOverlay.tsx rename to gui/src/components/mainInput/TipTapEditor/components/DragOverlay.tsx diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx new file mode 100644 index 000000000..16e959ebb --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -0,0 +1,235 @@ +import { + ChevronDownIcon, + EyeSlashIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { EyeIcon } from "@heroicons/react/24/solid"; +import { useEffect, useMemo, useRef, useState } from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscBadgeBackground, + vscCommandCenterInactiveBorder, + vscEditorBackground, +} from "../../.."; +import { useAppSelector } from "../../../../redux/hooks"; +import { getFontSize } from "../../../../util"; +import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; + +const MAX_PREVIEW_HEIGHT = 100; +const MAX_EXPANED_PREVIEW_HEIGHT = MAX_PREVIEW_HEIGHT * 3; + +const PreviewDiv = styled.div<{ + borderColor?: string; +}>` + background-color: ${vscEditorBackground}; + border-radius: ${defaultBorderRadius}; + border: 0.5px solid ${(props) => props.borderColor || lightGray}; + margin-top: 4px; + margin-bottom: 4px; + overflow: hidden; + position: relative; + + & div { + background-color: ${vscEditorBackground}; + } +`; + +const ContentContainer = styled.div<{ expanded: boolean }>` + position: relative; + max-height: ${(props) => + props.expanded + ? `${MAX_EXPANED_PREVIEW_HEIGHT}px` + : `${MAX_PREVIEW_HEIGHT}px`}; + overflow: hidden; + display: flex; + flex-direction: column; +`; + +const ScrollableContent = styled.div<{ shouldShowChevron: boolean }>` + overflow-y: auto; + padding-bottom: ${(props) => (props.shouldShowChevron ? "24px" : "0px")}; +`; + +const ChevronContainer = styled.div` + position: sticky; + bottom: 0; + left: 0; + right: 0; + display: flex; + justify-content: center; + background: ${vscEditorBackground}; + padding: 4px 0; + z-index: 10; +`; + +/** + * Props for the ExpandableToolbarPreview component + */ +interface ExpandableToolbarPreviewProps { + /** Title to display in the header */ + title: string; + /** Optional icon to display next to the title */ + icon?: React.ReactNode; + /** ID of the input this preview is associated with (for toolbar hiding logic) */ + inputId?: string; + /** ID of the item being displayed (for toolbar hiding logic) */ + itemId?: string; + /** Whether the preview is initially hidden (overridden if inputId and itemId are provided) */ + initiallyHidden?: boolean; + /** Callback when the delete button is clicked */ + onDelete?: () => void; + /** Callback when the title is clicked */ + onTitleClick?: (e: React.MouseEvent) => void; + /** Border color of the preview */ + borderColor?: string; + /* Whether the preview is selected */ + isSelected?: boolean; + /** Content to display in the preview */ + children: React.ReactNode; +} + +/** + * A generalized expandable preview component for displaying content with a header and expandable body + */ +export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { + // Get toolbar visibility state from Redux if inputId and itemId are provided + const newestCodeblockForInputId = useAppSelector((store) => + props.inputId + ? store.session.newestToolbarPreviewForInput[props.inputId] + : undefined, + ); + + const calculatedInitiallyHidden = useMemo(() => { + // If initiallyHidden is explicitly set to false, always start visible + if (props.initiallyHidden === false) { + return false; + } + + // Otherwise, use the inputId/itemId logic + if (props.inputId && props.itemId) { + return newestCodeblockForInputId !== props.itemId; + } + return props.initiallyHidden ?? false; + }, [ + newestCodeblockForInputId, + props.inputId, + props.itemId, + props.initiallyHidden, + ]); + + const [hidden, setHidden] = useState(calculatedInitiallyHidden); + const [isExpanded, setIsExpanded] = useState(false); + + // Track if user has manually toggled visibility + const [userToggled, setUserToggled] = useState(false); + + const contentRef = useRef(null); + const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); + + useEffect(() => { + // Only update hidden state from props if user hasn't manually toggled + // or if initiallyHidden isn't explicitly set to false + if (!userToggled || props.initiallyHidden !== false) { + setHidden(calculatedInitiallyHidden); + } + }, [calculatedInitiallyHidden, userToggled, props.initiallyHidden]); + useEffect(() => { + const resizeObserver = new ResizeObserver(() => { + setContentDims({ + width: contentRef.current?.scrollWidth ?? 0, + height: contentRef.current?.scrollHeight ?? 0, + }); + }); + + if (contentRef.current) { + resizeObserver.observe(contentRef.current); + } + + return () => { + resizeObserver.disconnect(); + }; + }, [contentRef]); + + return ( + +

{ + setUserToggled(true); + setHidden(!hidden); + }} + > +
{ + e.stopPropagation(); + if (props.onTitleClick) { + props.onTitleClick(e); + } + }} + > + {props.icon} + {props.title} +
+
+ + {hidden ? ( + + ) : ( + + )} + + {props.onDelete && ( + { + e.stopPropagation(); + props.onDelete?.(); + }} + > + + + )} +
+
+ + {!hidden && ( + + MAX_PREVIEW_HEIGHT} + > + {props.children} + + + {contentDims.height > MAX_PREVIEW_HEIGHT && ( + + + setIsExpanded((v) => !v)} + /> + + + )} + + )} + + ); +} diff --git a/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx b/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx new file mode 100644 index 000000000..ac1a67836 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx @@ -0,0 +1,23 @@ +import { + NodeViewWrapper as TiptapNodeViewWrapper, + NodeViewWrapperProps as TiptapNodeViewWrapperProps, +} from "@tiptap/react"; +import React from "react"; + +interface NodeViewWrapperProps { + children: React.ReactNode; +} + +export const NodeViewWrapper: React.FC = ({ + children, +}) => { + // Not setting this as a "p" will cause issues with foreign keyboards + // See https://github.com/continuedev/continue/issues/3199 + const nodeViewWrapperTag: TiptapNodeViewWrapperProps["as"] = "p"; + + return ( + + {children} + + ); +}; diff --git a/gui/src/components/mainInput/tiptap/StyledComponents.ts b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts similarity index 95% rename from gui/src/components/mainInput/tiptap/StyledComponents.ts rename to gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts index 2aca4f1be..f994b53d6 100644 --- a/gui/src/components/mainInput/tiptap/StyledComponents.ts +++ b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts @@ -8,8 +8,8 @@ import { vscForeground, vscInputBackground, vscInputBorderFocus, -} from "../.."; -import { getFontSize } from "../../../util"; +} from "../../.."; +import { getFontSize } from "../../../../util"; export const InputBoxDiv = styled.div<{}>` resize: none; diff --git a/gui/src/components/mainInput/TipTapEditor/components/index.ts b/gui/src/components/mainInput/TipTapEditor/components/index.ts new file mode 100644 index 000000000..ddcf5dd94 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/index.ts @@ -0,0 +1,3 @@ +export * from "./DragOverlay"; +export * from "./ExpandableToolbarPreview"; +export * from "./StyledComponents"; diff --git a/gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts similarity index 88% rename from gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts index f633c342b..87b524435 100644 --- a/gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts @@ -1,25 +1,16 @@ import { mergeAttributes, Node } from "@tiptap/core"; -import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; - -export type MentionOptions = { - HTMLAttributes: Record; - renderHTML: (props: { - options: MentionOptions; - node: ProseMirrorNode; - }) => DOMOutputSpec; - suggestion: Omit; -}; - -export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit"); +import Suggestion from "@tiptap/suggestion"; +import { MentionOptions } from "./types"; export const AddCodeToEdit = Node.create({ name: "add-code-to-edit", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "add-code-to-edit", + }, renderHTML({ options, node }) { return [ "span", @@ -29,7 +20,7 @@ export const AddCodeToEdit = Node.create({ }, suggestion: { char: "#", - pluginKey: AddCodeToEditPluginKey, + pluginKey: new PluginKey(this.name), allow: ({ state, range }) => { const $from = state.doc.resolve(range.from); const type = state.schema.nodes[this.name]; diff --git a/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx similarity index 74% rename from gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx index aea6e18af..386593e28 100644 --- a/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx @@ -1,9 +1,9 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeBlockComponent } from "../CodeBlockComponent"; +import { CodeBlockPreview } from "./CodeBlockPreview"; -export const CodeBlockExtension = Node.create({ - name: "codeBlock", +export const CodeBlock = Node.create({ + name: "code-block", group: "block", @@ -37,6 +37,6 @@ export const CodeBlockExtension = Node.create({ }, addNodeView() { - return ReactNodeViewRenderer(CodeBlockComponent); + return ReactNodeViewRenderer(CodeBlockPreview); }, }); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx new file mode 100644 index 000000000..c414d7f1c --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -0,0 +1,76 @@ +import { NodeViewProps } from "@tiptap/react"; +import { ContextItemWithId } from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; +import { dedent, getMarkdownLanguageTagForFile } from "core/util"; +import { useContext, useMemo } from "react"; +import { vscBadgeBackground } from "../../../.."; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import FileIcon from "../../../../FileIcon"; +import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; +import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; +import { NodeViewWrapper } from "../../components/NodeViewWrapper"; + +const backticksRegex = /`{3,}/gm; + +/** + * Component for displaying a code block in the TipTap editor + */ +export const CodeBlockPreview = ({ + node, + deleteNode, + selected, +}: NodeViewProps) => { + const item: ContextItemWithId = node.attrs.item; + const inputId = node.attrs.inputId; + const ideMessenger = useContext(IdeMessengerContext); + + const content = useMemo(() => { + return dedent`${item.content}`; + }, [item.content]); + + const fence = useMemo(() => { + const backticks = content.match(backticksRegex); + return backticks ? backticks.sort().at(-1) + "`" : "```"; + }, [content]); + + const handleTitleClick = (e: React.MouseEvent) => { + e.stopPropagation(); + + if (item.id.providerTitle === "file" && item.uri?.value) { + ideMessenger.post("showFile", { + filepath: item.uri.value, + }); + } else if (item.id.providerTitle === "code") { + const rif = ctxItemToRifWithContents(item, true); + ideMessenger.ide.showLines( + rif.filepath, + rif.range.start.line, + rif.range.end.line, + ); + } else { + ideMessenger.post("showVirtualFile", { + content: item.content, + name: item.name, + }); + } + }; + + return ( + + } + inputId={inputId} + itemId={item.id.itemId} + onDelete={() => deleteNode()} + borderColor={selected ? vscBadgeBackground : undefined} + onTitleClick={handleTitleClick} + > + + + + ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts new file mode 100644 index 000000000..ca111193d --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts @@ -0,0 +1 @@ +export * from "./CodeBlock"; diff --git a/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts index 364b241ee..bfd48b0f6 100644 --- a/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts @@ -1,25 +1,17 @@ import { mergeAttributes, Node } from "@tiptap/core"; -import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; - -export type MentionOptions = { - HTMLAttributes: Record; - renderHTML: (props: { - options: MentionOptions; - node: ProseMirrorNode; - }) => DOMOutputSpec; - suggestion: Omit; -}; - -export const MentionPluginKey = new PluginKey("mention"); +import Suggestion from "@tiptap/suggestion"; +import { MentionOptions } from "./types"; export const Mention = Node.create({ name: "mention", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "mention", + }, + renderHTML({ options, node }) { return [ "span", @@ -29,7 +21,7 @@ export const Mention = Node.create({ }, suggestion: { char: "@", - pluginKey: MentionPluginKey, + pluginKey: new PluginKey(this.name), command: ({ editor, range, props }) => { // increase range.to by one when the next node is of type "text" // and starts with a space character diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts new file mode 100644 index 000000000..b35a637ea --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts @@ -0,0 +1,130 @@ +import { mergeAttributes, Node } from "@tiptap/core"; +import { Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { ReactNodeViewRenderer } from "@tiptap/react"; +import { ContextItemWithId, SlashCommandDescription } from "core"; +import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat"; +import { PromptBlockPreview } from "./PromptBlockPreview"; + +export interface PromptBlockOptions { + HTMLAttributes: Record; +} + +export interface PromptBlockAttributes { + item: ContextItemWithId; + inputId: string; +} + +declare module "@tiptap/core" { + interface Commands { + promptBlock: { + /** + * Insert a prompt block into the editor + */ + insertPrompt: (item: SlashCommandDescription) => ReturnType; + + /** + * Clear all prompt blocks from the editor + */ + clearPrompt: () => ReturnType; + }; + } +} + +/** + * Extension for adding prompt blocks to the TipTap editor + */ +export const PromptBlock = Node.create({ + name: "prompt-block", + group: "block", + content: "inline*", + + addOptions() { + return { + HTMLAttributes: { + class: "prompt-block", + }, + }; + }, + + addAttributes() { + return { + item: { + default: null, + }, + inputId: { + default: null, + }, + }; + }, + + parseHTML() { + return [ + { + tag: "prompt-block", + }, + ]; + }, + + renderHTML({ HTMLAttributes }) { + return ["prompt-block", mergeAttributes(HTMLAttributes), 0]; + }, + + addNodeView() { + return ReactNodeViewRenderer(PromptBlockPreview); + }, + + addCommands() { + return { + insertPrompt: + (prompt: SlashCommandDescription) => + ({ chain }) => { + const item: ContextItemWithId = { + content: prompt.prompt ?? "", + name: prompt.name, + description: prompt.description, + id: { + providerTitle: "prompt", + itemId: prompt.name, + }, + }; + + return chain() + .insertContentAt(0, { + type: this.name, + attrs: { + item, + inputId: MAIN_EDITOR_INPUT_ID, + }, + }) + .focus("end") + .run(); + }, + + // TODO: This could probably be greatly simplified with something along the lines of + // `editor.commands.deleteNode(this.name)`, but was unable to get it working + clearPrompt: + () => + ({ state, commands }) => { + // Find all prompt-block nodes in the document + const promptNodes: { pos: number; node: ProseMirrorNode }[] = []; + state.doc.descendants((node, pos) => { + if (node.type.name === this.name) { + promptNodes.push({ pos, node }); + return false; // Don't descend into this node + } + return true; + }); + + // Delete all found prompt blocks + // We process them in reverse order so that deleting one doesn't affect the position of others + for (let i = promptNodes.length - 1; i >= 0; i--) { + const { pos, node } = promptNodes[i]; + commands.deleteRange({ from: pos, to: pos + node.nodeSize }); + } + + // Return true if we deleted any nodes + return promptNodes.length > 0; + }, + }; + }, +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx new file mode 100644 index 000000000..8a1095d80 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx @@ -0,0 +1,51 @@ +import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; +import { NodeViewProps } from "@tiptap/react"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; +import { NodeViewWrapper } from "../../components/NodeViewWrapper"; +import { PromptBlockAttributes } from "./PromptBlock"; + +/** + * Component for prompt blocks in the Tiptap editor + */ +export const PromptBlockPreview = ({ + node, + selected, + editor, +}: NodeViewProps) => { + const { item, inputId } = node.attrs as PromptBlockAttributes; + + const ideMessenger = useContext(IdeMessengerContext); + + const handleTitleClick = (e: React.MouseEvent) => { + e.stopPropagation(); + ideMessenger.post("showVirtualFile", { + content: item.content, + name: item.name, + }); + }; + + const handleDelete = () => { + editor.commands.clearPrompt(); + }; + + return ( + + } + inputId={inputId} + itemId={item.id.itemId} + onDelete={handleDelete} + onTitleClick={handleTitleClick} + > +
+ {item.content} +
+
+
+ ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts new file mode 100644 index 000000000..3a72d7bd3 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts @@ -0,0 +1 @@ +export * from "./PromptBlock"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts new file mode 100644 index 000000000..892d80355 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts @@ -0,0 +1,58 @@ +// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts) + +import { Node } from "@tiptap/core"; +import { PluginKey } from "@tiptap/pm/state"; +import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; +import { ComboBoxItem } from "../../types"; + +export type SlashCommandOptions = { + suggestion: Omit, "editor">; +}; + +export const SlashCommand = Node.create({ + name: "slash-command", + + addOptions() { + return { + suggestion: { + char: "/", + pluginKey: new PluginKey(this.name), + startOfLine: true, + command: ({ editor, range, props }) => { + // First delete the slash character and any text after it + editor.chain().focus().deleteRange(range).run(); + + editor.commands.insertPrompt({ + name: props.title, + description: props.description, + prompt: props.content, + }); + }, + }, + }; + }, + + group: "inline", + inline: true, + selectable: false, + atom: true, + + // We don't need attributes since we won't be rendering any node + addAttributes() { + return {}; + }, + + // No need to parse HTML since we're not rendering anything + parseHTML() { + return []; + }, + + addProseMirrorPlugins() { + return [ + Suggestion({ + editor: this.editor, + ...this.options.suggestion, + }), + ]; + }, +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts new file mode 100644 index 000000000..06426b9c3 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -0,0 +1,5 @@ +export * from "./AddCodeToEdit"; +export * from "./CodeBlock"; +export * from "./Mention"; +export * from "./Prompt"; +export * from "./SlashCommand"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/types.ts b/gui/src/components/mainInput/TipTapEditor/extensions/types.ts new file mode 100644 index 000000000..318b1062d --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/types.ts @@ -0,0 +1,11 @@ +import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { SuggestionOptions } from "@tiptap/suggestion"; + +export type MentionOptions = { + HTMLAttributes: Record; + renderHTML: (props: { + options: MentionOptions; + node: ProseMirrorNode; + }) => DOMOutputSpec; + suggestion: Omit; +}; diff --git a/gui/src/components/mainInput/TipTapEditor/index.ts b/gui/src/components/mainInput/TipTapEditor/index.ts new file mode 100644 index 000000000..b2d446398 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/index.ts @@ -0,0 +1,4 @@ +export * from "./extensions"; +export * from "./MainEditorProvider"; +export * from "./TipTapEditor"; +export * from "./utils"; diff --git a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts similarity index 68% rename from gui/src/components/mainInput/tiptap/useWebviewListeners.ts rename to gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 3a4694939..6e7808ba7 100644 --- a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -1,43 +1,50 @@ -import { Editor } from "@tiptap/core"; +import { Editor } from "@tiptap/react"; import { InputModifiers } from "core"; import { rifWithContentsToContextItem } from "core/commands/util"; import { MutableRefObject } from "react"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { clearCodeToEdit, - setNewestCodeblocksForInput, + setNewestToolbarPreviewForInput, } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { TipTapEditorProps } from "./TipTapEditor"; +import { CodeBlock, PromptBlock } from "./extensions"; -export function useWebviewListeners(options: { +/** + * Hook for setting up main editor specific webview listeners + */ +export function useMainEditorWebviewListeners({ + editor, + onEnterRef, + dispatch, + historyLength, + inputId, + editorFocusedRef, +}: { editor: Editor | null; onEnterRef: MutableRefObject<(modifiers: InputModifiers) => void>; dispatch: AppDispatch; historyLength: number; - props: TipTapEditorProps; + inputId: string; editorFocusedRef: MutableRefObject; }) { - const { - editor, - onEnterRef, - dispatch, - historyLength, - props, - editorFocusedRef, - } = options; + useWebviewListener( + "isContinueInputFocused", + async () => { + return !!editorFocusedRef.current; + }, + [editorFocusedRef], + ); useWebviewListener( "userInput", async (data) => { - if (!props.isMainInput) { - return; - } - editor?.commands.insertContent(data.input); + if (!editor) return; + editor.commands.insertContent(data.input); onEnterRef.current({ useCodebase: false, noContext: true }); }, - [editor, onEnterRef.current, props.isMainInput], + [editor, onEnterRef.current], ); useWebviewListener("jetbrains/editorInsetRefresh", async () => { @@ -46,11 +53,7 @@ export function useWebviewListeners(options: { useWebviewListener( "focusContinueInput", - async (data) => { - if (!props.isMainInput) { - return; - } - + async () => { dispatch(clearCodeToEdit()); if (historyLength > 0) { @@ -61,52 +64,46 @@ export function useWebviewListeners(options: { }), ); } + setTimeout(() => { editor?.commands.blur(); editor?.commands.focus("end"); }, 20); }, - [historyLength, editor, props.isMainInput], + [historyLength, editor, dispatch], ); useWebviewListener( "focusContinueInputWithoutClear", async () => { - if (!props.isMainInput) { - return; - } setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor], ); useWebviewListener( "focusContinueInputWithNewSession", async () => { - if (!props.isMainInput) { - return; - } await dispatch( saveCurrentSession({ openNewSession: true, generateTitle: true, }), ); + setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor, dispatch], ); useWebviewListener( "highlightedCode", async (data) => { - if (!props.isMainInput || !editor) { - return; - } + if (!editor) return; const contextItem = rifWithContentsToContextItem( data.rangeInFileWithContents, @@ -114,31 +111,38 @@ export function useWebviewListeners(options: { let index = 0; for (const el of editor.getJSON()?.content ?? []) { + // Prevent exact duplicate code blocks if (el.attrs?.item?.name === contextItem.name) { - return; // Prevent exact duplicate code blocks + return; } - if (el.type === "codeBlock") { + + if (el.type === CodeBlock.name || el.type === PromptBlock.name) { index += 2; } else { break; } } + + debugger; + editor .chain() .insertContentAt(index, { - type: "codeBlock", + type: CodeBlock.name, attrs: { item: contextItem, - inputId: props.inputId, + inputId, }, }) .run(); + dispatch( - setNewestCodeblocksForInput({ - inputId: props.inputId, + setNewestToolbarPreviewForInput({ + inputId, contextItemId: contextItem.id.itemId, }), ); + if (data.prompt) { editor.commands.focus("end"); editor.commands.insertContent(data.prompt); @@ -153,52 +157,42 @@ export function useWebviewListeners(options: { editor.commands.focus("end"); }, 20); }, - [editor, props.isMainInput, historyLength, onEnterRef.current], + [editor, inputId, onEnterRef.current], ); useWebviewListener( "focusEdit", async () => { - if (!props.isMainInput) { - return; - } - setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor], ); useWebviewListener( "focusEditWithoutClear", async () => { - if (!props.isMainInput) { - return; - } - setTimeout(() => { editor?.commands.focus("end"); }, 2000); }, - [editor, props.isMainInput], + [editor], ); useWebviewListener( "isContinueInputFocused", async () => { - return props.isMainInput && !!editorFocusedRef.current; + return !!editorFocusedRef.current; }, - [editorFocusedRef, props.isMainInput], - !props.isMainInput, + [editorFocusedRef], ); useWebviewListener( "focusContinueSessionId", async (data) => { - if (!props.isMainInput || !data.sessionId) { - return; - } + if (!data.sessionId) return; + await dispatch( loadSession({ sessionId: data.sessionId, @@ -206,6 +200,6 @@ export function useWebviewListeners(options: { }), ); }, - [props.isMainInput], + [], ); } diff --git a/gui/src/components/mainInput/tiptap/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts similarity index 86% rename from gui/src/components/mainInput/tiptap/editorConfig.ts rename to gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 985cadc64..8addede87 100644 --- a/gui/src/components/mainInput/tiptap/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -11,32 +11,29 @@ import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { usePostHog } from "posthog-js/react"; import { useRef } from "react"; -import { IIdeMessenger } from "../../../context/IdeMessenger"; -import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders"; -import { useInputHistory } from "../../../hooks/useInputHistory"; -import useUpdatingRef from "../../../hooks/useUpdatingRef"; -import { useAppSelector } from "../../../redux/hooks"; -import { selectUseActiveFile } from "../../../redux/selectors"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { + getContextProviderDropdownOptions, + getSlashCommandDropdownOptions, +} from "."; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; +import { useSubmenuContextProviders } from "../../../../context/SubmenuContextProviders"; +import { useInputHistory } from "../../../../hooks/useInputHistory"; +import useUpdatingRef from "../../../../hooks/useUpdatingRef"; +import { useAppSelector } from "../../../../redux/hooks"; +import { selectUseActiveFile } from "../../../../redux/selectors"; +import { selectDefaultModel } from "../../../../redux/slices/configSlice"; import { addCodeToEdit, selectHasCodeToEdit, selectIsInEditMode, -} from "../../../redux/slices/sessionSlice"; -import { AppDispatch } from "../../../redux/store"; -import { exitEditMode } from "../../../redux/thunks"; -import { loadLastSession } from "../../../redux/thunks/session"; -import { getFontSize } from "../../../util"; -import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; -import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; -import { SlashCommand } from "./extensions/CommandsExtension"; -import { Mention } from "./extensions/MentionExtension"; -import { - getContextProviderDropdownOptions, - getSlashCommandDropdownOptions, -} from "./getSuggestion"; +} from "../../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../../redux/store"; +import { exitEditMode } from "../../../../redux/thunks"; +import { loadLastSession } from "../../../../redux/thunks/session"; +import { getFontSize } from "../../../../util"; +import * as ContinueExtensions from "../extensions"; +import { TipTapEditorProps } from "../TipTapEditor"; import { handleImageFile } from "./imageUtils"; -import { TipTapEditorProps } from "./TipTapEditor"; export function getPlaceholderText( placeholder: TipTapEditorProps["placeholder"], @@ -63,7 +60,6 @@ export function createEditorConfig(options: { const posthog = usePostHog(); - // #region Selectors const { getSubmenuContextItems } = useSubmenuContextProviders(); const defaultModel = useAppSelector(selectDefaultModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); @@ -72,9 +68,7 @@ export function createEditorConfig(options: { const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - // #endregion - // #region Refs const inSubmenuRef = useRef(undefined); const inDropdownRef = useRef(false); const defaultModelRef = useUpdatingRef(defaultModel); @@ -90,8 +84,6 @@ export function createEditorConfig(options: { ); const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); - // #endregion - const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); const indexOfAt = contents.lastIndexOf("@"); @@ -294,10 +286,7 @@ export function createEditorConfig(options: { }, }), Text, - Mention.configure({ - HTMLAttributes: { - class: "mention", - }, + ContinueExtensions.Mention.configure({ suggestion: getContextProviderDropdownOptions( availableContextProvidersRef, getSubmenuContextItemsRef, @@ -307,15 +296,8 @@ export function createEditorConfig(options: { inSubmenuRef, ideMessenger, ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, }), - - AddCodeToEdit.configure({ - HTMLAttributes: { - class: "add-code-to-edit", - }, + ContinueExtensions.AddCodeToEdit.configure({ suggestion: { ...getContextProviderDropdownOptions( availableContextProvidersRef, @@ -351,25 +333,22 @@ export function createEditorConfig(options: { }, }, }), - SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, + ContinueExtensions.SlashCommand.configure({ suggestion: getSlashCommandDropdownOptions( availableSlashCommandsRef, onClose, onOpen, ideMessenger, + dispatch, + props.inputId, ), - renderText: (props) => { - return props.node.attrs.label; - }, }), - CodeBlockExtension, + ContinueExtensions.PromptBlock, + ContinueExtensions.CodeBlock, ], editorProps: { attributes: { - class: "outline-none -mt-1 overflow-hidden", + class: "outline-none overflow-hidden", style: `font-size: ${getFontSize()}px;`, }, }, diff --git a/gui/src/components/mainInput/tiptap/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts similarity index 93% rename from gui/src/components/mainInput/tiptap/getSuggestion.ts rename to gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index f9faad863..8c0613a4a 100644 --- a/gui/src/components/mainInput/tiptap/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -6,10 +6,12 @@ import { } from "core"; import { MutableRefObject } from "react"; import tippy from "tippy.js"; -import { IIdeMessenger } from "../../../context/IdeMessenger"; -import AtMentionDropdown from "../AtMentionDropdown"; -import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../types"; -import { TIPPY_DIV_ID } from "./TipTapEditor"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; +import { AppDispatch } from "../../../../redux/store"; +import AtMentionDropdown from "../../AtMentionDropdown"; +import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; +import { TIPPY_DIV_ID } from "../TipTapEditor"; +import { SlashCommand } from "../extensions"; function getSuggestion( items: (props: { query: string }) => Promise, @@ -196,6 +198,8 @@ export function getSlashCommandDropdownOptions( onClose: () => void, onOpen: () => void, ideMessenger: IIdeMessenger, + dispatch: AppDispatch, + inputId: string, ) { const items = async ({ query }: { query: string }) => { const options = [...availableSlashCommandsRef.current]; @@ -215,7 +219,8 @@ export function getSlashCommandDropdownOptions( id: provider.title, title: provider.title, label: provider.title, - type: (provider.type ?? "slashCommand") as ComboBoxItemType, + type: (provider.type ?? SlashCommand.name) as ComboBoxItemType, + content: provider.content, action: provider.action, })); @@ -232,6 +237,7 @@ export function getSlashCommandDropdownOptions( name: "", id: "", label: "", + content: "", }); } diff --git a/gui/src/components/mainInput/tiptap/imageUtils.ts b/gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts similarity index 96% rename from gui/src/components/mainInput/tiptap/imageUtils.ts rename to gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts index 0803e5ab8..23de2dda1 100644 --- a/gui/src/components/mainInput/tiptap/imageUtils.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts @@ -1,4 +1,4 @@ -import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; const IMAGE_RESOLUTION = 1024; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/index.ts b/gui/src/components/mainInput/TipTapEditor/utils/index.ts new file mode 100644 index 000000000..5ce05a866 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/utils/index.ts @@ -0,0 +1,5 @@ +export * from "./editorConfig"; +export * from "./getSuggestion"; +export * from "./imageUtils"; +export * from "./keyHandlers"; +export * from "./resolveEditorContent"; diff --git a/gui/src/components/mainInput/tiptap/keyHandlers.ts b/gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/keyHandlers.ts rename to gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts index c25a53271..a102ba2f0 100644 --- a/gui/src/components/mainInput/tiptap/keyHandlers.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts @@ -1,20 +1,18 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; -import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util"; +import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../../util"; import { handleJetBrainsOSRMetaKeyIssues, handleVSCMetaKeyIssues, -} from "../util/handleMetaKeyIssues"; +} from "../../util/handleMetaKeyIssues"; export function useEditorEventHandlers(options: { editor: Editor | null; isOSREnabled: boolean; editorFocusedRef: React.MutableRefObject; - isInEditMode: boolean; setActiveKey: (key: string | null) => void; }) { - const { editor, isOSREnabled, editorFocusedRef, isInEditMode, setActiveKey } = - options; + const { editor, isOSREnabled, editorFocusedRef, setActiveKey } = options; /** * This handles various issues with meta key actions diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts new file mode 100644 index 000000000..63ebad23c --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -0,0 +1,341 @@ +import { Dispatch } from "@reduxjs/toolkit"; +import Image from "@tiptap/extension-image"; +import { Paragraph } from "@tiptap/extension-paragraph"; +import { Text } from "@tiptap/extension-text"; +import { JSONContent } from "@tiptap/react"; +import { + ContextItemWithId, + DefaultContextProvider, + InputModifiers, + MessageContent, + MessagePart, + RangeInFile, + SlashCommandDescription, + TextMessagePart, +} from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; +import { renderChatMessage, stripImages } from "core/util/messageContent"; +import { getUriFileExtension } from "core/util/uri"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; +import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; +import { CodeBlock, Mention, SlashCommand } from "../extensions"; + +interface MentionAttrs { + label: string; + id: string; + itemType?: string; + query?: string; +} + +interface ResolveEditorContentInput { + editorState: JSONContent; + modifiers: InputModifiers; + ideMessenger: IIdeMessenger; + defaultContextProviders: DefaultContextProvider[]; + availableSlashCommands: SlashCommandDescription[]; + selectedModelTitle: string; + dispatch: Dispatch; +} + +type ResolveEditorContentOutput = [ + ContextItemWithId[], + RangeInFile[], + MessageContent, + ( + | { + command: SlashCommandDescription; + input: string; + } + | undefined + ), +]; + +/** + * This function converts the input from the editor to a string, resolving any context items + * Context items are appended to the top of the prompt and then referenced within the input + */ +export async function resolveEditorContent({ + editorState, + modifiers, + ideMessenger, + defaultContextProviders, + availableSlashCommands, + selectedModelTitle, + dispatch, +}: ResolveEditorContentInput): Promise { + const { parts, contextItemAttrs, selectedCode, slashCommandName } = + processEditorContent(editorState); + + const slashCommandWithInput = processSlashCommand( + slashCommandName, + availableSlashCommands, + parts, + ); + + const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput; + if (shouldGatherContext) { + dispatch(setIsGatheringContext(true)); + } + + const contextItems = await gatherContextItems({ + contextItemAttrs, + modifiers, + ideMessenger, + defaultContextProviders, + parts, + selectedCode, + selectedModelTitle, + }); + + if (shouldGatherContext) { + dispatch(setIsGatheringContext(false)); + } + + return [contextItems, selectedCode, parts, slashCommandWithInput]; +} + +/** + * Processes editor content and extracts parts, context items, code, and slash commands + */ +function processEditorContent(editorState: JSONContent) { + const contextItemAttrs: MentionAttrs[] = []; + const selectedCode: RangeInFile[] = []; + let slashCommandName: string | undefined; + + const parts = (editorState?.content || []).reduce( + (parts, p) => { + switch (p.type) { + case Paragraph.name: { + const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); + + // Only take the first slash command + if (foundSlashCommand && !slashCommandName) { + slashCommandName = foundSlashCommand; + } + + contextItemAttrs.push(...ctxItems); + + if (!text) return parts; + + // Merge with previous text part if possible + if (parts[parts.length - 1]?.type === "text") { + (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; + return parts; + } + + return [...parts, { type: "text", text }]; + } + + case CodeBlock.name: { + if (!p.attrs?.item) { + console.warn("codeBlock has no item attribute"); + return parts; + } + + const contextItem = p.attrs.item as ContextItemWithId; + const rif = ctxItemToRifWithContents(contextItem, true); + selectedCode.push(rif); + + // If editing, only include in selectedCode + if (contextItem.editing) { + return parts; + } + + const fileExtension = getUriFileExtension(rif.filepath); + const codeText = [ + "\n\n```", + fileExtension, + " ", + contextItem.description, + "\n", + contextItem.content, + "\n```", + ].join(""); + + if (parts[parts.length - 1]?.type === "text") { + (parts[parts.length - 1] as TextMessagePart).text += + "\n" + codeText; + return parts; + } + + return [...parts, { type: "text", text: codeText }]; + } + + case Image.name: { + return [ + ...parts, + { + type: "imageUrl", + imageUrl: { url: p.attrs?.src }, + }, + ]; + } + + default: { + console.warn("Unexpected content type", p.type); + return parts; + } + } + }, + [], + ); + + return { parts, contextItemAttrs, selectedCode, slashCommandName }; +} + +/** + * Processes slash commands and prepares the command with input + */ +function processSlashCommand( + slashCommandName: string | undefined, + availableSlashCommands: SlashCommandDescription[], + parts: MessagePart[], +): { command: SlashCommandDescription; input: string } | undefined { + if (!slashCommandName) return; + + const command = availableSlashCommands.find( + (c) => c.name === slashCommandName, + ); + + if (!command) return; + + const lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); + const lastTextPart = parts[lastTextIndex] as TextMessagePart; + + let input: string; + + // Get input and add text of last slash command text back in to last text node + if (lastTextPart) { + // TODO: only input the slash cmd is currently using + // improove this comment + input = renderChatMessage({ + role: "user", + content: lastTextPart.text, + }).trimStart(); + lastTextPart.text = `/${command.name} ${lastTextPart.text}`; + } else { + input = ""; + parts.push({ type: "text", text: `/${command.name}` }); + } + + return { + command, + input, + }; +} + +/** + * Gathers context items from various sources + */ +async function gatherContextItems({ + contextItemAttrs, + modifiers, + ideMessenger, + defaultContextProviders, + parts, + selectedCode, + selectedModelTitle, +}: { + contextItemAttrs: MentionAttrs[]; + modifiers: InputModifiers; + ideMessenger: IIdeMessenger; + defaultContextProviders: DefaultContextProvider[]; + parts: MessagePart[]; + selectedCode: RangeInFile[]; + selectedModelTitle: string; +}): Promise { + let contextItems: ContextItemWithId[] = []; + + // Process context item attributes + for (const item of contextItemAttrs) { + const result = await ideMessenger.request("context/getContextItems", { + name: item.itemType === "contextProvider" ? item.id : item.itemType!, + query: item.query ?? "", + fullInput: stripImages(parts), + selectedCode, + selectedModelTitle, + }); + if (result.status === "success") { + contextItems.push(...result.content); + } + } + + // cmd+enter to use codebase + if (modifiers.useCodebase) { + const result = await ideMessenger.request("context/getContextItems", { + name: "codebase", + query: "", + fullInput: stripImages(parts), + selectedCode, + selectedModelTitle, + }); + + if (result.status === "success") { + contextItems.push(...result.content); + } + } + + // Include default context providers + const defaultContextItems = await Promise.all( + defaultContextProviders.map(async (provider) => { + const result = await ideMessenger.request("context/getContextItems", { + name: provider.name, + query: provider.query ?? "", + fullInput: stripImages(parts), + selectedCode, + selectedModelTitle, + }); + if (result.status === "success") { + return result.content; + } else { + return []; + } + }), + ); + contextItems.push(...defaultContextItems.flat()); + + return contextItems; +} + +function findLastIndex( + array: T[], + predicate: (value: T, index: number, obj: T[]) => boolean, +): number { + for (let i = array.length - 1; i >= 0; i--) { + if (predicate(array[i], i, array)) { + return i; + } + } + return -1; // if no element satisfies the predicate +} + +function resolveParagraph( + p: JSONContent, +): [string, MentionAttrs[], string | undefined] { + const contextItems: MentionAttrs[] = []; + let slashCommand: string | undefined; + + const text = (p.content || []) + .map((child) => { + switch (child.type) { + case Text.name: + return child.text; + case Mention.name: + contextItems.push(child.attrs as MentionAttrs); + return child.attrs?.renderInlineAs ?? child.attrs?.label; + case SlashCommand.name: + if (!slashCommand) { + slashCommand = child.attrs?.id; + return ""; + } + return child.attrs?.label; + default: + console.warn("Unexpected child type", child.type); + return ""; + } + }) + .join("") + .trimStart(); + + return [text, contextItems, slashCommand]; +} diff --git a/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx deleted file mode 100644 index e63e273ad..000000000 --- a/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; -import { ContextItemWithId } from "core"; -import { vscBadgeBackground } from "../.."; -import CodeSnippetPreview from "../../markdown/CodeSnippetPreview"; - -export const CodeBlockComponent = (props: any) => { - const { node, deleteNode, selected, editor, updateAttributes } = props; - const item: ContextItemWithId = node.attrs.item; - const inputId = node.attrs.inputId; - // const contextItems = useSelector( - // (store: RootState) => - // store.session.messages[store.session.messages.length - 1].contextItems, - // ); - // const isFirstContextItem = item.id === contextItems[0]?.id; - const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now - - // Not setting this as a "p" will cause issues with foreign keyboards - // See https://github.com/continuedev/continue/issues/3199 - const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p"; - - return ( - - { - deleteNode(); - }} - /> - - ); -}; diff --git a/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts b/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts deleted file mode 100644 index 0c25d7cca..000000000 --- a/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts +++ /dev/null @@ -1,178 +0,0 @@ -// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts) - -import { mergeAttributes, Node } from "@tiptap/core"; -import { Node as ProseMirrorNode } from "@tiptap/pm/model"; -import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; - -export type SlashCommandOptions = { - HTMLAttributes: Record; - renderText: (props: { - options: SlashCommandOptions; - node: ProseMirrorNode; - }) => string; - suggestion: Omit; -}; - -export const SlashCommandPluginKey = new PluginKey("slashcommand"); - -export const SlashCommand = Node.create({ - name: "slashcommand", - - addOptions() { - return { - HTMLAttributes: {}, - renderText({ options, node }) { - return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`; - }, - suggestion: { - char: "/", - pluginKey: SlashCommandPluginKey, - startOfLine: true, - command: ({ editor, range, props }) => { - // increase range.to by one when the next node is of type "text" - // and starts with a space character - const nodeAfter = editor.view.state.selection.$to.nodeAfter; - const overrideSpace = nodeAfter?.text?.startsWith(" "); - - if (overrideSpace) { - range.to += 1; - } - - editor - .chain() - .focus() - .insertContentAt(range, [ - { - type: this.name, - attrs: props, - }, - { - type: "text", - text: " ", - }, - ]) - .run(); - - window.getSelection()?.collapseToEnd(); - }, - allow: ({ state, range }) => { - const $from = state.doc.resolve(range.from); - const type = state.schema.nodes[this.name]; - const allow = !!$from.parent.type.contentMatch.matchType(type); - - return allow; - }, - }, - }; - }, - - group: "inline", - - inline: true, - - selectable: false, - - atom: true, - - addAttributes() { - return { - id: { - default: null, - parseHTML: (element) => element.getAttribute("data-id"), - renderHTML: (attributes) => { - if (!attributes.id) { - return {}; - } - - return { - "data-id": attributes.id, - }; - }, - }, - - label: { - default: null, - parseHTML: (element) => element.getAttribute("data-label"), - renderHTML: (attributes) => { - if (!attributes.label) { - return {}; - } - - return { - "data-label": attributes.label, - }; - }, - }, - }; - }, - - parseHTML() { - return [ - { - tag: `span[data-type="${this.name}"]`, - }, - ]; - }, - - renderHTML({ node, HTMLAttributes }) { - return [ - "span", - mergeAttributes( - { "data-type": this.name }, - this.options.HTMLAttributes, - HTMLAttributes, - ), - this.options.renderText({ - options: this.options, - node, - }), - ]; - }, - - renderText({ node }) { - return this.options.renderText({ - options: this.options, - node, - }); - }, - - addKeyboardShortcuts() { - return { - Backspace: () => - this.editor.commands.command(({ tr, state }) => { - let isSlashCommand = false; - const { selection } = state; - const { empty, anchor } = selection; - - if (!empty) { - return false; - } - - state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => { - if (node.type.name === this.name) { - isSlashCommand = true; - tr.insertText( - this.options.suggestion.char || "", - pos, - pos + node.nodeSize, - ); - - return false; - } - }); - - return isSlashCommand; - }), - }; - }, - - addProseMirrorPlugins() { - return [ - Suggestion({ - editor: this.editor, - ...this.options.suggestion, - }), - ]; - }, -}); diff --git a/gui/src/components/mainInput/tiptap/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts deleted file mode 100644 index 76a868115..000000000 --- a/gui/src/components/mainInput/tiptap/resolveInput.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { JSONContent } from "@tiptap/react"; -import { - ContextItemWithId, - DefaultContextProvider, - InputModifiers, - MessageContent, - MessagePart, - RangeInFile, - SlashCommandDescription, - TextMessagePart, -} from "core"; -import { ctxItemToRifWithContents } from "core/commands/util"; -import { renderChatMessage, stripImages } from "core/util/messageContent"; -import { getUriFileExtension } from "core/util/uri"; -import { IIdeMessenger } from "../../../context/IdeMessenger"; -import { setIsGatheringContext } from "../../../redux/slices/sessionSlice"; - -interface MentionAttrs { - label: string; - id: string; - itemType?: string; - query?: string; -} - -interface ResolveEditorContentInput { - editorState: JSONContent; - modifiers: InputModifiers; - ideMessenger: IIdeMessenger; - defaultContextProviders: DefaultContextProvider[]; - availableSlashCommands: SlashCommandDescription[]; - selectedModelTitle: string; - dispatch: Dispatch; -} - -/** - * This function converts the input from the editor to a string, resolving any context items - * Context items are appended to the top of the prompt and then referenced within the input - */ -async function resolveEditorContent({ - editorState, - modifiers, - ideMessenger, - defaultContextProviders, - availableSlashCommands, - selectedModelTitle, - dispatch, -}: ResolveEditorContentInput): Promise< - [ - ContextItemWithId[], - RangeInFile[], - MessageContent, - ( - | { - command: SlashCommandDescription; - input: string; - } - | undefined - ), - ] -> { - let parts: MessagePart[] = []; - let contextItemAttrs: MentionAttrs[] = []; - const selectedCode: RangeInFile[] = []; - let slashCommandName: string | undefined = undefined; - let slashCommandWithInput: - | { command: SlashCommandDescription; input: string } - | undefined = undefined; - if (editorState?.content) { - for (const p of editorState.content) { - if (p.type === "paragraph") { - const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - // Only take the first slash command - if (foundSlashCommand && typeof slashCommandName === "undefined") { - slashCommandName = foundSlashCommand; - } - - contextItemAttrs.push(...ctxItems); - - if (text === "") { - continue; - } - - if (parts[parts.length - 1]?.type === "text") { - (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; - } else { - parts.push({ type: "text", text }); - } - } else if (p.type === "codeBlock") { - if (p.attrs?.item) { - const contextItem = p.attrs.item as ContextItemWithId; - const rif = ctxItemToRifWithContents(contextItem, true); - // If not editing, include codeblocks in the prompt - // If editing is handled by selectedCode below - if (!contextItem.editing) { - const fileExtension = getUriFileExtension(rif.filepath); - // let extName = relativeFilepath.split(".").slice(-1)[0]; - const text = - "\n\n" + - "```" + - fileExtension + - " " + - contextItem.description + - "\n" + - contextItem.content + - "\n```"; - if (parts[parts.length - 1]?.type === "text") { - (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; - } else { - parts.push({ - type: "text", - text, - }); - } - } - selectedCode.push(rif); - } else { - console.warn("codeBlock has no item attribute"); - } - } else if (p.type === "image") { - parts.push({ - type: "imageUrl", - imageUrl: { - url: p.attrs?.src, - }, - }); - } else { - console.warn("Unexpected content type", p.type); - } - } - } - - if (slashCommandName) { - const command = availableSlashCommands.find( - (c) => c.name === slashCommandName, - ); - if (command) { - const lastTextIndex = findLastIndex( - parts, - (part) => part.type === "text", - ); - const lastTextPart = parts[lastTextIndex] as TextMessagePart; - - let input: string; - // Get input and add text of last slash command text back in to last text node - if (lastTextPart) { - input = renderChatMessage({ - role: "user", - content: lastTextPart.text, - }).trimStart(); - lastTextPart.text = `/${command.name} ${lastTextPart.text}`; - } else { - input = ""; - parts.push({ type: "text", text: `/${command.name}` }); - } - - slashCommandWithInput = { - command, - input, - }; - } - } - - const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput; - if (shouldGatherContext) { - dispatch(setIsGatheringContext(true)); - } - - let contextItemsText = ""; - let contextItems: ContextItemWithId[] = []; - for (const item of contextItemAttrs) { - const result = await ideMessenger.request("context/getContextItems", { - name: item.itemType === "contextProvider" ? item.id : item.itemType!, - query: item.query ?? "", - fullInput: stripImages(parts), - selectedCode, - selectedModelTitle, - }); - if (result.status === "success") { - const resolvedItems = result.content; - contextItems.push(...resolvedItems); - for (const resolvedItem of resolvedItems) { - contextItemsText += resolvedItem.content + "\n\n"; - } - } - } - - // cmd+enter to use codebase - if (modifiers.useCodebase) { - const result = await ideMessenger.request("context/getContextItems", { - name: "codebase", - query: "", - fullInput: stripImages(parts), - selectedCode, - selectedModelTitle, - }); - - if (result.status === "success") { - const codebaseItems = result.content; - contextItems.push(...codebaseItems); - for (const codebaseItem of codebaseItems) { - contextItemsText += codebaseItem.content + "\n\n"; - } - } - } - - // Include default context providers - const defaultContextItems = await Promise.all( - defaultContextProviders.map(async (provider) => { - const result = await ideMessenger.request("context/getContextItems", { - name: provider.name, - query: provider.query ?? "", - fullInput: stripImages(parts), - selectedCode, - selectedModelTitle, - }); - if (result.status === "success") { - return result.content; - } else { - return []; - } - }), - ); - contextItems.push(...defaultContextItems.flat()); - - if (contextItemsText !== "") { - contextItemsText += "\n"; - } - - if (shouldGatherContext) { - dispatch(setIsGatheringContext(false)); - } - - return [contextItems, selectedCode, parts, slashCommandWithInput]; -} - -function findLastIndex( - array: T[], - predicate: (value: T, index: number, obj: T[]) => boolean, -): number { - for (let i = array.length - 1; i >= 0; i--) { - if (predicate(array[i], i, array)) { - return i; - } - } - return -1; // if no element satisfies the predicate -} - -function resolveParagraph( - p: JSONContent, -): [string, MentionAttrs[], string | undefined] { - let text = ""; - const contextItems: MentionAttrs[] = []; - let slashCommand: string | undefined = undefined; - for (const child of p.content || []) { - if (child.type === "text") { - text += text === "" ? child.text?.trimStart() : child.text; - } else if (child.type === "mention") { - text += - typeof child.attrs?.renderInlineAs === "string" - ? child.attrs.renderInlineAs - : child.attrs?.label; - contextItems.push(child.attrs as MentionAttrs); - } else if (child.type === "slashcommand") { - if (typeof slashCommand === "undefined") { - slashCommand = child.attrs?.id; - } else { - text += child.attrs?.label; - } - } else { - console.warn("Unexpected child type", child.type); - } - } - return [text, contextItems, slashCommand]; -} - -export default resolveEditorContent; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 9f9078303..bc45d19f1 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,6 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; +import { CodeBlock } from "../TipTapEditor"; const isWebEnv = isWebEnvironment(); @@ -103,7 +104,7 @@ export const handleJetBrainsMetaBackspace = (editor: Editor) => { for (let i = doc.content.childCount - 1; i >= 0; i--) { const node = doc.content.child(i); - if (node.type.name === "codeBlock") { + if (node.type.name === CodeBlock.name) { continue; } diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx deleted file mode 100644 index 06717c5ee..000000000 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import { - ChevronDownIcon, - EyeSlashIcon, - XMarkIcon, -} from "@heroicons/react/24/outline"; -import { ContextItemWithId } from "core"; -import { dedent, getMarkdownLanguageTagForFile } from "core/util"; -import { useContext, useEffect, useMemo, useRef, useState } from "react"; -import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscEditorBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { getFontSize } from "../../util"; -import FileIcon from "../FileIcon"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import StyledMarkdownPreview from "./StyledMarkdownPreview"; -import { ctxItemToRifWithContents } from "core/commands/util"; -import { EyeIcon } from "@heroicons/react/24/solid"; -import { useAppSelector } from "../../redux/hooks"; - -const PreviewMarkdownDiv = styled.div<{ - borderColor?: string; -}>` - background-color: ${vscEditorBackground}; - border-radius: ${defaultBorderRadius}; - border: 0.5px solid ${(props) => props.borderColor || lightGray}; - margin-top: 4px; - margin-bottom: 4px; - overflow: hidden; - position: relative; - - & div { - background-color: ${vscEditorBackground}; - } -`; - -interface CodeSnippetPreviewProps { - item: ContextItemWithId; - onDelete?: () => void; - borderColor?: string; - inputId: string; -} - -const MAX_PREVIEW_HEIGHT = 100; - -const backticksRegex = /`{3,}/gm; - -function CodeSnippetPreview(props: CodeSnippetPreviewProps) { - const ideMessenger = useContext(IdeMessengerContext); - - const [localHidden, setLocalHidden] = useState(); - const [isSizeLimited, setIsSizeLimited] = useState(true); - - const newestCodeblockForInputId = useAppSelector( - (store) => store.session.newestCodeblockForInput[props.inputId], - ); - - const hidden = useMemo(() => { - return localHidden ?? newestCodeblockForInputId !== props.item.id.itemId; - }, [localHidden, newestCodeblockForInputId, props.item]); - - const content = useMemo(() => { - return dedent`${props.item.content}`; - }, [props.item.content]); - - const fence = useMemo(() => { - const backticks = content.match(backticksRegex); - return backticks ? backticks.sort().at(-1) + "`" : "```"; - }, [content]); - - const codeBlockRef = useRef(null); - - const [codeblockDims, setCodeblockDims] = useState({ width: 0, height: 0 }); - useEffect(() => { - const resizeObserver = new ResizeObserver(() => { - setCodeblockDims({ - width: codeBlockRef.current?.scrollWidth ?? 0, - height: codeBlockRef.current?.scrollHeight ?? 0, - }); - }); - - if (codeBlockRef.current) { - resizeObserver.observe(codeBlockRef.current); - } - - return () => { - resizeObserver.disconnect(); - }; - }, [codeBlockRef]); - - return ( - -
{ - setLocalHidden(!hidden); - }} - > -
{ - e.stopPropagation(); - if ( - props.item.id.providerTitle === "file" && - props.item.uri?.value - ) { - ideMessenger.post("showFile", { - filepath: props.item.uri.value, - }); - } else if (props.item.id.providerTitle === "code") { - const rif = ctxItemToRifWithContents(props.item, true); - ideMessenger.ide.showLines( - rif.filepath, - rif.range.start.line, - rif.range.end.line, - ); - } else { - ideMessenger.post("showVirtualFile", { - content, - name: props.item.name, - }); - } - }} - > - - {props.item.name} -
-
- - {hidden ? ( - - ) : ( - - )} - - { - e.stopPropagation(); - props.onDelete?.(); - }} - > - - -
-
-
- -
- - {codeblockDims.height > MAX_PREVIEW_HEIGHT && ( - - setIsSizeLimited((v) => !v)} - /> - - )} -
- ); -} - -export default CodeSnippetPreview; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 71e7ca9cf..0da1c5c7f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -7,6 +7,7 @@ import Spinner from "../../gui/Spinner"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; interface ApplyActionsProps { + disableManualApply?: boolean; applyState?: ApplyState; onClickAccept: () => void; onClickReject: () => void; @@ -59,8 +60,8 @@ export default function ApplyActions(props: ApplyActionsProps) { ); case "done": return ( -
- +
+ {`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`} {` remaining`} @@ -90,10 +91,15 @@ export default function ApplyActions(props: ApplyActionsProps) { ); } - + if (props.disableManualApply) { + return null; + } return applyButton("Reapply"); } default: + if (props.disableManualApply) { + return null; + } return applyButton("Apply"); } } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c2f09a24a..ee46ccee8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -1,8 +1,8 @@ -import FileIcon from "../../FileIcon"; +import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; +import { getLastNPathParts } from "core/util/uri"; import { useContext } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { getLastNPathParts, getUriPathBasename } from "core/util/uri"; -import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; +import FileIcon from "../../FileIcon"; export interface FileInfoProps { relativeFilepath: string; @@ -23,17 +23,17 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { } return ( -
-
+
+
- - {getLastNPathParts(relativeFilepath, 1)} - {range && ` ${range}`} -
+ + {getLastNPathParts(relativeFilepath, 1)} + {range && ` ${range}`} +
); }; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 46fa90d68..f09ed1a9f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -3,7 +3,6 @@ import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; import { debounce } from "lodash"; import { useContext, useEffect, useRef, useState } from "react"; import styled from "styled-components"; -import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, vscCommandCenterInactiveBorder, @@ -26,6 +25,8 @@ import GeneratingCodeLoader from "./GeneratingCodeLoader"; import RunInTerminalButton from "./RunInTerminalButton"; const TopDiv = styled.div` + display: flex; + flex-direction: column; outline: 1px solid ${vscCommandCenterInactiveBorder}; outline-offset: -0.5px; border-radius: ${defaultBorderRadius}; @@ -38,7 +39,6 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>` display: flex; justify-content: space-between; align-items: center; - background: inherit; font-size: ${getFontSize() - 2}px; padding: 4px 6px; margin: 0; @@ -52,42 +52,32 @@ export interface StepContainerPreToolbarProps { relativeFilepath: string; isGeneratingCodeBlock: boolean; codeBlockIndex: number; // To track which codeblock we are applying + codeBlockStreamId: string; range?: string; children: any; expanded?: boolean; - hideApply?: boolean; + disableManualApply?: boolean; } export default function StepContainerPreToolbar( props: StepContainerPreToolbarProps, ) { const ideMessenger = useContext(IdeMessengerContext); - const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isInEditMode = useAppSelector(selectIsInEditMode); const [isExpanded, setIsExpanded] = useState( props.expanded ?? (isInEditMode ? false : true), ); const [codeBlockContent, setCodeBlockContent] = useState(""); - const isStreaming = useAppSelector((state) => state.session.isStreaming); const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, streamIdRef.current), + selectApplyStateByStreamId(state, props.codeBlockStreamId), ); - // This handles an edge case when the last node in the markdown syntax tree is a codeblock. - // In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if - // we are done generating based on whether the next node in the tree is not a codeblock. - // The tree parsing logic for Remark is defined on page load, so we can't access state - // during the actual tree parsing. - const isGeneratingCodeBlock = !isStreaming - ? false - : props.isGeneratingCodeBlock; - const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath); @@ -104,7 +94,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, filepath: fileUri, text: codeBlockContent, curSelectedModelTitle: defaultModel.title, @@ -135,19 +125,17 @@ export default function StepContainerPreToolbar( } }, [props.children, codeBlockContent]); - // Temporarily disabling auto apply for Edit mode // useEffect(() => { // const hasCompletedGenerating = // wasGeneratingRef.current && !isGeneratingCodeBlock; - // const shouldAutoApply = hasCompletedGenerating && isInEditMode; - - // if (shouldAutoApply) { - // onClickApply(); - // } - // wasGeneratingRef.current = isGeneratingCodeBlock; - // }, [isGeneratingCodeBlock]); + // if (hasCompletedGenerating) { + // if (props.autoApply) { + // onClickApply(); + // } + // } + // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( @@ -156,7 +144,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("acceptDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } @@ -167,7 +155,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("rejectDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } @@ -183,44 +171,40 @@ export default function StepContainerPreToolbar( return ( - -
+ +
-
- -
+
- {isGeneratingCodeBlock && ( + {props.isGeneratingCodeBlock ? ( - )} - - {!isGeneratingCodeBlock && ( + ) : ( <> - {props.hideApply || - (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - - ) : ( - - ))} + {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( + + ) : ( + + )} )}
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index d968101d0..6af2f68d5 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,5 +1,5 @@ import { ctxItemToRifWithContents } from "core/commands/util"; -import { memo, useEffect, useMemo } from "react"; +import { memo, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -17,7 +17,7 @@ import useUpdatingRef from "../../hooks/useUpdatingRef"; import { useAppSelector } from "../../redux/hooks"; import { selectUIConfig } from "../../redux/slices/configSlice"; import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols"; -import { getFontSize, isJetBrains } from "../../util"; +import { getFontSize } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; @@ -69,7 +69,7 @@ const StyledMarkdown = styled.div<{ overflow-x: scroll; overflow-y: hidden; - padding: 16px 8px; + padding: 8px; } code { @@ -114,10 +114,6 @@ const StyledMarkdown = styled.div<{ line-height: 1.5; } - > *:first-child { - margin-top: 8px; - } - > *:last-child { margin-bottom: 0; } @@ -130,6 +126,9 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; + disableManualApply?: boolean; + singleCodeblockStreamId?: string; + expandCodeblocks?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -196,6 +195,29 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }, [props.itemIndex, history, allSymbols]); const pastFileInfoRef = useUpdatingRef(pastFileInfo); + const isLastItem = useMemo(() => { + return props.itemIndex && props.itemIndex === history.length - 1; + }, [history.length, props.itemIndex]); + const isLastItemRef = useUpdatingRef(isLastItem); + + const isStreaming = useAppSelector((store) => store.session.isStreaming); + const isStreamingRef = useUpdatingRef(isStreaming); + + const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( + [], + ); + + useEffect(() => { + if (props.singleCodeblockStreamId) { + codeblockState.current = [ + { + streamId: props.singleCodeblockStreamId, + isGenerating: false, + }, + ]; + } + }, [props.singleCodeblockStreamId]); + const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ remarkTables, @@ -219,8 +241,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( node.data = node.data || {}; node.data.hProperties = node.data.hProperties || {}; - node.data.hProperties["data-isgeneratingcodeblock"] = - lastCodeNode === node; + node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node; node.data.hProperties["data-codeblockcontent"] = node.value; if (node.meta) { @@ -282,8 +303,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const { className, range } = preChildProps; const relativeFilePath = preChildProps["data-relativefilepath"]; const codeBlockContent = preChildProps["data-codeblockcontent"]; - const isGeneratingCodeBlock = - preChildProps["data-isgeneratingcodeblock"]; if (!props.isRenderingInStepContainer) { return ; @@ -291,11 +310,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const language = getLanguageFromClassName(className); - // If we don't have a filepath show the more basic toolbar - // that is just action buttons on hover. - // We also use this in JB since we haven't yet implemented - // the logic forfileUri lazy apply. - if (!relativeFilePath || isJetBrains()) { + if (!relativeFilePath) { return ( diff --git a/gui/src/components/modelSelection/platform/AssistantIcon.tsx b/gui/src/components/modelSelection/platform/AssistantIcon.tsx index 9f4bfcd0b..c901bfdf4 100644 --- a/gui/src/components/modelSelection/platform/AssistantIcon.tsx +++ b/gui/src/components/modelSelection/platform/AssistantIcon.tsx @@ -10,7 +10,15 @@ export interface AssistantIconProps { export default function AssistantIcon({ assistant, size }: AssistantIconProps) { const sizeTw = size ?? 4; if (isLocalProfile(assistant)) { - return ; + return ( +
+ +
+ ); } else if (assistant.iconUrl) { return ( { + const tinyFont = useFontSize(-4); + const navigate = useNavigate(); const hasFatalErrors = useMemo(() => { @@ -79,25 +81,30 @@ const AssistantSelectOption = ({ disabled={hasFatalErrors} onClick={!hasFatalErrors ? handleOptionClick : undefined} fontSizeModifier={-2} + className={selected ? "bg-list-active text-list-active-foreground" : ""} > -
-
-
-
+
+
+
+
{profile.title}
-
-
{selected ? : null}
+
{!profile.errors?.length ? ( isLocalProfile(profile) ? ( { e.stopPropagation(); e.preventDefault(); @@ -106,7 +113,7 @@ const AssistantSelectOption = ({ /> ) : ( { e.stopPropagation(); e.preventDefault(); @@ -143,9 +150,7 @@ export default function AssistantSelect() { const buttonRef = useRef(null); const { selectedProfile, selectedOrganization } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); - const isLumpToolbarExpanded = useAppSelector( - (state) => state.ui.isBlockSettingsToolbarExpanded, - ); + const { isToolbarExpanded } = useLump(); const { profiles, session, login } = useAuth(); const navigate = useNavigate(); @@ -205,7 +210,7 @@ export default function AssistantSelect() { > Create your first assistant @@ -227,7 +232,7 @@ export default function AssistantSelect() {
{selectedProfile.title} @@ -239,9 +244,9 @@ export default function AssistantSelect() { - +
{profiles?.map((profile, idx) => { return ( @@ -268,8 +273,13 @@ export default function AssistantSelect() { fontSizeModifier={-2} onClick={session ? onNewAssistant : () => login(false)} > -
- +
+ New Assistant
@@ -287,22 +297,32 @@ export default function AssistantSelect() { fontSize: tinyFont, }} > - + {getMetaKeyLabel()} ⇧ ' to toggle
navigate(ROUTES.CONFIG)} > {selectedOrganization?.iconUrl ? ( ) : ( )} - + {selectedOrganization?.name || "Personal"}
diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index d90259a9b..ded57ee08 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -16,10 +16,14 @@ import { } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { + acceptToolCall, addContextItemsAtIndex, setInactive, + setToolCallOutput, + updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; +import { streamResponseAfterToolCall } from "../redux/thunks"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; @@ -245,6 +249,42 @@ function useSetup() { }, [defaultModel], ); + + const activeToolStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); + useWebviewListener( + "updateApplyState", + async (state) => { + // dispatch( + // updateCurCheckpoint({ + // filepath: state.filepath, + // content: state.fileContent, + // }), + // ); + dispatch(updateApplyState(state)); + if ( + activeToolStreamId && + state.streamId === activeToolStreamId[0] && + state.status === "closed" + ) { + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; + dispatch(acceptToolCall()); + dispatch(setToolCallOutput([])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolStreamId[1], + toolOutput: [], + }), + ); + } + }, + [activeToolStreamId], + ); } export default useSetup; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index aea4bdadb..682671cbb 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -21,7 +21,7 @@ import TimelineItem from "../../components/gui/TimelineItem"; import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; @@ -75,6 +75,8 @@ const StepsDiv = styled.div` } `; +export const MAIN_EDITOR_INPUT_ID = "main-editor-input"; + function fallbackRender({ error, resetErrorBoundary }: any) { // Call resetErrorBoundary() to reset the error boundary and retry the render. @@ -295,7 +297,7 @@ export function Chat() { 0 ? "flex-1" : ""}`} + className={`mt-3 overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} > {highlights} {history.map((item, index: number) => ( @@ -406,7 +408,7 @@ export function Chat() { onEnter={(editorState, modifiers, editor) => sendInput(editorState, modifiers, undefined, editor) } - inputId={"main-editor"} + inputId={MAIN_EDITOR_INPUT_ID} /> )} diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index bca805f45..45396dc23 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -7,9 +7,13 @@ interface CreateFileToolCallProps { } export function CreateFile(props: CreateFileToolCallProps) { - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "test.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; return props.relativeFilepath ? ( - + ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx new file mode 100644 index 000000000..80927e6e7 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -0,0 +1,54 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import { useMemo } from "react"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import { useAppSelector } from "../../../redux/hooks"; + +type EditToolCallProps = { + relativeFilePath: string; + newContents: string; + toolCallId?: string; +}; + +export function EditFile(props: EditToolCallProps) { + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const states = useAppSelector((store) => store.session.codeBlockApplyStates); + + const applyState = useMemo(() => { + return states.states.find( + (state) => state.toolCallId && state.toolCallId === props.toolCallId, + ); + }, [states, props.toolCallId]); + + if (!props.relativeFilePath) { + return null; + } + + return ( + <> + + {/* TODO better indicator of generation at bottom */} + {/* {isStreaming && applyState?.status === "streaming" && ( +
+ Generating... +
+ )} */} + {!isStreaming && applyState?.status === "done" && ( +
+ {}} + /> +
+ )} + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 52b41f505..55ed79e2a 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,5 +1,7 @@ -import { ToolCall, ToolCallDelta, ToolCallState } from "core"; +import { ToolCallDelta, ToolCallState } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { CreateFile } from "./CreateFile"; +import { EditFile } from "./EditFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ @@ -12,14 +14,22 @@ function FunctionSpecificToolCallDiv({ const args = toolCallState.parsedArgs; switch (toolCall.function?.name) { - case "builtin_create_new_file": + case BuiltInToolNames.CreateNewFile: return ( ); - case "builtin_run_terminal_command": + case BuiltInToolNames.EditExistingFile: + return ( + + ); + case BuiltInToolNames.RunTerminalCommand: return ( ; + activeToolStreamId?: [string, string]; + newestToolbarPreviewForInput: Record; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -91,7 +93,7 @@ const initialState: SessionState = { curIndex: 0, }, lastSessionId: undefined, - newestCodeblockForInput: {}, + newestToolbarPreviewForInput: {}, }; export const sessionSlice = createSlice({ @@ -353,16 +355,32 @@ export const sessionSlice = createSlice({ if (message.role === "assistant" && message.toolCalls?.[0]) { const toolCallDelta = message.toolCalls[0]; if ( - toolCallDelta.id && - toolCallDelta.function?.arguments && - toolCallDelta.function?.name && - toolCallDelta.type + !( + toolCallDelta.id && + toolCallDelta.function?.arguments && + toolCallDelta.function?.name && + toolCallDelta.type + ) ) { console.warn( "Received streamed tool call without required fields", toolCallDelta, ); } + + if ( + toolCallDelta.id && + toolCallDelta.function?.name === + BuiltInToolNames.EditExistingFile + ) { + const streamId = uuidv4(); + state.codeBlockApplyStates.states.push({ + streamId, + toolCallId: toolCallDelta.id, + status: "streaming", + }); + state.activeToolStreamId = [streamId, toolCallDelta.id]; + } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -626,6 +644,7 @@ export const sessionSlice = createSlice({ toolCallState.status = "canceled"; }, acceptToolCall: (state) => { + state.activeToolStreamId = undefined; const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -648,7 +667,7 @@ export const sessionSlice = createSlice({ const nextIndex = (currentIndex + 1) % modes.length; state.mode = modes[nextIndex] as MessageModes; }, - setNewestCodeblocksForInput: ( + setNewestToolbarPreviewForInput: ( state, { payload, @@ -657,7 +676,8 @@ export const sessionSlice = createSlice({ contextItemId: string; }>, ) => { - state.newestCodeblockForInput[payload.inputId] = payload.contextItemId; + state.newestToolbarPreviewForInput[payload.inputId] = + payload.contextItemId; }, }, selectors: { @@ -716,7 +736,7 @@ export const selectCurrentToolCall = createSelector( export const selectApplyStateByStreamId = createSelector( [ (state: RootState) => state.session.codeBlockApplyStates.states, - (state: RootState, streamId: string) => streamId, + (state: RootState, streamId?: string) => streamId, ], (states, streamId) => { return states.find((state) => state.streamId === streamId); @@ -758,7 +778,7 @@ export const { addSessionMetadata, updateSessionMetadata, deleteSessionMetadata, - setNewestCodeblocksForInput, + setNewestToolbarPreviewForInput, cycleMode, } = sessionSlice.actions; diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index ba4801197..0ea07b190 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -25,7 +25,6 @@ type UIState = { toolSettings: { [toolName: string]: ToolSetting }; toolGroupSettings: { [toolGroupName: string]: ToolGroupSetting }; ttsActive: boolean; - isBlockSettingsToolbarExpanded: boolean; }; export const DEFAULT_TOOL_SETTING: ToolSetting = "allowedWithPermission"; @@ -45,6 +44,7 @@ export const uiSlice = createSlice({ ttsActive: false, toolSettings: { [BuiltInToolNames.ReadFile]: "allowedWithoutPermission", + [BuiltInToolNames.EditExistingFile]: "allowedWithPermission", [BuiltInToolNames.CreateNewFile]: "allowedWithPermission", [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission", [BuiltInToolNames.GrepSearch]: "allowedWithoutPermission", @@ -56,7 +56,6 @@ export const uiSlice = createSlice({ toolGroupSettings: { BUILT_IN_GROUP_NAME: "include", }, - isBlockSettingsToolbarExpanded: true, } as UIState, reducers: { setOnboardingCard: ( @@ -124,10 +123,6 @@ export const uiSlice = createSlice({ setTTSActive: (state, { payload }: PayloadAction) => { state.ttsActive = payload; }, - toggleBlockSettingsToolbar: (state) => { - state.isBlockSettingsToolbarExpanded = - !state.isBlockSettingsToolbarExpanded; - }, }, }); @@ -142,7 +137,6 @@ export const { toggleToolGroupSetting, addTool, setTTSActive, - toggleBlockSettingsToolbar, } = uiSlice.actions; export default uiSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 8aff8e1de..f321f0dae 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -127,7 +127,9 @@ export function setupStore() { ideMessenger: new IdeMessenger(), }, }, - }).concat(logger), + }), + // This can be uncommented to get detailed Redux logs + // .concat(logger), }); } diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 34ae00390..bf15e7ae8 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,4 +1,9 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { ContextItem } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; +import { EditToolArgs } from "core/tools/definitions/editFile"; +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { @@ -6,6 +11,7 @@ import { cancelToolCall, setCalling, setToolCallOutput, + updateApplyState, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -31,28 +37,59 @@ export const callTool = createAsyncThunk( dispatch(setCalling()); - const result = await extra.ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - selectedModelTitle: defaultModel.title, - }); + let errorMessage = ""; + let output: ContextItem[] | undefined = undefined; - if (result.status === "success") { - const contextItems = result.content.contextItems; - dispatch(setToolCallOutput(contextItems)); - dispatch(acceptToolCall()); - - // Send to the LLM to continue the conversation - const response = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCall.id, - toolOutput: contextItems, - }), + if ( + toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile + ) { + const args = JSON.parse( + toolCallState.toolCall.function.arguments || "{}", ); - unwrapResult(response); + try { + if (!state.session.activeToolStreamId) { + throw new Error("Invalid apply state"); + } + await customGuiEditImpl( + args, + extra.ideMessenger, + state.session.activeToolStreamId[0], + defaultModel.title, + toolCallState.toolCallId, + ); + } catch (e) { + errorMessage = "Failed to call edit tool"; + if (e instanceof Error) { + errorMessage = e.message; + } + if (state.session.activeToolStreamId?.[0]) { + dispatch( + updateApplyState({ + streamId: state.session.activeToolStreamId[0], + status: "closed", + toolCallId: toolCallState.toolCallId, + numDiffs: 0, + filepath: args.filepath, + }), + ); + } + } } else { + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + selectedModelTitle: defaultModel.title, + }); + if (result.status === "error") { + errorMessage = result.error; + } else { + output = result.content.contextItems; + } + } + + if (errorMessage) { dispatch(cancelToolCall()); - const output = await dispatch( + const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, toolOutput: [ @@ -60,13 +97,52 @@ export const callTool = createAsyncThunk( icon: "problems", name: "Tool Call Error", description: "Tool Call Failed", - content: `The tool call failed with the message:\n\n${result.error}\n\nPlease try something else or request further instructions.`, + content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, hidden: false, }, ], }), ); - unwrapResult(output); + unwrapResult(wrapped); + } else if (output) { + dispatch(setToolCallOutput(output)); + dispatch(acceptToolCall()); + + // Send to the LLM to continue the conversation + const wrapped = await dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCall.id, + toolOutput: output, + }), + ); + unwrapResult(wrapped); } + // okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool }, ); + +async function customGuiEditImpl( + args: EditToolArgs, + ideMessenger: IIdeMessenger, + streamId: string, + modelTitle: string, + toolCallId: string, +) { + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + ideMessenger.ide, + ); + if (!firstUriMatch) { + throw new Error(`${args.filepath} does not exist`); + } + const apply = await ideMessenger.request("applyToFile", { + streamId, + text: args.new_contents, + curSelectedModelTitle: modelTitle, + toolCallId, + filepath: firstUriMatch, + }); + if (apply.status === "error") { + throw new Error(apply.error); + } +} diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 1c38e965b..450471164 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -8,7 +8,7 @@ import { SlashCommandDescription, } from "core"; import * as URI from "uri-js"; -import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { selectDefaultModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts index 05396c3ed..49e259421 100644 --- a/gui/src/redux/thunks/updateFileSymbols.ts +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -1,7 +1,8 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { ThunkApiType } from "../store"; -import { updateFileSymbols } from "../slices/sessionSlice"; import { ChatHistoryItem, ContextItemWithId } from "core"; +import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions"; +import { updateFileSymbols } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; export function getContextItemsFromHistory( historyItems: ChatHistoryItem[], @@ -25,7 +26,7 @@ export function getContextItemsFromHistory( .flatMap((item) => item.editorState.content) .filter( (content) => - content?.type === "codeBlock" && + content?.type === CodeBlock.name && content?.attrs?.item?.uri?.value && content.attrs.item.uri?.type === "file", ) diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index 67677e103..fe2b8c0e4 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -33,6 +33,8 @@ module.exports = { "vsc-editor-background": "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))", "vsc-input-border": "var(--vscode-input-border, #999998)", + "vsc-commandCenter-inactiveBorder": + "var(--vscode-commandCenter-inactiveBorder, #999998)", // Starting to make things less vsc-specific // TODO make it all non-IDE-specific naming diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index d7d96c4f0..703632362 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.67", + "version": "1.0.71", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/README.md b/packages/config-yaml/src/README.md index 4ef80cb49..c68cd8fdc 100644 --- a/packages/config-yaml/src/README.md +++ b/packages/config-yaml/src/README.md @@ -15,3 +15,14 @@ This happens on the server, unless using local mode. ## Client rendering The unrolled config.yaml is then rendered on the client. This is done by replacing all user secret template variables with their values and replacing all other secrets with secret locations. + +## Publishing + +Make sure you are logged into the npm registry with `npm login`. + +Then, bump the version in `package.json` and then run: + +```bash +npm run build +npm publish --access public +``` diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index f376fbc84..92a0b0157 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -17,6 +17,7 @@ import { blockSchema, ConfigYaml, configYamlSchema, + Rule, } from "../schemas/index.js"; import { useProxyForUnrenderedSecrets } from "./clientRender.js"; @@ -62,7 +63,7 @@ export function parseBlock(configYaml: string): Block { } } -const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; +export const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; export function getTemplateVariables(templatedYaml: string): string[] { const variables = new Set(); @@ -313,13 +314,13 @@ export async function unrollBlocks( } } - // Rules are a bit different because they're just strings, so handle separately + // Rules are a bit different because they can be strings, so hanlde separately if (assistant.rules) { - const rules: string[] = []; + const rules: Rule[] = []; for (const rule of assistant.rules) { - if (typeof rule === "string") { + if (typeof rule === "string" || !("uses" in rule)) { rules.push(rule); - } else { + } else if ("uses" in rule) { const blockConfigYaml = await resolveBlock( decodeFullSlug(rule.uses), rule.with, diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1ca03b0b6..ae12c99a7 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -28,6 +28,16 @@ const docSchema = z.object({ faviconUrl: z.string().optional(), }); +const ruleObjectSchema = z.object({ + name: z.string(), + rule: z.string(), + if: z.string().optional(), +}); + +const ruleSchema = z.union([z.string(), ruleObjectSchema]); + +export type Rule = z.infer; + export const blockItemWrapperSchema = (schema: T) => z.object({ uses: z.string(), @@ -63,7 +73,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ rules: z .array( z.union([ - z.string(), + ruleSchema, z.object({ uses: z.string(), with: z.record(z.string()).optional(), @@ -82,7 +92,7 @@ export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ context: z.array(contextSchema).optional(), data: z.array(dataSchema).optional(), mcpServers: z.array(mcpServerSchema).optional(), - rules: z.array(z.string()).optional(), + rules: z.array(ruleSchema).optional(), prompts: z.array(promptSchema).optional(), docs: z.array(docSchema).optional(), }); @@ -95,7 +105,9 @@ export const blockSchema = baseConfigYamlSchema.and( z.object({ context: z.array(contextSchema).length(1) }), z.object({ data: z.array(dataSchema).length(1) }), z.object({ mcpServers: z.array(mcpServerSchema).length(1) }), - z.object({ rules: z.array(z.string()).length(1) }), + z.object({ + rules: z.array(ruleSchema).length(1), + }), z.object({ prompts: z.array(promptSchema).length(1) }), z.object({ docs: z.array(docSchema).length(1) }), ]), diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 6a7097284..e0a924706 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.4", + "version": "1.0.5", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 01fc631db..d4e8145d0 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -15,9 +15,9 @@ export function fetchwithRequestOptions( init?: RequestInit, requestOptions?: RequestOptions, ): Promise { - let url = url_; - if (typeof url === "string") { - url = new URL(url); + const url = typeof url_ === "string" ? new URL(url_) : url_; + if (url.host === "localhost") { + url.host = "127.0.0.1"; } const TIMEOUT = 7200; // 7200 seconds = 2 hours diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index d0e8e4633..7f33e377d 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -2,6 +2,7 @@ export async function* toAsyncIterable( nodeReadable: NodeJS.ReadableStream, ): AsyncGenerator { for await (const chunk of nodeReadable) { + // @ts-expect-error yield chunk as Uint8Array; } }