From 1e699f15d4fa0c71e50062d296f2f6d04ffd6a42 Mon Sep 17 00:00:00 2001 From: Lester Hairston Date: Fri, 27 Sep 2024 16:40:53 -0500 Subject: [PATCH 01/25] adding discord provider --- core/context/providers/DiscordContext.ts | 147 +++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 core/context/providers/DiscordContext.ts diff --git a/core/context/providers/DiscordContext.ts b/core/context/providers/DiscordContext.ts new file mode 100644 index 000000000..6a3615e09 --- /dev/null +++ b/core/context/providers/DiscordContext.ts @@ -0,0 +1,147 @@ +import { AxiosError, AxiosInstance } from "axios"; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, +} from "../../index.js"; +import { BaseContextProvider } from "../index.js"; + +// Define helper interfaces for Discord responses +export interface DiscordChannel { + id: string; + name?: string; + icon?: string; + topic?: string; + guild_id?: string; // The ID of the guild (server) that the channel belongs to +} + +interface DiscordMessage { + id: string; + content: string; + author: { + id: string; + username: string; + }; + timestamp: string; +} + +class DiscordContextProvider extends BaseContextProvider { + // Description for the context provider + static description: ContextProviderDescription = { + title: "discord-messages", + displayTitle: "Discord Messages", + description: "Reference messages from a Discord channel", + type: "normal", + }; + + // Helper function to get the Axios instance with proper authorization + private async getApi(): Promise { + const { default: Axios } = await import("axios"); + const token = this.options.token; + if (!token) { + throw new Error("Discord Bot Token is required!"); + } + + return Axios.create({ + baseURL: "https://discord.com/api/v10", + headers: { + Authorization: `Bot ${token}`, + }, + }); + } + + // Reusable error handling method + private handleApiError(ex: unknown): string { + let content = "# Discord API Error\n\nFailed to retrieve data. "; + if (ex instanceof AxiosError) { + if (ex.response) { + const errorMessage = ex.response?.data + ? (ex.response.data.message ?? JSON.stringify(ex.response?.data)) + : `${ex.response.status}: ${ex.response.statusText}`; + content += `Discord API Error: ${errorMessage}`; + } else { + content += `Discord API Request Error ${ex.request}`; + } + } else { + content += `Unknown error: ${ex instanceof Error ? ex.message : JSON.stringify(ex)}`; + } + return content; + } + + // Fetch Discord channels + private async fetchChannels( + extras: ContextProviderExtras, + ): Promise> { + const api = await this.getApi(); + + try { + const response = await api.get>( + `/guilds/${this.options.guildId}/channels`, + ); + return response.data; + } catch (ex) { + throw new Error(this.handleApiError(ex)); + } + } + + // Fetch messages from a specific channel + private async fetchMessages( + channelId: string, + extras: ContextProviderExtras, + ): Promise> { + const api = await this.getApi(); + try { + const response = await api.get>( + `/channels/${channelId}/messages`, + { params: { limit: 10 } }, + ); + return response.data; + } catch (ex) { + throw new Error(this.handleApiError(ex)); + } + } + + // Main function to get context items (channels and messages) + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const result = [] as Array; + + try { + // Fetch channels + const channels = await this.fetchChannels(extras); + + // Fetch messages for each channel in parallel + const channelMessagePromises = channels.map(async (channel) => { + const messages = await this.fetchMessages(channel.id, extras); + const parts = [ + `# Discord Channel: ${channel.name}`, + ...messages.map( + (message) => + `- ${message.author.username}: ${message.content} (at ${message.timestamp})`, + ), + ]; + + return { + name: `Messages from ${channel.name}`, + content: parts.join("\n"), + description: `Latest messages from the channel ${channel.name}`, + }; + }); + + const channelMessageItems = await Promise.all(channelMessagePromises); + result.push(...channelMessageItems); + } catch (ex) { + result.push({ + name: "Discord Error", + content: this.handleApiError(ex), + description: "Error fetching data from Discord.", + }); + } + + return result; + } +} + +export default DiscordContextProvider; From 6da94c48646ca13d9a8a23cfeef3f8731c01b075 Mon Sep 17 00:00:00 2001 From: Lester Hairston Date: Sun, 29 Sep 2024 20:33:48 -0500 Subject: [PATCH 02/25] updated the provider for multichannel support --- core/context/providers/DiscordContext.ts | 147 --------------- .../providers/DiscordContextProvider.ts | 168 ++++++++++++++++++ core/context/providers/index.ts | 2 + .../src/main/resources/config_schema.json | 73 ++++++++ extensions/vscode/config_schema.json | 66 +++++++ extensions/vscode/continue_rc_schema.json | 83 +++++++++ 6 files changed, 392 insertions(+), 147 deletions(-) delete mode 100644 core/context/providers/DiscordContext.ts create mode 100644 core/context/providers/DiscordContextProvider.ts diff --git a/core/context/providers/DiscordContext.ts b/core/context/providers/DiscordContext.ts deleted file mode 100644 index 6a3615e09..000000000 --- a/core/context/providers/DiscordContext.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { AxiosError, AxiosInstance } from "axios"; -import { - ContextItem, - ContextProviderDescription, - ContextProviderExtras, -} from "../../index.js"; -import { BaseContextProvider } from "../index.js"; - -// Define helper interfaces for Discord responses -export interface DiscordChannel { - id: string; - name?: string; - icon?: string; - topic?: string; - guild_id?: string; // The ID of the guild (server) that the channel belongs to -} - -interface DiscordMessage { - id: string; - content: string; - author: { - id: string; - username: string; - }; - timestamp: string; -} - -class DiscordContextProvider extends BaseContextProvider { - // Description for the context provider - static description: ContextProviderDescription = { - title: "discord-messages", - displayTitle: "Discord Messages", - description: "Reference messages from a Discord channel", - type: "normal", - }; - - // Helper function to get the Axios instance with proper authorization - private async getApi(): Promise { - const { default: Axios } = await import("axios"); - const token = this.options.token; - if (!token) { - throw new Error("Discord Bot Token is required!"); - } - - return Axios.create({ - baseURL: "https://discord.com/api/v10", - headers: { - Authorization: `Bot ${token}`, - }, - }); - } - - // Reusable error handling method - private handleApiError(ex: unknown): string { - let content = "# Discord API Error\n\nFailed to retrieve data. "; - if (ex instanceof AxiosError) { - if (ex.response) { - const errorMessage = ex.response?.data - ? (ex.response.data.message ?? JSON.stringify(ex.response?.data)) - : `${ex.response.status}: ${ex.response.statusText}`; - content += `Discord API Error: ${errorMessage}`; - } else { - content += `Discord API Request Error ${ex.request}`; - } - } else { - content += `Unknown error: ${ex instanceof Error ? ex.message : JSON.stringify(ex)}`; - } - return content; - } - - // Fetch Discord channels - private async fetchChannels( - extras: ContextProviderExtras, - ): Promise> { - const api = await this.getApi(); - - try { - const response = await api.get>( - `/guilds/${this.options.guildId}/channels`, - ); - return response.data; - } catch (ex) { - throw new Error(this.handleApiError(ex)); - } - } - - // Fetch messages from a specific channel - private async fetchMessages( - channelId: string, - extras: ContextProviderExtras, - ): Promise> { - const api = await this.getApi(); - try { - const response = await api.get>( - `/channels/${channelId}/messages`, - { params: { limit: 10 } }, - ); - return response.data; - } catch (ex) { - throw new Error(this.handleApiError(ex)); - } - } - - // Main function to get context items (channels and messages) - async getContextItems( - query: string, - extras: ContextProviderExtras, - ): Promise { - const result = [] as Array; - - try { - // Fetch channels - const channels = await this.fetchChannels(extras); - - // Fetch messages for each channel in parallel - const channelMessagePromises = channels.map(async (channel) => { - const messages = await this.fetchMessages(channel.id, extras); - const parts = [ - `# Discord Channel: ${channel.name}`, - ...messages.map( - (message) => - `- ${message.author.username}: ${message.content} (at ${message.timestamp})`, - ), - ]; - - return { - name: `Messages from ${channel.name}`, - content: parts.join("\n"), - description: `Latest messages from the channel ${channel.name}`, - }; - }); - - const channelMessageItems = await Promise.all(channelMessagePromises); - result.push(...channelMessageItems); - } catch (ex) { - result.push({ - name: "Discord Error", - content: this.handleApiError(ex), - description: "Error fetching data from Discord.", - }); - } - - return result; - } -} - -export default DiscordContextProvider; diff --git a/core/context/providers/DiscordContextProvider.ts b/core/context/providers/DiscordContextProvider.ts new file mode 100644 index 000000000..f1282070a --- /dev/null +++ b/core/context/providers/DiscordContextProvider.ts @@ -0,0 +1,168 @@ +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../index.js"; +import { BaseContextProvider } from "../index.js"; +import axios, { AxiosInstance } from "axios"; + +// Define helper interfaces for Discord responses +export interface DiscordChannel { + id: string; + name?: string; // Optional field + icon?: string; + topic?: string; + type?: number; + guild_id?: string; // The ID of the guild (server) that the channel belongs to +} + +interface DiscordMessage { + id: string; + content: string; + author: { + id: string; + username: string; + }; + timestamp: string; +} + +class DiscordContextProvider extends BaseContextProvider { + // Description for the context provider + static description: ContextProviderDescription = { + title: "discord", + displayTitle: "Discord", + description: "Reference Discord messages from a channel", + type: "submenu", + }; + + private baseUrl = "https://discord.com/api/v10"; + + // Helper function to get the Axios instance with proper authorization + private getApi(): AxiosInstance { + const token = this.options.discordKey; + if (!token) { + throw new Error("Discord Bot Token is required!"); + } + + return axios.create({ + baseURL: this.baseUrl, + headers: { + Authorization: `Bot ${token}`, + "Content-Type": "application/json", + }, + }); + } + + // Fetch Discord messages from a specific channel using Axios + async fetchMessages(channelId: string): Promise> { + const api = this.getApi(); + + try { + const response = await api.get>( + `/channels/${channelId}/messages`, + ); + return response.data; + } catch (error) { + console.error("Error fetching messages:", error); + throw new Error(`Failed to fetch messages: ${error}`); + } + } + + // Fetch Discord channels using Axios + async fetchChannels(): Promise> { + // If channels (with id and optional name) are already provided, skip the API call + if (this.options.channels && this.options.channels.length > 0) { + // Return the channel details using the provided channel objects + return this.options.channels.map( + (channel: { id: string; name?: string }) => ({ + id: channel.id, + name: channel.name ?? `Channel ${channel.id}`, // Fall back to "Channel {id}" if name is not provided + }), + ); + } + + // If no channels are provided, fetch them from the API using guildId + const api = this.getApi(); + + try { + const response = await api.get>( + `/guilds/${this.options.guildId}/channels`, + ); + + // Filter for text channels (type 0 represents text channels) + const filteredChannels = response.data.filter( + (channel) => channel.type === 0, + ); + + return filteredChannels; + } catch (error) { + console.error("Error fetching channels:", error); + throw new Error(`Failed to fetch channels: ${error}`); + } + } + + // Main function to get context items (messages) + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + // Ensure channels are fetched if only guildId is provided + const channels = await this.fetchChannels(); + + // Determine the channel ID from the selected channel (either from query or the first in the options) + let channelId: string; + const selectedChannel = channels.find( + (channel) => channel.id === query || channel.name === query, + ); + + channelId = selectedChannel ? selectedChannel.id : channels[0].id; // Use the first channel if no match is found + + // Prepare parts for rendering the message content + const parts = ["# Discord Channel Messages", `Channel ID: ${channelId}`]; + const messages = await this.fetchMessages(channelId); + + // Check if there are messages + if (messages.length > 0) { + parts.push("## Messages"); + + messages.forEach((message) => { + // Log each message and the username to confirm access + parts.push( + `### ${message.author?.username ?? "Unknown User"} on ${ + message.timestamp + }\n\n${message.content}`, + ); + }); + } else { + parts.push("No messages found."); + } + + const content = parts.join("\n\n"); + + return [ + { + name: `Messages from Channel ${channelId}`, + content, + description: "Latest messages from the channel", + }, + ]; + } + + // Submenu to load the list of channels + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const channels = await this.fetchChannels(); + + // Map over the channels and return them as submenu items + return channels.map((channel) => ({ + id: channel.id, + title: channel.name || `Channel ${channel.id}`, // Fallback to ID if name is missing + description: channel.topic ?? "", + })); + } +} + +export default DiscordContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 9c2ab4303..110ed066b 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider"; import TerminalContextProvider from "./TerminalContextProvider"; import URLContextProvider from "./URLContextProvider"; import RepoMapContextProvider from "./RepoMapContextProvider"; +import DiscordContextProvider from "./DiscordContextProvider"; /** * Note: We are currently omitting the following providers due to bugs: @@ -53,6 +54,7 @@ export const Providers: (typeof BaseContextProvider)[] = [ URLContextProvider, ContinueProxyContextProvider, RepoMapContextProvider, + DiscordContextProvider, ]; export function contextProviderClassFromName( diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 5a20c6daf..333edeb25 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1570,6 +1570,72 @@ } }, "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": ["discord"] + } + } + }, + "then": { + "allOf": [ + { + "properties": { + "params": { + "properties": { + "discordKey": { + "type": "string", + "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." + }, + "guildId": { + "type": "string", + "description": "The ID of the guild (server) from which to fetch channels and messages." + }, + "channels": { + "type": "array", + "description": "A list of channel objects to search for messages", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the channel" + }, + "name": { + "type": "string", + "description": "The name of the channel" + } + }, + "required": ["id"] + } + } + }, + "required": ["discordKey"] + } + } + }, + { + "oneOf": [ + { + "properties": { + "params": { + "required": ["guildId"] + } + } + }, + { + "properties": { + "params": { + "required": ["channels"] + } + } + } + ] + } + ] + } + }, { "if": { "properties": { @@ -2115,6 +2181,13 @@ "minimum": 128, "exclusiveMaximum": 2147483647 }, + "maxBatchSize": { + "title": "Maximum Batch Size", + "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", + "type": "integer", + "minimum": 1, + "exclusiveMaximum": 2147483647 + }, "region": { "title": "Region", "description": "The region where the model is hosted", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 176bbd295..333edeb25 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1570,6 +1570,72 @@ } }, "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": ["discord"] + } + } + }, + "then": { + "allOf": [ + { + "properties": { + "params": { + "properties": { + "discordKey": { + "type": "string", + "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." + }, + "guildId": { + "type": "string", + "description": "The ID of the guild (server) from which to fetch channels and messages." + }, + "channels": { + "type": "array", + "description": "A list of channel objects to search for messages", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the channel" + }, + "name": { + "type": "string", + "description": "The name of the channel" + } + }, + "required": ["id"] + } + } + }, + "required": ["discordKey"] + } + } + }, + { + "oneOf": [ + { + "properties": { + "params": { + "required": ["guildId"] + } + } + }, + { + "properties": { + "params": { + "required": ["channels"] + } + } + } + ] + } + ] + } + }, { "if": { "properties": { diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 7a7e54764..f7bff8284 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1741,6 +1741,82 @@ } }, "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": [ + "discord" + ] + } + } + }, + "then": { + "allOf": [ + { + "properties": { + "params": { + "properties": { + "discordKey": { + "type": "string", + "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." + }, + "guildId": { + "type": "string", + "description": "The ID of the guild (server) from which to fetch channels and messages." + }, + "channels": { + "type": "array", + "description": "A list of channel objects to search for messages", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the channel" + }, + "name": { + "type": "string", + "description": "The name of the channel" + } + }, + "required": [ + "id" + ] + } + } + }, + "required": [ + "discordKey" + ] + } + } + }, + { + "oneOf": [ + { + "properties": { + "params": { + "required": [ + "guildId" + ] + } + } + }, + { + "properties": { + "params": { + "required": [ + "channels" + ] + } + } + } + ] + } + ] + } + }, { "if": { "properties": { @@ -2356,6 +2432,13 @@ "minimum": 128, "exclusiveMaximum": 2147483647 }, + "maxBatchSize": { + "title": "Maximum Batch Size", + "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", + "type": "integer", + "minimum": 1, + "exclusiveMaximum": 2147483647 + }, "region": { "title": "Region", "description": "The region where the model is hosted", From 986f2d2204d95ada9cc04d936d5c08df6d989b8b Mon Sep 17 00:00:00 2001 From: Lester Hairston Date: Sun, 29 Sep 2024 22:27:33 -0500 Subject: [PATCH 03/25] docs update --- docs/docs/customize/context-providers.md | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index daed6d63b..d5212e562 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -315,6 +315,36 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC You can override this query by setting the `issueQuery` parameter. +### `@Discord` + +Reference the messages in a Discord channel. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "discord", + "params": { + "discordKey": "bot token", + "guildId": "1234567890", + "channels": [ + { + "id": "123456", + "name": "example-channel" + }, + { + "id": "678901", + "name": "example-channel-2" + } + ] + } + } + ] +} +``` + +Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels. + ### `@Postgres` Reference the schema of a table, and some sample rows From 550c4b4508b7b93db7c0d0b16e1aced73bd53859 Mon Sep 17 00:00:00 2001 From: Lester Hairston Date: Sun, 6 Oct 2024 23:45:58 -0500 Subject: [PATCH 04/25] Integrated fetch. Made clearer comments --- .../providers/DiscordContextProvider.ts | 117 +++++++----------- 1 file changed, 44 insertions(+), 73 deletions(-) diff --git a/core/context/providers/DiscordContextProvider.ts b/core/context/providers/DiscordContextProvider.ts index f1282070a..f341be6ab 100644 --- a/core/context/providers/DiscordContextProvider.ts +++ b/core/context/providers/DiscordContextProvider.ts @@ -4,18 +4,18 @@ import { ContextProviderExtras, ContextSubmenuItem, LoadSubmenuItemsArgs, + FetchFunction, } from "../../index.js"; import { BaseContextProvider } from "../index.js"; -import axios, { AxiosInstance } from "axios"; -// Define helper interfaces for Discord responses +//Define helper interfaces for Discord responses export interface DiscordChannel { id: string; - name?: string; // Optional field + name?: string; icon?: string; topic?: string; type?: number; - guild_id?: string; // The ID of the guild (server) that the channel belongs to + guild_id?: string; } interface DiscordMessage { @@ -29,7 +29,6 @@ interface DiscordMessage { } class DiscordContextProvider extends BaseContextProvider { - // Description for the context provider static description: ContextProviderDescription = { title: "discord", displayTitle: "Discord", @@ -39,96 +38,70 @@ class DiscordContextProvider extends BaseContextProvider { private baseUrl = "https://discord.com/api/v10"; - // Helper function to get the Axios instance with proper authorization - private getApi(): AxiosInstance { - const token = this.options.discordKey; - if (!token) { - throw new Error("Discord Bot Token is required!"); - } + // Helper function to get the full fetch URL + private getUrl(path: string): string { + return `${this.baseUrl}${path}`; + } - return axios.create({ - baseURL: this.baseUrl, + async fetchMessages( + channelId: string, + fetch: FetchFunction, + ): Promise> { + const url = this.getUrl(`/channels/${channelId}/messages`); + // Fetch messages from the specified channel using the provided fetch function + const response = await fetch(url, { headers: { - Authorization: `Bot ${token}`, + Authorization: `Bot ${this.options.discordKey}`, "Content-Type": "application/json", }, }); - } - // Fetch Discord messages from a specific channel using Axios - async fetchMessages(channelId: string): Promise> { - const api = this.getApi(); - - try { - const response = await api.get>( - `/channels/${channelId}/messages`, - ); - return response.data; - } catch (error) { - console.error("Error fetching messages:", error); - throw new Error(`Failed to fetch messages: ${error}`); - } - } - - // Fetch Discord channels using Axios - async fetchChannels(): Promise> { - // If channels (with id and optional name) are already provided, skip the API call - if (this.options.channels && this.options.channels.length > 0) { - // Return the channel details using the provided channel objects - return this.options.channels.map( - (channel: { id: string; name?: string }) => ({ - id: channel.id, - name: channel.name ?? `Channel ${channel.id}`, // Fall back to "Channel {id}" if name is not provided - }), - ); + if (!response.ok) { + throw new Error(`Failed to fetch messages: ${response.statusText}`); } - // If no channels are provided, fetch them from the API using guildId - const api = this.getApi(); - - try { - const response = await api.get>( - `/guilds/${this.options.guildId}/channels`, - ); - - // Filter for text channels (type 0 represents text channels) - const filteredChannels = response.data.filter( - (channel) => channel.type === 0, - ); - - return filteredChannels; - } catch (error) { - console.error("Error fetching channels:", error); - throw new Error(`Failed to fetch channels: ${error}`); - } + return response.json(); + } + + async fetchChannels(fetch: FetchFunction): Promise> { + const url = this.getUrl(`/guilds/${this.options.guildId}/channels`); + const response = await fetch(url, { + headers: { + Authorization: `Bot ${this.options.discordKey}`, + "Content-Type": "application/json", + }, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch channels: ${response.statusText}`); + } + + const channels = await response.json(); + // Filter channels to only include text channels (type 0) + return channels.filter((channel: DiscordChannel) => channel.type === 0); } - // Main function to get context items (messages) async getContextItems( query: string, extras: ContextProviderExtras, ): Promise { - // Ensure channels are fetched if only guildId is provided - const channels = await this.fetchChannels(); + const channels = await this.fetchChannels(extras.fetch); - // Determine the channel ID from the selected channel (either from query or the first in the options) let channelId: string; + // Find the channel by ID or name in the query string. If not found, use the first channel const selectedChannel = channels.find( (channel) => channel.id === query || channel.name === query, ); - channelId = selectedChannel ? selectedChannel.id : channels[0].id; // Use the first channel if no match is found + channelId = selectedChannel ? selectedChannel.id : channels[0].id; - // Prepare parts for rendering the message content const parts = ["# Discord Channel Messages", `Channel ID: ${channelId}`]; - const messages = await this.fetchMessages(channelId); + const messages = await this.fetchMessages(channelId, extras.fetch); - // Check if there are messages if (messages.length > 0) { parts.push("## Messages"); - + // Format each message into a markdown string messages.forEach((message) => { - // Log each message and the username to confirm access parts.push( `### ${message.author?.username ?? "Unknown User"} on ${ message.timestamp @@ -150,16 +123,14 @@ class DiscordContextProvider extends BaseContextProvider { ]; } - // Submenu to load the list of channels async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { - const channels = await this.fetchChannels(); + const channels = await this.fetchChannels(args.fetch); - // Map over the channels and return them as submenu items return channels.map((channel) => ({ id: channel.id, - title: channel.name || `Channel ${channel.id}`, // Fallback to ID if name is missing + title: channel.name || `Channel ${channel.id}`, description: channel.topic ?? "", })); } From ef88320ac5d13e8894a80e17dfebb257679d0c2e Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 8 Oct 2024 14:39:59 +0200 Subject: [PATCH 05/25] Fullscreen history sidebar --- .../history.tsx => components/History.tsx} | 306 +++++++----------- gui/src/pages/{gui.tsx => gui/Chat.tsx} | 44 ++- gui/src/pages/gui/index.tsx | 22 ++ gui/src/pages/history/HistoryHeader.tsx | 37 +++ gui/src/pages/history/index.tsx | 12 + gui/tailwind.config.cjs | 5 +- 6 files changed, 214 insertions(+), 212 deletions(-) rename gui/src/{pages/history.tsx => components/History.tsx} (51%) rename gui/src/pages/{gui.tsx => gui/Chat.tsx} (92%) create mode 100644 gui/src/pages/gui/index.tsx create mode 100644 gui/src/pages/history/HistoryHeader.tsx create mode 100644 gui/src/pages/history/index.tsx diff --git a/gui/src/pages/history.tsx b/gui/src/components/History.tsx similarity index 51% rename from gui/src/pages/history.tsx rename to gui/src/components/History.tsx index 2bfa45355..937064304 100644 --- a/gui/src/pages/history.tsx +++ b/gui/src/components/History.tsx @@ -1,8 +1,4 @@ -import { - ArrowLeftIcon, - PencilSquareIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; +import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionInfo } from "core"; import MiniSearch from "minisearch"; import React, { Fragment, useEffect, useState } from "react"; @@ -12,16 +8,12 @@ import styled from "styled-components"; import { defaultBorderRadius, Input, - lightGray, - vscBackground, vscBadgeBackground, vscForeground, vscInputBackground, -} from "../components"; -import ButtonWithTooltip from "../components/ButtonWithTooltip"; +} from "."; +import ButtonWithTooltip from "./ButtonWithTooltip"; import useHistory from "../hooks/useHistory"; -import { useNavigationListener } from "../hooks/useNavigationListener"; -import { getFontSize } from "../util"; const SearchBarContainer = styled.div` display: flex; @@ -71,7 +63,7 @@ const SectionHeader = styled.tr` user-select: none; padding: 4px; background-color: ${vscInputBackground}; - width: 100%; + width: calc(100% - 8px); font-weight: bold; text-align: center; align-items: center; @@ -81,15 +73,6 @@ const SectionHeader = styled.tr` height: 1.5em; `; -const TdDiv = styled.div` - cursor: pointer; - flex-grow: 1; - padding-left: 1rem; - padding-right: 1rem; - padding-top: 0.5rem; - padding-bottom: 0.5rem; -`; - function TableRow({ session, date, @@ -132,17 +115,18 @@ function TableRow({ onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} > -
- { - // Save current session - saveSession(); - await loadSession(session.sessionId); - navigate("/"); - }} - > -
- {editing ? ( +
{ + // Save current session + saveSession(); + await loadSession(session.sessionId); + navigate("/"); + }} + > +
+ {editing ? ( +
handleKeyUp(e)} onBlur={() => setEditing(false)} /> - ) : ( - JSON.stringify(session.title).slice(1, -1) - )} -
+
+ ) : ( + + {JSON.stringify(session.title).slice(1, -1)} + + )} -
- {lastPartOfPath(session.workspaceDirectory || "")} +
+ {lastPartOfPath(session.workspaceDirectory || "")} {!hovered && ( - + {date.toLocaleString("en-US", { year: "2-digit", month: "2-digit", @@ -172,31 +158,29 @@ function TableRow({ )}
- +
{hovered && ( - { - setEditing(true); - }} - > - - - )} - - {hovered && ( - { - deleteSession(session.sessionId); - onDelete(session.sessionId); - }} - > - - +
+ { + e.stopPropagation(); + setEditing(true); + }} + > + + + { + deleteSession(session.sessionId); + onDelete(session.sessionId); + }} + > + + +
)}
@@ -208,10 +192,7 @@ function lastPartOfPath(path: string): string { return path.split(sep).pop() || path; } -function History() { - useNavigationListener(); - const navigate = useNavigate(); - +export function History() { const [sessions, setSessions] = useState([]); const [filteredAndSortedSessions, setFilteredAndSortedSessions] = useState< SessionInfo[] @@ -227,9 +208,6 @@ function History() { const searchInputRef = React.useRef(null); - const stickyHistoryHeaderRef = React.useRef(null); - const [headerHeight, setHeaderHeight] = useState(0); - const dispatch = useDispatch(); const { getHistory } = useHistory(dispatch); @@ -297,138 +275,90 @@ function History() { ); }, [sessions, searchTerm, minisearch]); - useEffect(() => { - setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100); - }, [stickyHistoryHeaderRef.current]); - const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24); const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7); const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); const earlier = new Date(0); return ( -
-
-
+ + setSearchTerm(e.target.value)} + /> + { + if (searchInputRef.current.value === "") { + searchInputRef.current.value = "*"; + setSearchTerm("*"); + } else { + searchInputRef.current.value = ""; + setSearchTerm(""); + } }} > - navigate("/")} - className="inline-block ml-4 cursor-pointer" - /> -

History

+ {searchTerm === "" ? "Show All" : "Clear"} +
+
+ + {filteredAndSortedSessions.length === 0 && ( +
+ No past sessions found. To start a new session, either click the "+" + button or use the keyboard shortcut: Option + Command + N
- {/* {workspacePaths && workspacePaths.length > 0 && ( - setFilteringByWorkspace((prev) => !prev)} - title={`Show only sessions from ${lastPartOfPath( - workspacePaths[workspacePaths.length - 1] - )}/`} - /> - )} */} -
+ )} -
- - setSearchTerm(e.target.value)} - /> - { - if (searchInputRef.current.value === "") { - searchInputRef.current.value = "*"; - setSearchTerm("*"); - } else { - searchInputRef.current.value = ""; - setSearchTerm(""); - } - }} - > - {searchTerm === "" ? "Show All" : "Clear"} - - - - {filteredAndSortedSessions.length === 0 && ( -
- No past sessions found. To start a new session, either click the "+" - button or use the keyboard shortcut: Option + Command + N -
- )} - - - - {filteredAndSortedSessions.map((session, index) => { - const prevDate = - index > 0 - ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) - : earlier; - const date = parseDate(session.dateCreated); - return ( - - {index === 0 && date > yesterday && ( - - Today - - )} - {date < yesterday && - date > lastWeek && - prevDate > yesterday && ( - - This Week - - )} - {date < lastWeek && - date > lastMonth && - prevDate > lastWeek && ( - - This Month - - )} - {date < lastMonth && prevDate > lastMonth && ( - - Older - +
+ + {filteredAndSortedSessions.map((session, index) => { + const prevDate = + index > 0 + ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) + : earlier; + const date = parseDate(session.dateCreated); + return ( + + {index === 0 && date > yesterday && ( + Today + )} + {date < yesterday && + date > lastWeek && + prevDate > yesterday && ( + This Week )} + {date < lastWeek && date > lastMonth && prevDate > lastWeek && ( + This Month + )} + {date < lastMonth && prevDate > lastMonth && ( + Older + )} - - deleteSessionInUI(session.sessionId)} - > - - - ); - })} - -
-
- - All session data is saved in ~/.continue/sessions - -
+ + deleteSessionInUI(session.sessionId)} + > + + + ); + })} + + +
+ + All session data is saved in ~/.continue/sessions +
); } - -export default History; diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui/Chat.tsx similarity index 92% rename from gui/src/pages/gui.tsx rename to gui/src/pages/gui/Chat.tsx index 156c0b3b2..243657462 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -24,43 +24,43 @@ import { lightGray, vscBackground, vscForeground, -} from "../components"; -import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; -import StepContainer from "../components/gui/StepContainer"; -import TimelineItem from "../components/gui/TimelineItem"; -import ContinueInputBox from "../components/mainInput/ContinueInputBox"; -import { defaultInputModifiers } from "../components/mainInput/inputModifiers"; -import { TutorialCard } from "../components/mainInput/TutorialCard"; +} from "../../components"; +import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; +import StepContainer from "../../components/gui/StepContainer"; +import TimelineItem from "../../components/gui/TimelineItem"; +import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; +import { defaultInputModifiers } from "../../components/mainInput/inputModifiers"; +import { TutorialCard } from "../../components/mainInput/TutorialCard"; import { OnboardingCard, useOnboardingCard, -} from "../components/OnboardingCard"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import useChatHandler from "../hooks/useChatHandler"; -import useHistory from "../hooks/useHistory"; -import { useTutorialCard } from "../hooks/useTutorialCard"; -import { useWebviewListener } from "../hooks/useWebviewListener"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +} from "../../components/OnboardingCard"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import useChatHandler from "../../hooks/useChatHandler"; +import useHistory from "../../hooks/useHistory"; +import { useTutorialCard } from "../../hooks/useTutorialCard"; +import { useWebviewListener } from "../../hooks/useWebviewListener"; +import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { clearLastResponse, deleteMessage, newSession, setInactive, -} from "../redux/slices/stateSlice"; +} from "../../redux/slices/stateSlice"; import { setDialogEntryOn, setDialogMessage, setShowDialog, -} from "../redux/slices/uiStateSlice"; -import { RootState } from "../redux/store"; +} from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; import { getFontSize, getMetaKeyLabel, isJetBrains, isMetaEquivalentKeyPressed, -} from "../util"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +} from "../../util"; +import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; +import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; const TopGuiDiv = styled.div<{ showScrollbar?: boolean; @@ -144,7 +144,7 @@ function fallbackRender({ error, resetErrorBoundary }: any) { ); } -function GUI() { +export function Chat() { const posthog = usePostHog(); const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); @@ -528,5 +528,3 @@ function GUI() { ); } - -export default GUI; diff --git a/gui/src/pages/gui/index.tsx b/gui/src/pages/gui/index.tsx new file mode 100644 index 000000000..53e184027 --- /dev/null +++ b/gui/src/pages/gui/index.tsx @@ -0,0 +1,22 @@ +import { Chat } from "./Chat"; +import { History } from "../../components/History"; +import styled from "styled-components"; +import { vscSidebarBorder } from "../../components"; + +export const Aside = styled.aside` + border-right: 1px solid ${vscSidebarBorder}; +`; + +export default function GUI() { + return ( +
+ + +
+ +
+
+ ); +} diff --git a/gui/src/pages/history/HistoryHeader.tsx b/gui/src/pages/history/HistoryHeader.tsx new file mode 100644 index 000000000..4a8d4688c --- /dev/null +++ b/gui/src/pages/history/HistoryHeader.tsx @@ -0,0 +1,37 @@ +import { useNavigate } from "react-router-dom"; +import { lightGray, vscBackground } from "../../components"; +import { useNavigationListener } from "../../hooks/useNavigationListener"; +import { ArrowLeftIcon } from "@heroicons/react/24/outline"; + +export const HistoryHeader = () => { + useNavigationListener(); + const navigate = useNavigate(); + + return ( +
+
+ navigate("/")} + className="inline-block ml-4 cursor-pointer" + /> +

History

+
+ {/* {workspacePaths && workspacePaths.length > 0 && ( + setFilteringByWorkspace((prev) => !prev)} + title={`Show only sessions from ${lastPartOfPath( + workspacePaths[workspacePaths.length - 1] + )}/`} + /> + )} */} +
+ ); +}; diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx new file mode 100644 index 000000000..6d31c60bc --- /dev/null +++ b/gui/src/pages/history/index.tsx @@ -0,0 +1,12 @@ +import { History } from "../../components/History"; +import { getFontSize } from "../../util"; +import { HistoryHeader } from "./HistoryHeader"; + +export default function HistoryPage() { + return ( +
+ + +
+ ); +} diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index a20bdecf7..63e0c2810 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -10,12 +10,15 @@ module.exports = { theme: { // Note that these breakpoints are primarily optimized for the input toolbar screens: { - xxs: "170px", // Smallest width for Primary Sidebar in VS Code + "2xs": "170px", // Smallest width for Primary Sidebar in VS Code xs: "250px", // Avg default sidebar width in VS Code sm: "330px", md: "460px", lg: "590px", xl: "720px", + "2xl": "860px", + "3xl": "1000px", + "4xl": "1140px", }, extend: { animation: { From cacabc89a5d169e0db816c15288fbab4ba7d6321 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 8 Oct 2024 17:42:38 +0200 Subject: [PATCH 06/25] Refresh history on last session change --- gui/src/components/History.tsx | 4 +- gui/src/components/Layout.tsx | 66 ++++++++++++++------------ gui/src/context/LastSessionContext.tsx | 30 ++++++++++++ gui/src/hooks/useHistory.tsx | 14 ++++-- 4 files changed, 78 insertions(+), 36 deletions(-) create mode 100644 gui/src/context/LastSessionContext.tsx diff --git a/gui/src/components/History.tsx b/gui/src/components/History.tsx index 937064304..6112251fc 100644 --- a/gui/src/components/History.tsx +++ b/gui/src/components/History.tsx @@ -209,7 +209,7 @@ export function History() { const searchInputRef = React.useRef(null); const dispatch = useDispatch(); - const { getHistory } = useHistory(dispatch); + const { getHistory, lastSessionId } = useHistory(dispatch); const [minisearch, setMinisearch] = useState< MiniSearch<{ title: string; sessionId: string }> @@ -234,7 +234,7 @@ export function History() { ); }; fetchSessions(); - }, []); + }, [lastSessionId]); useEffect(() => { // When searchTerm is empty only show sessions from the current workspace diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 259de2e25..0714d32b4 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -13,6 +13,7 @@ import Footer from "./Footer"; import { updateApplyState, setShowDialog } from "../redux/slices/uiStateSlice"; import TextDialog from "./dialogs"; import { useOnboardingCard, isNewUserOnboarding } from "./OnboardingCard"; +import { LastSessionProvider } from "../context/LastSessionContext"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -174,39 +175,42 @@ const Layout = () => { }, [location]); return ( - -
- { - dispatch(setShowDialog(false)); + + +
{ - dispatch(setShowDialog(false)); - }} - message={dialogMessage} - /> + > + { + dispatch(setShowDialog(false)); + }} + onClose={() => { + dispatch(setShowDialog(false)); + }} + message={dialogMessage} + /> - - - - - -
- -
-
- + + + + + + +
+ +
+
+ + ); }; diff --git a/gui/src/context/LastSessionContext.tsx b/gui/src/context/LastSessionContext.tsx new file mode 100644 index 000000000..f931d9212 --- /dev/null +++ b/gui/src/context/LastSessionContext.tsx @@ -0,0 +1,30 @@ +import React, { createContext, useState, useEffect } from "react"; + +export const LastSessionContext = createContext<{ + lastSessionId: string | undefined; + setLastSessionId: (id: string | undefined) => void; +}>({ + lastSessionId: undefined, + setLastSessionId: () => {}, +}); + +export const LastSessionProvider: React.FC<{ + children: React.ReactNode; +}> = ({ children }) => { + const [lastSessionId, setLastSessionId] = useState(); + + useEffect(() => { + const storedId = localStorage.getItem("lastSessionId"); + if (storedId) { + setLastSessionId(storedId); + } + }, []); + + return ( + + {children} + + ); +}; + +export const useLastSessionContext = () => React.useContext(LastSessionContext); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 8e5fe22a2..2e00b3707 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -3,13 +3,14 @@ import { PersistedSessionInfo, SessionInfo } from "core"; import { llmCanGenerateInParallel } from "core/llm/autodetect"; import { stripImages } from "core/llm/images"; -import { useContext } from "react"; +import { useCallback, useContext, useEffect } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { useLastSessionContext } from "../context/LastSessionContext"; function truncateText(text: string, maxLength: number) { if (text.length > maxLength) { @@ -25,6 +26,12 @@ function useHistory(dispatch: Dispatch) { (store: RootState) => store.state.config.disableSessionTitles, ); const ideMessenger = useContext(IdeMessengerContext); + const { lastSessionId, setLastSessionId } = useLastSessionContext(); + + const updateLastSessionId = useCallback((sessionId: string) => { + setLastSessionId(sessionId); + setLocalStorage("lastSessionId", sessionId); + }, []); async function getHistory( offset?: number, @@ -85,7 +92,7 @@ function useHistory(dispatch: Dispatch) { sessionId: stateCopy.sessionId, workspaceDirectory: window.workspacePaths?.[0] || "", }; - setLocalStorage("lastSessionId", stateCopy.sessionId); + updateLastSessionId(stateCopy.sessionId); return await ideMessenger.request("history/save", sessionInfo); } @@ -106,7 +113,7 @@ function useHistory(dispatch: Dispatch) { } async function loadSession(id: string): Promise { - setLocalStorage("lastSessionId", state.sessionId); + updateLastSessionId(state.sessionId); const result = await ideMessenger.request("history/load", { id }); if (result.status === "error") { throw new Error(result.error); @@ -136,6 +143,7 @@ function useHistory(dispatch: Dispatch) { getLastSessionId, updateSession, getSession, + lastSessionId, }; } From cd693fb653a964e0892200ab8133dd7929498ed6 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 8 Oct 2024 17:46:04 +0200 Subject: [PATCH 07/25] Restore font sizes --- gui/src/components/History.tsx | 3 ++- gui/src/pages/history/HistoryHeader.tsx | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/gui/src/components/History.tsx b/gui/src/components/History.tsx index 6112251fc..b930d304e 100644 --- a/gui/src/components/History.tsx +++ b/gui/src/components/History.tsx @@ -14,6 +14,7 @@ import { } from "."; import ButtonWithTooltip from "./ButtonWithTooltip"; import useHistory from "../hooks/useHistory"; +import { getFontSize } from "../util"; const SearchBarContainer = styled.div` display: flex; @@ -281,7 +282,7 @@ export function History() { const earlier = new Date(0); return ( -
+
{ useNavigationListener(); const navigate = useNavigate(); return ( -
+
Date: Tue, 8 Oct 2024 18:38:45 +0200 Subject: [PATCH 08/25] Remove unnecessary code --- gui/src/context/LastSessionContext.tsx | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/gui/src/context/LastSessionContext.tsx b/gui/src/context/LastSessionContext.tsx index f931d9212..d3b555dc6 100644 --- a/gui/src/context/LastSessionContext.tsx +++ b/gui/src/context/LastSessionContext.tsx @@ -1,4 +1,4 @@ -import React, { createContext, useState, useEffect } from "react"; +import React, { createContext, useState } from "react"; export const LastSessionContext = createContext<{ lastSessionId: string | undefined; @@ -13,13 +13,6 @@ export const LastSessionProvider: React.FC<{ }> = ({ children }) => { const [lastSessionId, setLastSessionId] = useState(); - useEffect(() => { - const storedId = localStorage.getItem("lastSessionId"); - if (storedId) { - setLastSessionId(storedId); - } - }, []); - return ( {children} From 26e536847ce571e0b3e16bdd33d72cc5c2ddefab Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 8 Oct 2024 15:54:59 -0700 Subject: [PATCH 09/25] update keybindings for accept/reject diff --- .../ContinuePluginStartupActivity.kt | 19 +--------- .../editor/DiffStreamHandler.kt | 3 +- .../editor/DiffStreamManager.java | 4 +++ .../editor/InlineEditAction.kt | 9 +++-- .../continueintellijextension/utils/Utils.kt | 4 +-- .../src/main/resources/META-INF/plugin.xml | 35 +++++++++++++------ .../vscode/src/diff/vertical/handler.ts | 12 +++---- .../vscode/src/diff/vertical/manager.ts | 1 - 8 files changed, 41 insertions(+), 46 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamManager.java diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 4b0747ee7..f3a8f7d2e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -56,25 +56,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.IO) override fun runActivity(project: Project) { - removeShortcutFromAction(getPlatformSpecificKeyStroke("J")) removeShortcutFromAction(getPlatformSpecificKeyStroke("shift J")) - -// project.messageBus.connect().subscribe( -// ToolWindowManagerListener.TOPIC, -// object : ToolWindowManagerListener { -// override fun stateChanged(toolWindowManager: ToolWindowManager) { -// if (toolWindowManager.activeToolWindowId == TerminalToolWindowFactory.TOOL_WINDOW_ID -// || TerminalView.getInstance(project).isNotAvailable() -// ) { -// project.service().update( -// TerminalView.getInstance(project).widgets -// ) -// } -// } -// } -// ) - initializePlugin(project) } @@ -112,7 +95,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { project, ContinuePluginService::class.java ) - + val defaultStrategy = DefaultTextSelectionStrategy() coroutineScope.launch { 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 aa43e88bf..f26a80f5f 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 @@ -9,7 +9,6 @@ import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.colors.TextAttributesKey -import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.TextAttributes @@ -54,7 +53,7 @@ class DiffStreamHandler( key.let { editor.colorsScheme.setAttributes(it, attributes) } key } - + private val unfinishedKey = run { val attributes = TextAttributes().apply { backgroundColor = JBColor(0x20888888.toInt(), 0x20888888.toInt()) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamManager.java b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamManager.java new file mode 100644 index 000000000..6a3bbaf77 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamManager.java @@ -0,0 +1,4 @@ +package com.github.continuedev.continueintellijextension.editor; + +public class DiffStreamManager { +} 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 6b05c6fb2..8645bf88a 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 @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.`continue`.GetTheme import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel +import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction @@ -130,7 +131,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { Thread.sleep(20) } - + // Get highlighted range val selectionModel = editor.selectionModel val startLineNumber = editor.document.getLineNumber(selectionModel.selectionStart) @@ -416,16 +417,14 @@ class CustomPanel( border = EmptyBorder(0, 4, 0, 0) } - val leftButton = CustomButton("Reject (${getAltKeyLabel()}⇧N)") { onReject() }.apply { + val leftButton = CustomButton("Reject All (${getMetaKeyLabel()}⇧⌫)") { onReject() }.apply { background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) - } - val rightButton = CustomButton("Accept (${getAltKeyLabel()}⇧Y)") { onAccept() }.apply { + val rightButton = CustomButton("Accept All (${getMetaKeyLabel()}⇧⏎)") { onAccept() }.apply { background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) - } val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt index a743e8b50..21cc17089 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt @@ -18,8 +18,8 @@ fun getOs(): Os { fun getMetaKeyLabel(): String { return when (getOs()) { Os.MAC -> "⌘" - Os.WINDOWS -> "Ctrl" - Os.LINUX -> "Ctrl" + Os.WINDOWS -> "^" + Os.LINUX -> "^" } } diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 2e8130e5e..3633201f8 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -48,7 +48,6 @@ + first-keystroke="shift ctrl ENTER"/> + first-keystroke="shift meta ENTER"/> + + + + + + + + + + + + - + @@ -93,7 +109,7 @@ @@ -102,7 +118,7 @@ @@ -110,7 +126,6 @@ diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 5aa5b070b..a1efbd1df 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -386,18 +386,14 @@ export class VerticalDiffHandler implements vscode.Disposable { } } - if (numRed > 0) { - const rangeToDelete = - this.redDecorationManager.deleteRangeStartingAt(startLine); - - if (accept) { - // Delete the actual lines - await this.deleteLinesAt(startLine, numRed); - } + if (numRed > 0 && accept) { + // Delete the actual lines + await this.deleteLinesAt(startLine, numRed); } // Shift everything below upward const offset = -(accept ? numRed : numGreen); + this.redDecorationManager.shiftDownAfterLine(startLine, offset); this.greenDecorationManager.shiftDownAfterLine(startLine, offset); diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 2ecf6d596..985a6ba29 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,7 +1,6 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; - import { DiffLine } from "core"; import { streamDiffLines } from "core/edit/streamDiffLines"; import * as vscode from "vscode"; From 640f2b48a29df47e956fb9a26094e03155288638 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 9 Oct 2024 13:16:03 +0200 Subject: [PATCH 10/25] Toggle full screen mode --- core/protocol/ideWebview.ts | 2 +- extensions/vscode/package.json | 16 +++++++++++----- extensions/vscode/src/commands.ts | 31 ++++++++++++++++++++++++++++--- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 523ba4995..1f0d0e85e 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -22,7 +22,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { toggleDevTools: [undefined, void]; reloadWindow: [undefined, void]; focusEditor: [undefined, void]; - toggleFullScreen: [undefined, void]; + toggleFullScreen: [undefined, void, { newWindow?: boolean } | undefined]; insertAtCursor: [{ text: string }, void]; copyText: [{ text: string }, void]; "jetbrains/editorInsetHeight": [{ height: number }, void]; diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 6473fd504..ffa27b831 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -189,6 +189,12 @@ "icon": "$(fullscreen)", "group": "Continue" }, + { + "command": "continue.toggleNewWindow", + "category": "Continue", + "title": "Open New Window", + "icon": "$(link-external)" + }, { "command": "continue.openConfigJson", "category": "Continue", @@ -452,6 +458,11 @@ "command": "continue.toggleFullScreen", "group": "navigation@3", "when": "view == continue.continueGUIView" + }, + { + "command": "continue.toggleNewWindow", + "group": "navigation@4", + "when": "view == continue.continueGUIView" } ], "editor/title": [ @@ -464,11 +475,6 @@ "command": "continue.viewHistory", "group": "navigation@2", "when": "activeWebviewPanelId == continue.continueGUIView" - }, - { - "command": "continue.toggleFullScreen", - "group": "navigation@3", - "when": "activeWebviewPanelId == continue.continueGUIView" } ], "terminal/context": [ diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index b49e9a184..961e1c25d 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -483,7 +483,11 @@ const commandsMap: ( "continue.applyCodeFromChat": () => { sidebar.webviewProtocol.request("applyCodeFromChat", undefined); }, - "continue.toggleFullScreen": () => { + "continue.toggleFullScreen": ({ + newWindow, + }: { newWindow?: boolean } = {}) => { + focusGUI(); + // Check if full screen is already open by checking open tabs const fullScreenTab = getFullScreenTab(); @@ -532,6 +536,18 @@ const commandsMap: ( null, extensionContext.subscriptions, ); + + if (newWindow) { + vscode.commands.executeCommand( + "workbench.action.copyEditorToNewWindow", + ); + } + }, + "continue.toggleNewWindow": () => { + focusGUI(); + vscode.commands.executeCommand("continue.toggleFullScreen", { + newWindow: true, + }); }, "continue.openConfigJson": () => { ide.openFile(getConfigJsonPath()); @@ -654,6 +670,9 @@ const commandsMap: ( { label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", }, + { + label: "$(link-external) Open chat in a new window", + }, { label: quickPickStatusText(targetStatus), }, @@ -705,9 +724,15 @@ const commandsMap: ( "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" ) { vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if ( + selectedOption === "$(link-external) Open chat in a new window" + ) { + vscode.commands.executeCommand("continue.toggleNewWindow"); } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); + vscode.commands.executeCommand("continue.toggleFullScreen"); + vscode.commands.executeCommand("continue.toggleNewWindow"); + // focusGUI(); + // vscode.commands.executeCommand("continue.navigateTo", "/more"); } quickPick.dispose(); }); From 1786bfb4aed8bcce42fffdbdda837929a86d00c8 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 9 Oct 2024 14:54:43 +0200 Subject: [PATCH 11/25] Restore help center shortcut --- extensions/vscode/src/commands.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 961e1c25d..36245b6ab 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -729,10 +729,8 @@ const commandsMap: ( ) { vscode.commands.executeCommand("continue.toggleNewWindow"); } else if (selectedOption === "$(question) Open help center") { - vscode.commands.executeCommand("continue.toggleFullScreen"); - vscode.commands.executeCommand("continue.toggleNewWindow"); - // focusGUI(); - // vscode.commands.executeCommand("continue.navigateTo", "/more"); + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); } quickPick.dispose(); }); From af509ef1ae2e0265c3ea1f73c72c4aa20973bd3b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 9 Oct 2024 15:00:10 +0200 Subject: [PATCH 12/25] Widen 4xl breakpoint --- gui/tailwind.config.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index 63e0c2810..49d569e78 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -18,7 +18,7 @@ module.exports = { xl: "720px", "2xl": "860px", "3xl": "1000px", - "4xl": "1140px", + "4xl": "1180px", }, extend: { animation: { From b6b39dbf0abfca128cb0a7199a153cb78c710c77 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 9 Oct 2024 14:22:17 -0700 Subject: [PATCH 13/25] update diff accept/reject logi --- .../editor/DiffStreamHandler.kt | 149 ++- .../editor/DiffStreamService.kt | 6 +- .../editor/EditorComponentInlaysManager.kt | 2 - .../editor/VerticalDiffActionButtons.kt | 95 ++ .../vscode/src/diff/vertical/handler.ts | 7 +- gui/src/components/mainInput/InputToolbar.tsx | 2 +- gui/src/pages/gui.tsx | 940 +++++++++--------- 7 files changed, 707 insertions(+), 494 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt 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 f26a80f5f..15ff0689d 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 @@ -26,6 +26,13 @@ enum class DiffLineType { SAME, NEW, OLD } +data class VerticalDiffBlock( + val start: Int, + val numRed: Int, + val numGreen: Int, + val buttons: VerticalDiffActionButtons +) + class DiffStreamHandler( private val project: Project, private val editor: Editor, @@ -70,11 +77,13 @@ class DiffStreamHandler( private var currentLineHighlighter: RangeHighlighter? = null private val unfinishedHighlighters: MutableList = mutableListOf() private var changeCount: Int = 0 // Kept track of so we can count steps to undo when cancelling + private var insertedInCurrentBlock: Int = 0; private var running: Boolean = false - private var deletionBufferStartLine: Int = -1 private val deletionsBuffer: MutableList = mutableListOf() private val deletionInlays: MutableList = mutableListOf() + private val verticalDiffBlocks: MutableList = mutableListOf() + private fun removeDeletionInlays() { deletionInlays.forEach { @@ -102,8 +111,45 @@ class DiffStreamHandler( } private fun insertDeletionBuffer() { + if (deletionsBuffer.isNotEmpty() || insertedInCurrentBlock > 0) { + val start = currentLine - insertedInCurrentBlock + val numGreen = insertedInCurrentBlock + val numRed = deletionsBuffer.size + val buttons = VerticalDiffActionButtons( + editor, + start, + onClickAccept = { + acceptRejectBlock(true, start, numGreen, numRed) + }, + onClickReject = { + acceptRejectBlock(false, start, numGreen, numRed) + } + ) + + verticalDiffBlocks.add( + VerticalDiffBlock( + start = start, + numRed = deletionsBuffer.size, + numGreen = insertedInCurrentBlock, + buttons = buttons + ) + ) + + editor.contentComponent.add(buttons.acceptButton) + editor.contentComponent.add(buttons.rejectButton) + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + + if (deletionsBuffer.isEmpty()) { + insertedInCurrentBlock = 0; + return; + } + + // TODO: Handle decoration updates according to insertedInCurrentBlock + // Insert red highlighted code between the real lines in the editor - if (deletionBufferStartLine != -1 && deletionsBuffer.isNotEmpty()) { + if (deletionBufferStartLine != -1) { val component = JTextArea().apply { text = deletionsBuffer.joinToString("\n") isEditable = false @@ -125,6 +171,8 @@ class DiffStreamHandler( deletionsBuffer.clear() deletionBufferStartLine = -1 } + + insertedInCurrentBlock = 0; } private fun handleDiffLine(type: DiffLineType, line: String) { @@ -137,28 +185,25 @@ class DiffStreamHandler( } DiffLineType.NEW -> { - // Insert new line if (currentLine == editor.document.lineCount) { editor.document.insertString(editor.document.textLength, "\n") } + val offset = editor.document.getLineStartOffset(currentLine) editor.document.insertString(offset, line + "\n") - - // Highlight the new line green editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST) insertDeletionBuffer() currentLine++ changeCount++ + insertedInCurrentBlock++; } DiffLineType.OLD -> { - // Remove old line deleteLineAt(currentLine) - - // Add to deletions buffer deletionsBuffer.add(line) + if (deletionBufferStartLine == -1) { deletionBufferStartLine = currentLine } @@ -171,6 +216,7 @@ class DiffStreamHandler( if (currentLineHighlighter != null) { editor.markupModel.removeHighlighter(currentLineHighlighter!!) } + currentLineHighlighter = editor.markupModel.addLineHighlighter( currentLineKey, min(currentLine, editor.document.lineCount - 1), @@ -188,6 +234,64 @@ class DiffStreamHandler( } } + private fun acceptRejectBlock( + accept: Boolean, + startLine: Int, + numGreen: Int, + numRed: Int + ) { + // TODO: We use virtual lines for red so we should shouldnt be doing numRed addition + if (numGreen > 0) { + val highlightersToRemove = editor.markupModel.allHighlighters.filter { highlighter -> + val highlighterLine = editor.document.getLineNumber(highlighter.startOffset) + highlighterLine in startLine until (startLine + numRed) + } + + if (highlightersToRemove.isNotEmpty()) { + editor.markupModel.removeHighlighter(highlightersToRemove.first()) + } + + if (!accept) { + // Delete the actual lines + WriteCommandAction.runWriteCommandAction(project) { + for (i in 0 until numGreen) { + deleteLineAt(startLine + numRed) + } + } + } + } + + if (numRed > 0 && accept) { + // Delete the actual lines + WriteCommandAction.runWriteCommandAction(project) { + for (i in 0 until numRed) { + deleteLineAt(startLine) + } + } + } + + // Shift everything below upward + val offset = -(if (accept) numRed else numGreen) + + // Update the positions of the vertical diff blocks + verticalDiffBlocks.forEach { block -> + if (block.start > startLine) { + block.buttons.updatePosition(block.start + offset) + } + } + + // Remove the processed block + verticalDiffBlocks.removeAll { it.start == startLine } + + if (verticalDiffBlocks.isEmpty()) { + onClose() + } + + // Refresh the editor + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + private fun resetState() { // Remove all highlighters editor.markupModel.removeAllHighlighters() @@ -212,29 +316,36 @@ class DiffStreamHandler( } } - fun accept() { + private fun removeDiffBlock(block: VerticalDiffBlock) { + editor.contentComponent.remove(block.buttons.acceptButton) + editor.contentComponent.remove(block.buttons.rejectButton) + + verticalDiffBlocks.remove(block) + + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + + private fun removeAllDiffBlocks() { + verticalDiffBlocks.forEach(::removeDiffBlock) + } + + fun acceptAll() { // Accept the changes editor.markupModel.removeAllHighlighters() removeDeletionInlays() onClose() running = false + removeAllDiffBlocks() } - fun reject() { + fun rejectAll() { // Reject the changes resetState() removeDeletionInlays() onClose() running = false - } - - fun toggleFocus() { - if (textArea.hasFocus()) { - textArea.transferFocus() - editor.contentComponent.requestFocus() - } else { - textArea.requestFocus() - } + removeAllDiffBlocks() } fun run(input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt index 48aba76b8..222e6a71c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt @@ -9,19 +9,19 @@ class DiffStreamService { fun register(handler: DiffStreamHandler, editor: Editor) { if (handlers.containsKey(editor)) { - handlers[editor]?.reject() + handlers[editor]?.rejectAll() } handlers[editor] = handler println("Registered handler for editor") } fun reject(editor: Editor) { - handlers[editor]?.reject() + handlers[editor]?.rejectAll() handlers.remove(editor) } fun accept(editor: Editor) { - handlers[editor]?.accept() + handlers[editor]?.acceptAll() handlers.remove(editor) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt index 20d31a519..e8f24f972 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt @@ -14,10 +14,8 @@ import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import java.awt.Dimension import java.awt.Font -import java.awt.Insets import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent -import javax.swing.BorderFactory import javax.swing.JComponent import javax.swing.ScrollPaneConstants import kotlin.math.ceil diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt new file mode 100644 index 000000000..101799549 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt @@ -0,0 +1,95 @@ +package com.github.continuedev.continueintellijextension.editor + +import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.ui.JBColor +import java.awt.* +import javax.swing.JButton + +class VerticalDiffActionButtons( + private val editor: Editor, + private var lineNumber: Int, + private val onClickAccept: () -> Unit, + private val onClickReject: () -> Unit +) { + val acceptButton: JButton + val rejectButton: JButton + + private fun removeButtons() { + editor.contentComponent.remove(acceptButton) + editor.contentComponent.remove(rejectButton) + } + + init { + acceptButton = createButton("${getAltKeyLabel()}⇧Y", JBColor(0x9900FF00.toInt(), 0x9900FF00.toInt())) + rejectButton = createButton("${getAltKeyLabel()}⇧N", JBColor(0x99FF0000.toInt(), 0x99FF0000.toInt())) + + acceptButton.addActionListener { + removeButtons() + onClickAccept() + } + + rejectButton.addActionListener { + removeButtons() + onClickReject() + } + + // Position the buttons + val visibleArea = editor.scrollingModel.visibleArea + val lineStartPosition = editor.logicalPositionToXY(LogicalPosition(lineNumber, 0)) + val xPosition = + visibleArea.x + visibleArea.width - acceptButton.preferredSize.width - rejectButton.preferredSize.width - 20 + val yPosition = lineStartPosition.y + + acceptButton.setBounds( + xPosition, + yPosition, + acceptButton.preferredSize.width, + acceptButton.preferredSize.height + ) + rejectButton.setBounds( + xPosition + acceptButton.preferredSize.width + 5, + yPosition, + rejectButton.preferredSize.width, + rejectButton.preferredSize.height + ) + } + + private fun createButton(text: String, backgroundColor: JBColor): JButton { + return object : JButton(text) { + override fun paintComponent(g: Graphics) { + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g2.color = backgroundColor + g2.fillRoundRect(0, 0, width - 1, height - 1, 8, 8) + super.paintComponent(g2) + g2.dispose() + } + }.apply { + // This isn't working currently, font color is transparent + foreground = JBColor.WHITE + font = Font("Arial", Font.BOLD, 9) + isContentAreaFilled = false + isOpaque = false + border = null + preferredSize = Dimension(preferredSize.width, 16) + cursor = Cursor(Cursor.HAND_CURSOR) + } + } + + fun updatePosition(newLineNumber: Int) { + this.lineNumber = newLineNumber + val visibleArea = editor.scrollingModel.visibleArea + val lineStartPosition = editor.logicalPositionToXY(LogicalPosition(lineNumber, 0)) + val xPosition = + visibleArea.x + visibleArea.width - acceptButton.width - rejectButton.width - 40 + val yPosition = lineStartPosition.y + + acceptButton.location = Point(xPosition, yPosition) + rejectButton.location = Point(xPosition + acceptButton.width + 5, yPosition) + + // Refresh the editor to reflect the changes + editor.component.repaint() + } +} diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index a1efbd1df..37cb1badf 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -90,6 +90,7 @@ export class VerticalDiffHandler implements vscode.Disposable { private async insertDeletionBuffer() { // Don't remove trailing whitespace line const totalDeletedContent = this.deletionBuffer.join("\n"); + if ( totalDeletedContent === "" && this.currentLineIndex >= this.endLine + this.newLinesAdded && @@ -100,11 +101,13 @@ export class VerticalDiffHandler implements vscode.Disposable { if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || []; + blocks.push({ start: this.currentLineIndex - this.insertedInCurrentBlock, numRed: this.deletionBuffer.length, numGreen: this.insertedInCurrentBlock, }); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } @@ -118,10 +121,12 @@ export class VerticalDiffHandler implements vscode.Disposable { this.currentLineIndex - this.insertedInCurrentBlock, totalDeletedContent, ); + this.redDecorationManager.addLines( this.currentLineIndex - this.insertedInCurrentBlock, this.deletionBuffer.length, ); + // Shift green decorations downward this.greenDecorationManager.shiftDownAfterLine( this.currentLineIndex - this.insertedInCurrentBlock, @@ -132,9 +137,9 @@ export class VerticalDiffHandler implements vscode.Disposable { for (let i = 0; i < this.deletionBuffer.length; i++) { this.incrementCurrentLineIndex(); } + this.deletionBuffer = []; this.insertedInCurrentBlock = 0; - this.refreshCodeLens(); } diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index da255e86d..544ccfa23 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -152,7 +152,7 @@ function InputToolbar(props: InputToolbarProps) { } > - @codebase + {getMetaKeyLabel()}⏎ @codebase Submit with the codebase as context ({getMetaKeyLabel()}⏎) diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 156c0b3b2..02c7d2ec4 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -1,532 +1,536 @@ import { - ArrowLeftIcon, - ChatBubbleOvalLeftIcon, - CodeBracketSquareIcon, - ExclamationTriangleIcon, + ArrowLeftIcon, + ChatBubbleOvalLeftIcon, + CodeBracketSquareIcon, + ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; -import { JSONContent } from "@tiptap/react"; -import { InputModifiers } from "core"; -import { usePostHog } from "posthog-js/react"; +import {JSONContent} from "@tiptap/react"; +import {InputModifiers} from "core"; +import {usePostHog} from "posthog-js/react"; import { - Fragment, - useCallback, - useContext, - useEffect, - useRef, - useState, + Fragment, + useCallback, + useContext, + useEffect, + useRef, + useState, } from "react"; -import { ErrorBoundary } from "react-error-boundary"; -import { useDispatch, useSelector } from "react-redux"; +import {ErrorBoundary} from "react-error-boundary"; +import {useDispatch, useSelector} from "react-redux"; import styled from "styled-components"; import { - Button, - defaultBorderRadius, - lightGray, - vscBackground, - vscForeground, + Button, + defaultBorderRadius, + lightGray, + vscBackground, + vscForeground, } from "../components"; -import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; +import {ChatScrollAnchor} from "../components/ChatScrollAnchor"; import StepContainer from "../components/gui/StepContainer"; import TimelineItem from "../components/gui/TimelineItem"; import ContinueInputBox from "../components/mainInput/ContinueInputBox"; -import { defaultInputModifiers } from "../components/mainInput/inputModifiers"; -import { TutorialCard } from "../components/mainInput/TutorialCard"; +import {defaultInputModifiers} from "../components/mainInput/inputModifiers"; +import {TutorialCard} from "../components/mainInput/TutorialCard"; import { - OnboardingCard, - useOnboardingCard, + OnboardingCard, + useOnboardingCard, } from "../components/OnboardingCard"; -import { IdeMessengerContext } from "../context/IdeMessenger"; +import {IdeMessengerContext} from "../context/IdeMessenger"; import useChatHandler from "../hooks/useChatHandler"; import useHistory from "../hooks/useHistory"; -import { useTutorialCard } from "../hooks/useTutorialCard"; -import { useWebviewListener } from "../hooks/useWebviewListener"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import {useTutorialCard} from "../hooks/useTutorialCard"; +import {useWebviewListener} from "../hooks/useWebviewListener"; +import {defaultModelSelector} from "../redux/selectors/modelSelectors"; import { - clearLastResponse, - deleteMessage, - newSession, - setInactive, + clearLastResponse, + deleteMessage, + newSession, + setInactive, } from "../redux/slices/stateSlice"; import { - setDialogEntryOn, - setDialogMessage, - setShowDialog, + setDialogEntryOn, + setDialogMessage, + setShowDialog, } from "../redux/slices/uiStateSlice"; -import { RootState } from "../redux/store"; +import {RootState} from "../redux/store"; import { - getFontSize, - getMetaKeyLabel, - isJetBrains, - isMetaEquivalentKeyPressed, + getFontSize, + getMetaKeyLabel, + isJetBrains, + isMetaEquivalentKeyPressed, } from "../util"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import {FREE_TRIAL_LIMIT_REQUESTS} from "../util/freeTrial"; +import {getLocalStorage, setLocalStorage} from "../util/localStorage"; const TopGuiDiv = styled.div<{ - showScrollbar?: boolean; + showScrollbar?: boolean; }>` - overflow-y: auto; - height: 100%; - scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; + overflow-y: auto; + height: 100%; + scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; - &::-webkit-scrollbar { - display: ${(props) => (props.showScrollbar ? "block" : "none")}; - } + &::-webkit-scrollbar { + display: ${(props) => (props.showScrollbar ? "block" : "none")}; + } `; const StopButton = styled.div` - width: fit-content; - margin-right: auto; - margin-left: auto; - font-size: ${getFontSize() - 2}px; - border: 0.5px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 4px 8px; - color: ${lightGray}; - cursor: pointer; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); - transition: box-shadow 0.3s ease; + width: fit-content; + margin-right: auto; + margin-left: auto; + font-size: ${getFontSize() - 2}px; + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + cursor: pointer; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); + transition: box-shadow 0.3s ease; - &:hover { - box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1); - } + &:hover { + box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1); + } `; const StepsDiv = styled.div` - position: relative; - background-color: transparent; - - & > * { position: relative; - } + background-color: transparent; - .thread-message { - margin: 8px 4px 0 4px; - } + & > * { + position: relative; + } + + .thread-message { + margin: 8px 4px 0 4px; + } `; const NewSessionButton = styled.div` - width: fit-content; - margin-right: auto; - margin-left: 6px; - margin-top: 2px; - margin-bottom: 8px; - font-size: ${getFontSize() - 2}px; + width: fit-content; + margin-right: auto; + margin-left: 6px; + margin-top: 2px; + margin-bottom: 8px; + font-size: ${getFontSize() - 2}px; - border-radius: ${defaultBorderRadius}; - padding: 2px 6px; - color: ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 2px 6px; + color: ${lightGray}; - &:hover { - background-color: ${lightGray}33; - color: ${vscForeground}; - } + &:hover { + background-color: ${lightGray}33; + color: ${vscForeground}; + } - cursor: pointer; + cursor: pointer; `; -function fallbackRender({ error, resetErrorBoundary }: any) { - // Call resetErrorBoundary() to reset the error boundary and retry the render. +function fallbackRender({error, resetErrorBoundary}: any) { + // Call resetErrorBoundary() to reset the error boundary and retry the render. - return ( -
-

Something went wrong:

-
{error.message}
-
- -
-
- ); + return ( +
+

Something went wrong:

+
{error.message}
+ +
+ +
+
+ ); } function GUI() { - const posthog = usePostHog(); - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); - const onboardingCard = useOnboardingCard(); - const { showTutorialCard, closeTutorialCard } = useTutorialCard(); - const sessionState = useSelector((state: RootState) => state.state); - const defaultModel = useSelector(defaultModelSelector); - const ttsActive = useSelector((state: RootState) => state.state.ttsActive); - const active = useSelector((state: RootState) => state.state.active); - const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); - const mainTextInputRef = useRef(null); - const topGuiDivRef = useRef(null); - const [isAtBottom, setIsAtBottom] = useState(false); - const state = useSelector((state: RootState) => state.state); - const { saveSession, getLastSessionId, loadLastSession } = - useHistory(dispatch); + const posthog = usePostHog(); + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const {streamResponse} = useChatHandler(dispatch, ideMessenger); + const onboardingCard = useOnboardingCard(); + const {showTutorialCard, closeTutorialCard} = useTutorialCard(); + const sessionState = useSelector((state: RootState) => state.state); + const defaultModel = useSelector(defaultModelSelector); + const ttsActive = useSelector((state: RootState) => state.state.ttsActive); + const active = useSelector((state: RootState) => state.state.active); + const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); + const mainTextInputRef = useRef(null); + const topGuiDivRef = useRef(null); + const [isAtBottom, setIsAtBottom] = useState(false); + const state = useSelector((state: RootState) => state.state); + const {saveSession, getLastSessionId, loadLastSession} = + useHistory(dispatch); - useEffect(() => { - if (!active || !topGuiDivRef.current) return; + useEffect(() => { + if (!active || !topGuiDivRef.current) return; - const scrollAreaElement = topGuiDivRef.current; + const scrollAreaElement = topGuiDivRef.current; - scrollAreaElement.scrollTop = - scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; + scrollAreaElement.scrollTop = + scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; - setIsAtBottom(true); - }, [active]); + setIsAtBottom(true); + }, [active]); - useEffect(() => { - // Cmd + Backspace to delete current step - const listener = (e: any) => { - if ( - e.key === "Backspace" && - isMetaEquivalentKeyPressed(e) && - !e.shiftKey - ) { - dispatch(setInactive()); - } + useEffect(() => { + // Cmd + Backspace to delete current step + const listener = (e: any) => { + if ( + e.key === "Backspace" && + isMetaEquivalentKeyPressed(e) && + !e.shiftKey + ) { + dispatch(setInactive()); + } + }; + window.addEventListener("keydown", listener); + + return () => { + window.removeEventListener("keydown", listener); + }; + }, [active]); + + const handleScroll = () => { + // Temporary fix to account for additional height when code blocks are added + const OFFSET_HERUISTIC = 300; + if (!topGuiDivRef.current) return; + + const {scrollTop, scrollHeight, clientHeight} = topGuiDivRef.current; + const atBottom = + scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; + + setIsAtBottom(atBottom); }; - window.addEventListener("keydown", listener); - return () => { - window.removeEventListener("keydown", listener); - }; - }, [active]); + const sendInput = useCallback( + (editorState: JSONContent, modifiers: InputModifiers) => { + if (defaultModel?.provider === "free-trial") { + const u = getLocalStorage("ftc"); + if (u) { + setLocalStorage("ftc", u + 1); - const handleScroll = () => { - // Temporary fix to account for additional height when code blocks are added - const OFFSET_HERUISTIC = 300; - if (!topGuiDivRef.current) return; - - const { scrollTop, scrollHeight, clientHeight } = topGuiDivRef.current; - const atBottom = - scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; - - setIsAtBottom(atBottom); - }; - - const sendInput = useCallback( - (editorState: JSONContent, modifiers: InputModifiers) => { - if (defaultModel?.provider === "free-trial") { - const u = getLocalStorage("ftc"); - if (u) { - setLocalStorage("ftc", u + 1); - - if (u >= FREE_TRIAL_LIMIT_REQUESTS) { - onboardingCard.open("Best"); - posthog?.capture("ftc_reached"); - ideMessenger.ide.showToast( - "info", - "You've reached the free trial limit. Please configure a model to continue.", - ); - return; - } - } else { - setLocalStorage("ftc", 1); - } - } - - streamResponse(editorState, modifiers, ideMessenger); - - // Increment localstorage counter for popup - const currentCount = getLocalStorage("mainTextEntryCounter"); - if (currentCount) { - setLocalStorage("mainTextEntryCounter", currentCount + 1); - if (currentCount === 300) { - dispatch( - setDialogMessage( -
- 👋 Thanks for using Continue. We are always trying to improve - and love hearing from users. If you're interested in speaking, - enter your name and email. We won't use this information for - anything other than reaching out. -
-
-
{ - e.preventDefault(); - posthog?.capture("user_interest_form", { - name: e.target.elements[0].value, - email: e.target.elements[1].value, - }); - dispatch( - setDialogMessage( -
- Thanks! We'll be in touch soon. -
, - ), - ); - }} - style={{ - display: "flex", - flexDirection: "column", - gap: "10px", - }} - > - - - -
-
, - ), - ); - dispatch(setDialogEntryOn(false)); - dispatch(setShowDialog(true)); - } - } else { - setLocalStorage("mainTextEntryCounter", 1); - } - }, - [ - sessionState.history, - sessionState.contextItems, - defaultModel, - state, - streamResponse, - ], - ); - - useWebviewListener( - "newSession", - async () => { - saveSession(); - mainTextInputRef.current?.focus?.(); - }, - [saveSession], - ); - - const isLastUserInput = useCallback( - (index: number): boolean => { - return !state.history - .slice(index + 1) - .some((entry) => entry.message.role === "user"); - }, - [state.history], - ); - - return ( - <> - -
- - {state.history.map((item, index: number) => ( - - { - dispatch(newSession()); - }} - > - {item.message.role === "user" ? ( - { - streamResponse( - editorState, - modifiers, - ideMessenger, - index, + if (u >= FREE_TRIAL_LIMIT_REQUESTS) { + onboardingCard.open("Best"); + posthog?.capture("ftc_reached"); + ideMessenger.ide.showToast( + "info", + "You've reached the free trial limit. Please configure a model to continue.", ); - }} - isLastUserInput={isLastUserInput(index)} - isMainInput={false} - editorState={item.editorState} - contextItems={item.contextItems} + return; + } + } else { + setLocalStorage("ftc", 1); + } + } + + streamResponse(editorState, modifiers, ideMessenger); + + // Increment localstorage counter for popup + const currentCount = getLocalStorage("mainTextEntryCounter"); + if (currentCount) { + setLocalStorage("mainTextEntryCounter", currentCount + 1); + if (currentCount === 300) { + dispatch( + setDialogMessage( +
+ 👋 Thanks for using Continue. We are always trying to improve + and love hearing from users. If you're interested in speaking, + enter your name and email. We won't use this information for + anything other than reaching out. +
+
+
{ + e.preventDefault(); + posthog?.capture("user_interest_form", { + name: e.target.elements[0].value, + email: e.target.elements[1].value, + }); + dispatch( + setDialogMessage( +
+ Thanks! We'll be in touch soon. +
, + ), + ); + }} + style={{ + display: "flex", + flexDirection: "column", + gap: "10px", + }} + > + + + +
+
, + ), + ); + dispatch(setDialogEntryOn(false)); + dispatch(setShowDialog(true)); + } + } else { + setLocalStorage("mainTextEntryCounter", 1); + } + }, + [ + sessionState.history, + sessionState.contextItems, + defaultModel, + state, + streamResponse, + ], + ); + + useWebviewListener( + "newSession", + async () => { + saveSession(); + mainTextInputRef.current?.focus?.(); + }, + [saveSession], + ); + + const isLastUserInput = useCallback( + (index: number): boolean => { + return !state.history + .slice(index + 1) + .some((entry) => entry.message.role === "user"); + }, + [state.history], + ); + + return ( + <> + +
+ + {state.history.map((item, index: number) => ( + + { + dispatch(newSession()); + }} + > + {item.message.role === "user" ? ( + { + streamResponse( + editorState, + modifiers, + ideMessenger, + index, + ); + }} + isLastUserInput={isLastUserInput(index)} + isMainInput={false} + editorState={item.editorState} + contextItems={item.contextItems} + /> + ) : ( +
+ + ) : false ? ( + + ) : ( + + ) + } + open={ + typeof stepsOpen[index] === "undefined" + ? false + ? false + : true + : stepsOpen[index]! + } + onToggle={() => { + }} + > + { + }} + item={item} + onReverse={() => { + }} + onRetry={() => { + streamResponse( + state.history[index - 1].editorState, + state.history[index - 1].modifiers ?? + defaultInputModifiers, + ideMessenger, + index - 1, + ); + }} + onContinueGeneration={() => { + window.postMessage( + { + messageType: "userInput", + data: { + input: + "Continue your response exactly where you left off:", + }, + }, + "*", + ); + }} + onDelete={() => { + dispatch(deleteMessage(index)); + }} + modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} + /> + +
+ )} +
+
+ ))} +
+ +
- ) : null} - - {onboardingCard.show && ( -
- -
- )} - - {showTutorialCard !== false && !onboardingCard.open && ( -
- -
- )} - - )} -
- - -
- - {ttsActive && ( - { - ideMessenger.post("tts/kill", undefined); - }} - > - ■ Stop TTS - - )} - {active && ( - { - dispatch(setInactive()); - if ( - state.history[state.history.length - 1]?.message.content - .length === 0 - ) { - dispatch(clearLastResponse()); - } - }} - > - {getMetaKeyLabel()} ⌫ Cancel - - )} - - ); + > + ■ Stop TTS + + )} + {active && ( + { + dispatch(setInactive()); + if ( + state.history[state.history.length - 1]?.message.content + .length === 0 + ) { + dispatch(clearLastResponse()); + } + }} + > + {getMetaKeyLabel()} ⌫ Cancel + + )} + + ); } export default GUI; From 6a075813585cc2c9605c2ca0765276fceaa091b4 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 9 Oct 2024 18:00:44 -0700 Subject: [PATCH 14/25] WIP --- .idea/gradle.xml | 1 - .../editor/DiffStreamHandler.kt | 475 +++++++++--------- .../editor/InlineEditAction.kt | 14 +- .../editor/VerticalDiffActionButtons.kt | 63 +-- .../vscode/src/diff/vertical/handler.ts | 11 +- manual-testing-sandbox/.idea/vcs.xml | 6 + 6 files changed, 286 insertions(+), 284 deletions(-) create mode 100644 manual-testing-sandbox/.idea/vcs.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml index 6733405f9..1d937028b 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -5,7 +5,6 @@