This commit is contained in:
Nate 2024-10-12 22:24:55 -07:00
commit 46ee430293
38 changed files with 1271 additions and 561 deletions

1
.idea/gradle.xml generated
View file

@ -5,7 +5,6 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="corretto-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

View file

@ -0,0 +1,139 @@
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
FetchFunction,
} 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;
type?: number;
guild_id?: string;
}
interface DiscordMessage {
id: string;
content: string;
author: {
id: string;
username: string;
};
timestamp: string;
}
class DiscordContextProvider extends BaseContextProvider {
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 full fetch URL
private getUrl(path: string): string {
return `${this.baseUrl}${path}`;
}
async fetchMessages(
channelId: string,
fetch: FetchFunction,
): Promise<Array<DiscordMessage>> {
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 ${this.options.discordKey}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`Failed to fetch messages: ${response.statusText}`);
}
return response.json();
}
async fetchChannels(fetch: FetchFunction): Promise<Array<DiscordChannel>> {
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);
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const channels = await this.fetchChannels(extras.fetch);
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;
const parts = ["# Discord Channel Messages", `Channel ID: ${channelId}`];
const messages = await this.fetchMessages(channelId, extras.fetch);
if (messages.length > 0) {
parts.push("## Messages");
// Format each message into a markdown string
messages.forEach((message) => {
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",
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const channels = await this.fetchChannels(args.fetch);
return channels.map((channel) => ({
id: channel.id,
title: channel.name || `Channel ${channel.id}`,
description: channel.topic ?? "",
}));
}
}
export default DiscordContextProvider;

View file

@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider";
import TerminalContextProvider from "./TerminalContextProvider";
import URLContextProvider from "./URLContextProvider";
import RepoMapContextProvider from "./RepoMapContextProvider";
import DiscordContextProvider from "./DiscordContextProvider";
import GreptileContextProvider from "./GreptileContextProvider";
/**
@ -54,6 +55,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
URLContextProvider,
ContinueProxyContextProvider,
RepoMapContextProvider,
DiscordContextProvider,
GreptileContextProvider,
];

View file

@ -22,7 +22,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
toggleFullScreen: [undefined, void];
toggleFullScreen: [{ newWindow?: boolean } | undefined, void];
insertAtCursor: [{ text: string }, void];
copyText: [{ text: string }, void];
"jetbrains/editorInsetHeight": [{ height: number }, void];

View file

@ -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

View file

@ -73,4 +73,4 @@ If you need to force a refresh of the index, reload the VS Code window with `cmd
## Repository map
Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebsae retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=0.0.75
pluginVersion=0.0.76
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
#pluginUntilBuild = 232.*

View file

@ -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<TerminalActivityTrackingService>().update(
// TerminalView.getInstance(project).widgets
// )
// }
// }
// }
// )
initializePlugin(project)
}
@ -186,8 +169,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
val listener =
ContinuePluginSelectionListener(
ideProtocolClient,
coroutineScope
coroutineScope,
)
// Reload the WebView

View file

@ -1,25 +1,18 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.command.undo.UndoManager
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
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.ui.JBColor
import javax.swing.BorderFactory
import javax.swing.JTextArea
import com.intellij.openapi.vfs.VirtualFile
import kotlin.math.min
@ -30,62 +23,73 @@ enum class DiffLineType {
class DiffStreamHandler(
private val project: Project,
private val editor: Editor,
private val textArea: JTextArea,
private val startLine: Int,
private val endLine: Int,
private val onClose: () -> Unit,
private val onFinish: () -> Unit
) {
// Text attributes keys
private val greenKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
}
val key = TextAttributesKey.createTextAttributesKey("CONTINUE_DIFF_NEW_LINE")
key.let { editor.colorsScheme.setAttributes(it, attributes) }
key
}
private data class CurLineState(
var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
)
private val currentLineKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x40888888.toInt(), 0x40888888.toInt())
}
val key = TextAttributesKey.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE")
key.let { editor.colorsScheme.setAttributes(it, attributes) }
key
}
private val unfinishedKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x20888888.toInt(), 0x20888888.toInt())
}
val key = TextAttributesKey.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE")
key.let { editor.colorsScheme.setAttributes(it, attributes) }
key
}
private var curLine = CurLineState(startLine)
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
private var isRunning: Boolean = false
private var hasAcceptedOrRejectedBlock: Boolean = false
// State variables
private var currentLine = startLine
private var currentLineHighlighter: RangeHighlighter? = null
private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
private var changeCount: Int = 0 // Kept track of so we can count steps to undo when cancelling
private var running: Boolean = false
private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
private var deletionBufferStartLine: Int = -1
private val deletionsBuffer: MutableList<String> = mutableListOf()
private val deletionInlays: MutableList<Disposable> = mutableListOf()
private val curLineKey = createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888, editor)
private val unfinishedKey = createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888, editor)
private fun removeDeletionInlays() {
deletionInlays.forEach {
it.dispose()
}
deletionInlays.clear()
init {
initUnfinishedRangeHighlights()
}
fun setup() {
// Highlight the range with unfinished color
fun acceptAll() {
editor.markupModel.removeAllHighlighters()
resetState()
}
fun rejectAll() {
// The ideal action here is to undo all changes we made to return the user's edit buffer to the state prior
// to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple
// way to undo our changes without also undoing the diff that the user accepted or rejected.
if (hasAcceptedOrRejectedBlock) {
diffBlocks.forEach { it.handleReject() }
} else {
undoChanges()
}
resetState()
}
fun streamDiffLinesToEditor(
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String
) {
isRunning = true
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
val virtualFile = getVirtualFile()
continuePluginService.coreMessenger?.request(
"streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle), null
) { response ->
if (!isRunning) return@request
val parsed = response as Map<*, *>
if (response["done"] as? Boolean == true) {
handleFinishedResponse()
return@request
}
handleDiffLineResponse(parsed)
}
}
private fun initUnfinishedRangeHighlights() {
for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(
unfinishedKey, min(
@ -96,211 +100,185 @@ class DiffStreamHandler(
}
}
private fun deleteLineAt(index: Int) {
val startOffset = editor.document.getLineStartOffset(index)
val endOffset = editor.document.getLineEndOffset(index) + 1
editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength))
}
private fun insertDeletionBuffer() {
// Insert red highlighted code between the real lines in the editor
if (deletionBufferStartLine != -1 && deletionsBuffer.isNotEmpty()) {
val component = JTextArea().apply {
text = deletionsBuffer.joinToString("\n")
isEditable = false
background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt())
foreground = JBColor.GRAY
border = BorderFactory.createEmptyBorder(0, 0, 0, 0)
lineWrap = false
wrapStyleWord = false
font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
private fun handleDiffLine(type: DiffLineType, text: String) {
try {
when (type) {
DiffLineType.SAME -> handleSameLine()
DiffLineType.NEW -> handleNewLine(text)
DiffLineType.OLD -> handleOldLine()
}
val disposable = editorComponentInlaysManager.insert(deletionBufferStartLine, component, true)
updateProgressHighlighters(type)
if (disposable != null) {
deletionInlays.add(disposable)
// Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
// we reach EOF while in a diff block, since we won't encounter a "same" line.
if (curLine.index >= editor.document.lineCount - 1) {
curLine.diffBlock?.onLastDiffLine()
}
// Clear the buffer
deletionsBuffer.clear()
deletionBufferStartLine = -1
} catch (e: Exception) {
println("Error handling diff line: ${curLine.index}, $type, $text, ${e.message}")
}
}
private fun handleDiffLine(type: DiffLineType, line: String) {
println("DiffStreamHandler: handleDiffLine: $currentLine, $type, $line")
try {
when (type) {
DiffLineType.SAME -> {
insertDeletionBuffer()
currentLine++
}
private fun handleDiffBlockAcceptOrReject(diffBlock: VerticalDiffBlock, didAccept: Boolean) {
hasAcceptedOrRejectedBlock = true
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")
diffBlocks.remove(diffBlock)
// Highlight the new line green
editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST)
if (!didAccept) {
updatePositionsOnReject(diffBlock.startLine, diffBlock.addedLines.size, diffBlock.deletedLines.size)
}
insertDeletionBuffer()
if (diffBlocks.isEmpty()) {
onClose()
}
}
currentLine++
changeCount++
}
DiffLineType.OLD -> {
// Remove old line
deleteLineAt(currentLine)
private fun createDiffBlock(): VerticalDiffBlock {
val diffBlock = VerticalDiffBlock(
editor, project, curLine.index, ::handleDiffBlockAcceptOrReject
)
diffBlocks.add(diffBlock)
// Add to deletions buffer
deletionsBuffer.add(line)
if (deletionBufferStartLine == -1) {
deletionBufferStartLine = currentLine
}
return diffBlock
}
changeCount++
}
private fun handleSameLine() {
if (curLine.diffBlock != null) {
curLine.diffBlock!!.onLastDiffLine()
}
curLine.diffBlock = null
curLine.index++
}
private fun handleNewLine(text: String) {
if (curLine.diffBlock == null) {
curLine.diffBlock = createDiffBlock()
}
curLine.diffBlock!!.addNewLine(text, curLine.index)
curLine.index++
}
private fun handleOldLine() {
if (curLine.diffBlock == null) {
curLine.diffBlock = createDiffBlock()
}
curLine.diffBlock!!.deleteLineAt(curLine.index)
}
private fun updateProgressHighlighters(type: DiffLineType) {
// Update the highlighter to show the current line
curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
curLine.highlighter = editor.markupModel.addLineHighlighter(
curLineKey, min(curLine.index, editor.document.lineCount - 1), HighlighterLayer.LAST
)
// Remove the unfinished lines highlighter
if (type != DiffLineType.OLD && unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
}
}
private fun updatePositionsOnReject(startLine: Int, numAdditions: Int, numDeletions: Int) {
val offset = -numAdditions + numDeletions
diffBlocks.forEach { block ->
if (block.startLine > startLine) {
block.updatePosition(block.startLine + offset)
}
// Highlight the current line
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
currentLineHighlighter = editor.markupModel.addLineHighlighter(
currentLineKey,
min(currentLine, editor.document.lineCount - 1),
HighlighterLayer.LAST
)
// Remove the unfinished highlighter top line
if (type != DiffLineType.OLD) {
if (unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
}
}
} catch (e: Exception) {
println("Error handling diff line: $currentLine, $type, $line, $e.message")
}
}
private fun resetState() {
// Remove all highlighters
// Clear the editor of highlighting/inlays
editor.markupModel.removeAllHighlighters()
diffBlocks.forEach { it.clearEditorUI() }
// Remove all of the deletion inlays
removeDeletionInlays()
// Clear state vars
diffBlocks.clear()
curLine = CurLineState(startLine)
isRunning = false
// Undo changes just by using builtin undo
// Close the Edit input
onClose()
}
private fun undoChanges() {
WriteCommandAction.runWriteCommandAction(project) {
val undoManager = UndoManager.getInstance(project)
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) ?: return@runWriteCommandAction
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor?
val virtualFile = getVirtualFile() ?: return@runWriteCommandAction
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor
if (undoManager.isUndoAvailable(fileEditor)) {
for (i in 0 until changeCount) {
val numChanges = diffBlocks.sumOf { it.deletedLines.size + it.addedLines.size }
repeat(numChanges) {
undoManager.undo(fileEditor)
}
}
// Reset state variables
currentLine = startLine
changeCount = 0
}
}
fun accept() {
// Accept the changes
editor.markupModel.removeAllHighlighters()
removeDeletionInlays()
onClose()
running = false
private fun getVirtualFile(): VirtualFile? {
return FileDocumentManager.getInstance().getFile(editor.document) ?: return null
}
fun reject() {
// Reject the changes
resetState()
removeDeletionInlays()
onClose()
running = false
}
fun toggleFocus() {
if (textArea.hasFocus()) {
textArea.transferFocus()
editor.contentComponent.requestFocus()
} else {
textArea.requestFocus()
}
}
fun run(input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String) {
// Undo changes
resetState()
running = true
// Highlight the range with unfinished color
setup()
// Request diff stream from core
val continuePluginService = ServiceManager.getService(
this.project,
ContinuePluginService::class.java
private fun createRequestParams(
input: String,
prefix: String,
highlighted: String,
suffix: String,
virtualFile: VirtualFile?,
modelTitle: String
): Map<String, Any?> {
return mapOf(
"input" to input,
"prefix" to prefix,
"highlighted" to highlighted,
"suffix" to suffix,
"language" to virtualFile?.fileType?.name,
"modelTitle" to modelTitle
)
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
continuePluginService.coreMessenger?.request(
"streamDiffLines", mapOf(
"input" to input,
"prefix" to prefix,
"highlighted" to highlighted,
"suffix" to suffix,
"language" to virtualFile?.fileType?.name,
"modelTitle" to modelTitle
), null
) { response ->
if (!running) {
return@request
}
}
val parsed = response as Map<*, *>
val done = parsed["done"] as? Boolean
if (done == true) {
onFinish()
private fun handleFinishedResponse() {
onFinish()
ApplicationManager.getApplication().invokeLater {
// Clean up progress highlighters
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
unfinishedHighlighters.forEach { editor.markupModel.removeHighlighter(it) }
ApplicationManager.getApplication().invokeLater {
cleanupProgressHighlighters()
}
}
// Flush deletion buffer
insertDeletionBuffer()
private fun cleanupProgressHighlighters() {
curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
unfinishedHighlighters.forEach { editor.markupModel.removeHighlighter(it) }
}
// Add ", " to the text area
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
}
return@request
}
val data = parsed["content"] as Map<*, *>
val type = data["type"] as String
val diffLineType = when (type) {
"same" -> DiffLineType.SAME
"new" -> DiffLineType.NEW
"old" -> DiffLineType.OLD
else -> throw Exception("Unknown diff line type: $type")
}
private fun handleDiffLineResponse(parsed: Map<*, *>) {
val data = parsed["content"] as Map<*, *>
val diffLineType = getDiffLineType(data["type"] as String)
WriteCommandAction.runWriteCommandAction(project) {
handleDiffLine(diffLineType, data["line"] as String)
}
WriteCommandAction.runWriteCommandAction(project) {
handleDiffLine(diffLineType, data["line"] as String)
}
}
private fun getDiffLineType(type: String): DiffLineType {
return when (type) {
"same" -> DiffLineType.SAME
"new" -> DiffLineType.NEW
"old" -> DiffLineType.OLD
else -> throw Exception("Unknown diff line type: $type")
}
}
}

View file

@ -9,23 +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)
}
fun getHandler(editor: Editor): DiffStreamHandler? {
return handlers[editor]
}
}

View file

@ -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
@ -42,6 +40,7 @@ class EditorComponentInlaysManager(val editor: EditorImpl, private val onlyOneIn
EditorUtil.disposeWithEditor(editor, this)
}
@RequiresEdt
fun insert(lineIndex: Int, component: JComponent, showAbove: Boolean = false): Disposable? {
if (Disposer.isDisposed(this)) return null

View file

@ -1,9 +1,22 @@
package com.github.continuedev.continueintellijextension.editor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
class EditorUtils {
fun isTerminal(editor: Editor): Boolean {
return editor.javaClass.name.contains("Terminal")
}
}
}
fun createTextAttributesKey(name: String, color: Int, editor: Editor): TextAttributesKey {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(color, color)
}
return TextAttributesKey.createTextAttributesKey(name).also {
editor.colorsScheme.setAttributes(it, attributes)
}
}

View file

@ -3,7 +3,7 @@ package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.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,20 +130,31 @@ 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)
val endLineNumber = editor.document.getLineNumber(selectionModel.selectionEnd)
val start = editor.document.getLineStartOffset(startLineNumber)
val end = editor.document.getLineEndOffset(endLineNumber)
val prefix = editor.document.getText(TextRange(0, start))
val highlighted = editor.document.getText(TextRange(start, end))
val suffix = editor.document.getText(TextRange(end, editor.document.textLength))
val startOffset = selectionModel.selectionStart
val endOffset = selectionModel.selectionEnd
val startLineNumber = editor.document.getLineNumber(startOffset)
var endLineNumber = editor.document.getLineNumber(endOffset)
// Doesn't seem to be any built-in methods to check for a line selection that contains trailing newlines.
// The only case this matters is when a user double-clicks to highlight a full line. Without this check.
// the highlighted range will continue to the following line.
val isSingleLineSelection = endLineNumber > startLineNumber &&
endLineNumber < editor.document.lineCount &&
editor.document.getLineStartOffset(endLineNumber) == endOffset
if (isSingleLineSelection) {
endLineNumber--
}
val prefix = editor.document.getText(TextRange(0, startOffset))
val highlighted = editor.document.getText(TextRange(startOffset, endOffset))
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
val lineNumber = max(0, startLineNumber - 1)
val startLineNum = editor.document.getLineNumber(start)
val endLineNum = editor.document.getLineNumber(end)
val lineNumber = max(0, startLineNum - 1)
// Un-highlight the selected text
selectionModel.removeSelection()
@ -165,28 +176,35 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler = DiffStreamHandler(project, editor, textArea, startLineNum, endLineNum, {
val diffStreamHandler = DiffStreamHandler(project, editor, startLineNumber, endLineNumber, {
inlayRef.get().dispose()
}, {
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
})
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.setup()
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" ▾")
customPanelRef.get().enter()
diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret)
diffStreamHandler.streamDiffLinesToEditor(
textArea.text,
prefix,
highlighted,
suffix,
selectedModelStrippedOfCaret
)
}
val panel =
makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, { onEnter() }, {
diffStreamService.reject(editor)
selectionModel.setSelection(start, end)
selectionModel.setSelection(startOffset, endOffset)
}, {
diffStreamService.accept(editor)
inlayRef.get().dispose()
@ -194,13 +212,17 @@ fun openInlineEdit(project: Project?, editor: Editor) {
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNum, panel, true)
val inlay = manager.insert(startLineNumber, panel, true)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
// Scroll to the top of the startLine plus the height of the panel
editor.scrollingModel.scrollVertically(editor.visualLineToY(startLineNumber) - panel.height)
// Add key listener to text area
textArea.addKeyListener(object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
@ -214,7 +236,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
selectionModel.setSelection(start, end)
selectionModel.setSelection(startOffset, endOffset)
}
KeyEvent.VK_ENTER -> {
@ -311,11 +333,11 @@ class CustomPanel(
private val closeButton: JComponent = createCloseButton()
private val originalTextColor: Color = textArea.foreground
private val greyTextColor: Color = Color(128, 128, 128, 200)
public var isFinished = false
var isFinished = false
init {
isOpaque = false
add(closeButton, "pos 100%-25 0 -3 3, w 20!, h 20!")
add(closeButton, "pos 100%-20 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
@ -323,7 +345,7 @@ class CustomPanel(
foreground = Color(128, 128, 128, 128)
background = Color(0, 0, 0, 0)
font = UIUtil.getFontWithFallback("Arial", Font.BOLD, 10)
border = EmptyBorder(2, 6, 2, 6)
border = EmptyBorder(2, 6, 2, 0)
toolTipText = "`esc` to cancel"
isOpaque = false
@ -389,7 +411,7 @@ class CustomPanel(
add(rightButton, "align right")
}
border = EmptyBorder(0, 0, 20, 16)
border = EmptyBorder(0, 0, 16, 12)
add(dropdown, "align left")
add(rightPanel, "align right, split 2")
@ -406,7 +428,7 @@ class CustomPanel(
}
add(progressBar, BorderLayout.CENTER)
border = BorderFactory.createEmptyBorder(0, 0, 20, 16)
border = BorderFactory.createEmptyBorder(0, 0, 16, 12)
}
private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
@ -416,16 +438,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 {
@ -437,7 +457,7 @@ class CustomPanel(
add(leftLabel, "align left")
add(rightPanel, "align right")
border = BorderFactory.createEmptyBorder(0, 0, 20, 16)
border = BorderFactory.createEmptyBorder(0, 0, 16, 12)
isOpaque = false
}
@ -564,9 +584,9 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
if (isHovered) {
val brightenFactor = 1.1f
val brighterColor = Color(
(background.red * brightenFactor).toInt(),
(background.green * brightenFactor).toInt(),
(background.blue * brightenFactor).toInt()
(background.red * brightenFactor).coerceIn(0f, 255f).toInt(),
(background.green * brightenFactor).coerceIn(0f, 255f).toInt(),
(background.blue * brightenFactor).coerceIn(0f, 255f).toInt()
)
g2.color = brighterColor
} else {

View file

@ -1,8 +1,6 @@
import com.github.continuedev.continueintellijextension.actions.focusContinueInput
import com.github.continuedev.continueintellijextension.editor.openInlineEdit
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.ui.components.JBPanel

View file

@ -0,0 +1,233 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import java.awt.*
import javax.swing.BorderFactory
import javax.swing.JButton
import javax.swing.JTextArea
import kotlin.math.min
class VerticalDiffBlock(
private val editor: Editor,
private val project: Project,
var startLine: Int,
private val onAcceptReject: (VerticalDiffBlock, Boolean) -> Unit
) {
val deletedLines: MutableList<String> = mutableListOf();
val addedLines: MutableList<String> = mutableListOf();
private val acceptButton: JButton
private val rejectButton: JButton
private var deletionInlay: Disposable? = null
private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
private val greenKey = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor)
init {
val (acceptBtn, rejectBtn) = createButtons()
acceptButton = acceptBtn
rejectButton = rejectBtn
}
fun clearEditorUI() {
deletionInlay?.dispose()
removeGreenHighlighters()
removeButtons()
}
fun updatePosition(newLineNumber: Int) {
startLine = newLineNumber
val (x, y) = getButtonsXYPositions()
rejectButton.location = Point(x, y)
acceptButton.location = Point(x + rejectButton.preferredSize.width + 5, y)
refreshEditor()
}
fun deleteLineAt(line: Int) {
val startOffset = editor.document.getLineStartOffset(line)
val endOffset = editor.document.getLineEndOffset(line) + 1
val deletedText = editor.document.getText(TextRange(startOffset, endOffset))
deletedLines.add(deletedText.trimEnd())
editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength))
}
fun addNewLine(text: String, line: Int) {
if (line == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
}
val offset = editor.document.getLineStartOffset(line)
editor.document.insertString(offset, text + "\n")
editor.markupModel.addLineHighlighter(greenKey, line, HighlighterLayer.LAST)
addedLines.add(text)
}
fun onLastDiffLine() {
if (deletedLines.size > 0) {
renderDeletedLinesInlay()
}
renderButtons()
}
fun handleReject() {
revertDiff()
clearEditorUI()
}
private fun refreshEditor() {
editor.contentComponent.revalidate()
editor.contentComponent.repaint()
}
private fun renderDeletedLinesInlay() {
val textArea = createDeletionTextArea(deletedLines.joinToString("\n"))
this.textArea = textArea
val disposable = editorComponentInlaysManager.insert(startLine, textArea, true)
deletionInlay = disposable
}
private fun renderButtons() {
val (x, y) = getButtonsXYPositions()
rejectButton.setBounds(
x,
y,
rejectButton.preferredSize.width,
rejectButton.preferredSize.height
)
acceptButton.setBounds(
x + rejectButton.width + 5,
y,
acceptButton.preferredSize.width,
acceptButton.preferredSize.height
)
editor.contentComponent.add(acceptButton)
editor.contentComponent.add(rejectButton)
editor.contentComponent.setComponentZOrder(acceptButton, 0)
editor.contentComponent.setComponentZOrder(rejectButton, 0)
refreshEditor()
}
private fun createButtons(): Pair<JButton, JButton> {
val rejectBtn =
createButton("${getAltKeyLabel()}⇧N", JBColor(0x99FF0000.toInt(), 0x99FF0000.toInt())).apply {
addActionListener {
handleReject();
onAcceptReject(this@VerticalDiffBlock, false)
}
}
val acceptBtn =
createButton("${getAltKeyLabel()}⇧Y", JBColor(0x9900FF00.toInt(), 0x9900FF00.toInt())).apply {
addActionListener {
handleAccept();
onAcceptReject(this@VerticalDiffBlock, true)
}
}
return Pair(acceptBtn, rejectBtn)
}
private fun removeButtons() {
editor.contentComponent.remove(acceptButton)
editor.contentComponent.remove(rejectButton)
refreshEditor()
}
private fun handleAccept() {
clearEditorUI()
}
private fun revertDiff() {
WriteCommandAction.runWriteCommandAction(project) {
// Delete the added lines
val startOffset = editor.document.getLineStartOffset(startLine)
val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1
editor.document.deleteString(startOffset, endOffset)
// Add the deleted lines back
if (deletedLines.isNotEmpty()) {
editor.document.insertString(startOffset, deletedLines.joinToString("\n") + "\n")
}
}
}
private fun removeGreenHighlighters() {
val highlightersToRemove = editor.markupModel.allHighlighters.filter { highlighter ->
val highlighterLine = editor.document.getLineNumber(highlighter.startOffset)
highlighterLine in startLine until (startLine + addedLines.size)
}
highlightersToRemove.forEach { editor.markupModel.removeHighlighter(it) }
}
private fun createDeletionTextArea(text: String) = JTextArea(text).apply {
isEditable = false
background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt())
foreground = JBColor.GRAY
border = BorderFactory.createEmptyBorder()
lineWrap = false
wrapStyleWord = false
font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
}
private fun getButtonsXYPositions(): Pair<Int, Int> {
val visibleArea = editor.scrollingModel.visibleArea
val textAreaHeight = this.textArea?.height ?: 0
val lineStartPosition = editor.logicalPositionToXY(LogicalPosition(startLine, 0))
val xPosition =
visibleArea.x + visibleArea.width - acceptButton.preferredSize.width - rejectButton.preferredSize.width - 20
val yPosition = lineStartPosition.y - textAreaHeight
return Pair(xPosition, yPosition)
}
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)
}
}
}

View file

@ -1,7 +1,6 @@
package com.github.continuedev.continueintellijextension.listeners
import ToolTipComponent
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.utils.Debouncer
@ -18,19 +17,36 @@ import kotlinx.coroutines.CoroutineScope
import com.intellij.openapi.editor.Document
class ContinuePluginSelectionListener(
private val ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
coroutineScope: CoroutineScope,
) : SelectionListener, DumbAware {
private val debouncer = Debouncer(100, coroutineScope)
private var toolTipComponents: ArrayList<ToolTipComponent> = ArrayList()
private var lastActiveEditor: Editor? = null
override fun selectionChanged(e: SelectionEvent) {
debouncer.debounce { handleSelection(e) }
}
private fun removeAllTooltips() {
ApplicationManager.getApplication().invokeLater {
toolTipComponents.forEach { tooltip ->
tooltip.parent?.remove(tooltip)
}
toolTipComponents.clear()
}
}
private fun handleSelection(e: SelectionEvent) {
ApplicationManager.getApplication().runReadAction {
val editor = e.editor
// Fixes a bug where the tooltip isn't being disposed of when opening new files
if (editor != lastActiveEditor) {
removeAllTooltips()
lastActiveEditor = editor
}
val model: SelectionModel = editor.selectionModel
val selectedText = model.selectedText

View file

@ -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 -> "^"
}
}

View file

@ -48,7 +48,6 @@
<actions>
<action class="com.github.continuedev.continueintellijextension.editor.InlineEditAction"
id="continue.inlineEdit"
icon="/tool-window-icon.svg"
description="Inline Edit"
text="Inline Edit">
<keyboard-shortcut keymap="$default"
@ -59,29 +58,46 @@
</action>
<action id="continue.acceptDiff"
icon="/tool-window-icon.svg"
class="com.github.continuedev.continueintellijextension.actions.AcceptDiffAction"
text="Accept Diff" description="Accept Diff">
<keyboard-shortcut keymap="$default"
first-keystroke="alt shift Y"/>
first-keystroke="shift ctrl ENTER"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="alt shift Y"/>
first-keystroke="shift meta ENTER"/>
<override-text place="GoToAction" text="Continue: Accept Diff"/>
</action>
<action id="continue.rejectDiff"
icon="/tool-window-icon.svg"
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
text="Reject Diff" description="Reject Diff">
<keyboard-shortcut keymap="$default"
first-keystroke="shift ctrl DELETE"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="shift meta DELETE"/>
<override-text place="GoToAction" text="Continue: Reject Diff"/>
</action>
<action id="continue.acceptVerticalDiffBlock"
class="com.github.continuedev.continueintellijextension.actions.AcceptDiffAction"
text="Accept Diff" description="Accept Vertical Diff Block">
<keyboard-shortcut keymap="$default"
first-keystroke="alt shift Y"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="alt shift Y"/>
<override-text place="GoToAction" text="Continue: Accept Vertical Diff Block"/>
</action>
<action id="continue.rejectVerticalDiffBlock"
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
text="Reject Diff" description="Reject Vertical Diff Block">
<keyboard-shortcut keymap="$default"
first-keystroke="alt shift N"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="alt shift N"/>
<override-text place="GoToAction" text="Continue: Reject Diff "/>
<override-text place="GoToAction" text="Continue: Reject Vertical Diff Block"/>
</action>
<action id="continue.focusContinueInputWithoutClear"
icon="/tool-window-icon.svg"
class="com.github.continuedev.continueintellijextension.actions.FocusContinueInputWithoutClearAction"
text="Add selected code to context"
description="Focus Continue Input With Edit">
@ -93,7 +109,7 @@
</action>
<action id="continue.newContinueSession"
icon="/tool-window-icon.svg"
icon="AllIcons.General.Add"
class="com.github.continuedev.continueintellijextension.actions.NewContinueSessionAction"
text="Start New Continue Session"
description="Start New Continue Session">
@ -102,7 +118,7 @@
</action>
<action id="continue.viewHistory"
icon="/tool-window-icon.svg"
icon="AllIcons.Vcs.History"
class="com.github.continuedev.continueintellijextension.actions.ViewHistoryAction"
text="View History"
description="View History">
@ -110,7 +126,6 @@
</action>
<action id="continue.focusContinueInput"
icon="/tool-window-icon.svg"
class="com.github.continuedev.continueintellijextension.actions.FocusContinueInputAction"
text="Add selected code to context"
description="Focus Continue Input">

View file

@ -1610,6 +1610,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": {

View file

@ -1610,6 +1610,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": {

View file

@ -1781,6 +1781,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": {

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.215",
"version": "0.9.216",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.215",
"version": "0.9.216",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.215",
"version": "0.9.216",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -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": [

View file

@ -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,6 +724,10 @@ 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");

View file

@ -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();
}
@ -398,6 +403,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Shift everything below upward
const offset = -(accept ? numRed : numGreen);
this.redDecorationManager.shiftDownAfterLine(startLine, offset);
this.greenDecorationManager.shiftDownAfterLine(startLine, offset);

View file

@ -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";

View file

@ -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,15 +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`
@ -71,7 +64,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 +74,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 +116,18 @@ function TableRow({
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<div className="flex justify-between items-center w-full">
<TdDiv
onClick={async () => {
// Save current session
saveSession();
await loadSession(session.sessionId);
navigate("/");
}}
>
<div className="text-md w-100">
{editing ? (
<div
className="flex max-w-full box-border px-4 py-2"
onClick={async () => {
// Save current session
saveSession();
await loadSession(session.sessionId);
navigate("/");
}}
>
<div className="cursor-pointer flex-1">
{editing ? (
<div className="text-md">
<Input
type="text"
style={{ width: "100%" }}
@ -152,15 +137,17 @@ function TableRow({
onKeyUp={(e) => handleKeyUp(e)}
onBlur={() => setEditing(false)}
/>
) : (
JSON.stringify(session.title).slice(1, -1)
)}
</div>
</div>
) : (
<span className="truncate max-w-60 block">
{JSON.stringify(session.title).slice(1, -1)}
</span>
)}
<div style={{ color: "#9ca3af" }}>
{lastPartOfPath(session.workspaceDirectory || "")}
<div className="flex" style={{ color: "#9ca3af" }}>
<span>{lastPartOfPath(session.workspaceDirectory || "")}</span>
{!hovered && (
<span className="inline-block float-right">
<span className="inline-block ml-auto">
{date.toLocaleString("en-US", {
year: "2-digit",
month: "2-digit",
@ -172,31 +159,29 @@ function TableRow({
</span>
)}
</div>
</TdDiv>
</div>
{hovered && (
<ButtonWithTooltip
className="mr-2"
text="Edit"
onClick={async () => {
setEditing(true);
}}
>
<PencilSquareIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
)}
{hovered && (
<ButtonWithTooltip
className="mr-2"
text="Delete"
onClick={async () => {
deleteSession(session.sessionId);
onDelete(session.sessionId);
}}
>
<TrashIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
<div className="ml-auto pl-2 gap-x-2 flex">
<ButtonWithTooltip
text="Edit"
onClick={async (e) => {
e.stopPropagation();
setEditing(true);
}}
>
<PencilSquareIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
<ButtonWithTooltip
text="Delete"
onClick={async () => {
deleteSession(session.sessionId);
onDelete(session.sessionId);
}}
>
<TrashIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
</div>
)}
</div>
</td>
@ -208,10 +193,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<SessionInfo[]>([]);
const [filteredAndSortedSessions, setFilteredAndSortedSessions] = useState<
SessionInfo[]
@ -227,11 +209,8 @@ function History() {
const searchInputRef = React.useRef<HTMLInputElement>(null);
const stickyHistoryHeaderRef = React.useRef<HTMLDivElement>(null);
const [headerHeight, setHeaderHeight] = useState(0);
const dispatch = useDispatch();
const { getHistory } = useHistory(dispatch);
const { getHistory, lastSessionId } = useHistory(dispatch);
const [minisearch, setMinisearch] = useState<
MiniSearch<{ title: string; sessionId: string }>
@ -256,7 +235,7 @@ function History() {
);
};
fetchSessions();
}, []);
}, [lastSessionId]);
useEffect(() => {
// When searchTerm is empty only show sessions from the current workspace
@ -297,138 +276,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 (
<div className="overflow-y-scroll" style={{ fontSize: getFontSize() }}>
<div
ref={stickyHistoryHeaderRef}
className="sticky top-0"
style={{ backgroundColor: vscBackground }}
>
<div
className="items-center flex m-0 p-0"
<div style={{ fontSize: getFontSize() }}>
<SearchBarContainer className="space-x-2">
<SearchBar
className="flex-1 w-full"
ref={searchInputRef}
placeholder="Search past sessions"
type="text"
onChange={(e) => setSearchTerm(e.target.value)}
/>
<span
className="block text-center px-2 py-1.5 rounded-md w-12 mx-1 my-2 select-none cursor-pointer"
style={{
borderBottom: `0.5px solid ${lightGray}`,
fontSize: "11px",
backgroundColor:
searchTerm !== "" ? vscInputBackground : vscBadgeBackground,
}}
onClick={() => {
if (searchInputRef.current.value === "") {
searchInputRef.current.value = "*";
setSearchTerm("*");
} else {
searchInputRef.current.value = "";
setSearchTerm("");
}
}}
>
<ArrowLeftIcon
width="1.2em"
height="1.2em"
onClick={() => navigate("/")}
className="inline-block ml-4 cursor-pointer"
/>
<h3 className="text-lg font-bold m-2 inline-block">History</h3>
{searchTerm === "" ? "Show All" : "Clear"}
</span>
</SearchBarContainer>
{filteredAndSortedSessions.length === 0 && (
<div className="text-center m-4">
No past sessions found. To start a new session, either click the "+"
button or use the keyboard shortcut: <b>Option + Command + N</b>
</div>
{/* {workspacePaths && workspacePaths.length > 0 && (
<CheckDiv
checked={filteringByWorkspace}
onClick={() => setFilteringByWorkspace((prev) => !prev)}
title={`Show only sessions from ${lastPartOfPath(
workspacePaths[workspacePaths.length - 1]
)}/`}
/>
)} */}
</div>
)}
<div>
<SearchBarContainer className="space-x-2">
<SearchBar
className="flex-1 w-full"
ref={searchInputRef}
placeholder="Search past sessions"
type="text"
onChange={(e) => setSearchTerm(e.target.value)}
/>
<span
className="block text-center px-2 py-1.5 rounded-md w-12 mx-1 my-2 select-none cursor-pointer"
style={{
fontSize: "11px",
backgroundColor:
searchTerm !== "" ? vscInputBackground : vscBadgeBackground,
}}
onClick={() => {
if (searchInputRef.current.value === "") {
searchInputRef.current.value = "*";
setSearchTerm("*");
} else {
searchInputRef.current.value = "";
setSearchTerm("");
}
}}
>
{searchTerm === "" ? "Show All" : "Clear"}
</span>
</SearchBarContainer>
{filteredAndSortedSessions.length === 0 && (
<div className="text-center m-4">
No past sessions found. To start a new session, either click the "+"
button or use the keyboard shortcut: <b>Option + Command + N</b>
</div>
)}
<table className="w-full border-spacing-0 border-collapse">
<tbody>
{filteredAndSortedSessions.map((session, index) => {
const prevDate =
index > 0
? parseDate(filteredAndSortedSessions[index - 1].dateCreated)
: earlier;
const date = parseDate(session.dateCreated);
return (
<Fragment key={index}>
{index === 0 && date > yesterday && (
<SectionHeader style={{ top: `${headerHeight - 1}px` }}>
Today
</SectionHeader>
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
<SectionHeader style={{ top: `${headerHeight - 1}px` }}>
This Week
</SectionHeader>
)}
{date < lastWeek &&
date > lastMonth &&
prevDate > lastWeek && (
<SectionHeader style={{ top: `${headerHeight - 1}px` }}>
This Month
</SectionHeader>
)}
{date < lastMonth && prevDate > lastMonth && (
<SectionHeader style={{ top: `${headerHeight - 1}px` }}>
Older
</SectionHeader>
<table className="w-full border-spacing-0 border-collapse">
<tbody>
{filteredAndSortedSessions.map((session, index) => {
const prevDate =
index > 0
? parseDate(filteredAndSortedSessions[index - 1].dateCreated)
: earlier;
const date = parseDate(session.dateCreated);
return (
<Fragment key={index}>
{index === 0 && date > yesterday && (
<SectionHeader>Today</SectionHeader>
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
<SectionHeader>This Week</SectionHeader>
)}
{date < lastWeek && date > lastMonth && prevDate > lastWeek && (
<SectionHeader>This Month</SectionHeader>
)}
{date < lastMonth && prevDate > lastMonth && (
<SectionHeader>Older</SectionHeader>
)}
<Tr key={index}>
<TableRow
session={session}
date={date}
onDelete={() => deleteSessionInUI(session.sessionId)}
></TableRow>
</Tr>
</Fragment>
);
})}
</tbody>
</table>
<br />
<i className="text-sm ml-4">
All session data is saved in ~/.continue/sessions
</i>
</div>
<Tr key={index}>
<TableRow
session={session}
date={date}
onDelete={() => deleteSessionInUI(session.sessionId)}
></TableRow>
</Tr>
</Fragment>
);
})}
</tbody>
</table>
<br />
<i className="text-sm ml-4">
All session data is saved in ~/.continue/sessions
</i>
</div>
);
}
export default History;

View file

@ -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 (
<LayoutTopDiv>
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
<LastSessionProvider>
<LayoutTopDiv>
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
/>
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
/>
<GridDiv>
<PostHogPageView />
<Outlet />
<ModelDropdownPortalDiv id="model-select-top-div"></ModelDropdownPortalDiv>
<ProfileDropdownPortalDiv id="profile-select-top-div"></ProfileDropdownPortalDiv>
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
</LayoutTopDiv>
<GridDiv>
<PostHogPageView />
<Outlet />
<ModelDropdownPortalDiv id="model-select-top-div"></ModelDropdownPortalDiv>
<ProfileDropdownPortalDiv id="profile-select-top-div"></ProfileDropdownPortalDiv>
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
</LayoutTopDiv>
</LastSessionProvider>
);
};

View file

@ -152,7 +152,7 @@ function InputToolbar(props: InputToolbarProps) {
}
>
<span data-tooltip-id="add-codebase-context-tooltip">
@codebase
{getMetaKeyLabel()}⏎ @codebase
</span>
<ToolTip id="add-codebase-context-tooltip" place="top-end">
Submit with the codebase as context ({getMetaKeyLabel()}⏎)

View file

@ -61,7 +61,7 @@ const StyledListboxButton = styled(Listbox.Button)`
}
`;
const StyledListboxOptions = styled(Listbox.Options)<{ showAbove: boolean }>`
const StyledListboxOptions = styled(Listbox.Options)<{ $showabove: boolean }>`
margin-top: 4px;
position: absolute;
list-style: none;
@ -81,7 +81,7 @@ const StyledListboxOptions = styled(Listbox.Options)<{ showAbove: boolean }>`
scrollbar-width: none;
${(props) => (props.showAbove ? "bottom: 100%;" : "top: 100%;")}
${(props) => (props.$showabove ? "bottom: 100%;" : "top: 100%;")}
`;
const StyledListboxOption = styled(Listbox.Option)<{ isDisabled?: boolean }>`
@ -330,7 +330,7 @@ function ModelSelect() {
</div>
</StyledListboxButton>
<StyledListboxOptions
showAbove={showAbove}
$showabove={showAbove}
className="z-50 max-w-[90vw]"
>
<div className={`max-h-[${MAX_HEIGHT_PX}px]`}>

View file

@ -0,0 +1,23 @@
import React, { createContext, useState } 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<string | undefined>();
return (
<LastSessionContext.Provider value={{ lastSessionId, setLastSessionId }}>
{children}
</LastSessionContext.Provider>
);
};
export const useLastSessionContext = () => React.useContext(LastSessionContext);

View file

@ -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<PersistedSessionInfo> {
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,
};
}

View file

@ -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;

View file

@ -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 (
<div className="flex overflow-scroll">
<Aside className="overflow-y-auto w-96 hidden 4xl:block">
<History />
</Aside>
<main className="overflow-y-auto flex-1 flex flex-col">
<Chat />
</main>
</div>
);
}

View file

@ -0,0 +1,41 @@
import { useNavigate } from "react-router-dom";
import { lightGray, vscBackground } from "../../components";
import { useNavigationListener } from "../../hooks/useNavigationListener";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { getFontSize } from "../../util";
export const HistoryHeader = () => {
useNavigationListener();
const navigate = useNavigate();
return (
<div
className="sticky top-0"
style={{ backgroundColor: vscBackground, fontSize: getFontSize() }}
>
<div
className="items-center flex m-0 p-0"
style={{
borderBottom: `0.5px solid ${lightGray}`,
}}
>
<ArrowLeftIcon
width="1.2em"
height="1.2em"
onClick={() => navigate("/")}
className="inline-block ml-4 cursor-pointer"
/>
<h3 className="text-lg font-bold m-2 inline-block">History</h3>
</div>
{/* {workspacePaths && workspacePaths.length > 0 && (
<CheckDiv
checked={filteringByWorkspace}
onClick={() => setFilteringByWorkspace((prev) => !prev)}
title={`Show only sessions from ${lastPartOfPath(
workspacePaths[workspacePaths.length - 1]
)}/`}
/>
)} */}
</div>
);
};

View file

@ -0,0 +1,12 @@
import { History } from "../../components/History";
import { getFontSize } from "../../util";
import { HistoryHeader } from "./HistoryHeader";
export default function HistoryPage() {
return (
<div className="overflow-y-scroll" style={{ fontSize: getFontSize() }}>
<HistoryHeader />
<History />
</div>
);
}

View file

@ -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": "1180px",
},
extend: {
animation: {

6
manual-testing-sandbox/.idea/vcs.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>