From c4115e257b6da05dd0a568bbe7e3740356a11264 Mon Sep 17 00:00:00 2001 From: Carl-Robert Date: Thu, 16 Nov 2023 17:15:11 +0200 Subject: [PATCH] Add checkstyle rules (#274) --- .../codegpt.java-conventions.gradle.kts | 5 + .../embedding/EmbeddingsService.java | 24 +- .../ee/carlrobert/splitter/CodeSplitter.java | 4 +- .../ee/carlrobert/vector/VectorStore.java | 5 +- .../main/java/ee/carlrobert/vector/Word.java | 8 +- config/checkstyle/checkstyle.xml | 366 ++++++++++++++++++ config/checkstyle/suppressions.xml | 12 + .../ee/carlrobert/codegpt/CodeGPTBundle.java | 4 +- .../java/ee/carlrobert/codegpt/Icons.java | 3 +- .../codegpt/PluginStartupActivity.java | 22 +- .../actions/editor/CustomPromptAction.java | 12 +- .../actions/editor/EditorActionsUtil.java | 16 +- .../toolwindow/ClearChatWindowAction.java | 2 +- .../DeleteAllConversationsAction.java | 2 +- .../toolwindow/OpenInEditorAction.java | 2 +- .../ReplaceCodeInMainEditorAction.java | 8 +- .../completions/CompletionRequestHandler.java | 4 +- .../CompletionRequestProvider.java | 52 +-- .../codegpt/completions/llama/LlamaModel.java | 17 +- .../completions/llama/LlamaServerAgent.java | 7 +- .../completions/llama/PromptTemplate.java | 4 +- .../codegpt/completions/you/YouApiClient.java | 8 +- .../you/auth/AuthenticationNotifier.java | 3 +- .../you/auth/SignedOutNotifier.java | 3 +- .../completions/you/auth/YouAuthClient.java | 15 +- .../you/auth/YouAuthenticationError.java | 4 +- .../conversations/ConversationService.java | 6 +- .../conversations/ConversationsState.java | 4 +- .../credentials/AzureCredentialsManager.java | 11 +- .../credentials/OpenAICredentialsManager.java | 3 +- .../credentials/YouCredentialsManager.java | 3 +- .../codegpt/indexes/CodebaseIndexingTask.java | 12 +- .../indexes/FolderStructureTreePanel.java | 19 +- .../codegpt/settings/SettingsComponent.java | 4 +- .../settings/SettingsConfigurable.java | 47 ++- .../advanced/AdvancedSettingsComponent.java | 14 +- .../AdvancedSettingsConfigurable.java | 18 +- .../advanced/AdvancedSettingsState.java | 4 +- .../configuration/ConfigurationComponent.java | 35 +- .../ConfigurationConfigurable.java | 17 +- .../configuration/ConfigurationState.java | 4 +- .../settings/service/DownloadModelAction.java | 16 +- .../service/LlamaModelPreferencesForm.java | 118 +++--- .../service/LlamaServiceSelectionForm.java | 132 ++++--- .../service/ServiceSelectionForm.java | 16 +- .../service/YouServiceSelectionForm.java | 9 +- .../settings/state/AzureSettingsState.java | 31 +- .../settings/state/OpenAISettingsState.java | 13 +- .../toolwindow/ProjectToolWindowFactory.java | 3 +- .../chat/BaseChatToolWindowTabPanel.java | 5 +- .../chat/ChatToolWindowScrollablePanel.java | 4 +- .../codegpt/toolwindow/chat/StreamParser.java | 6 +- .../components/ChatMessageResponseBody.java | 8 +- .../chat/components/SmartScroller.java | 56 +-- .../components/UserPromptTextAreaHeader.java | 1 + .../chat/components/YouProCheckbox.java | 6 +- .../ContextualChatToolWindowLandingPanel.java | 68 ++-- .../chat/contextual/EditorActionEvent.java | 7 + .../chat/editor/ResponseEditor.java | 8 +- .../chat/editor/actions/DiffAction.java | 2 +- .../chat/editor/actions/EditAction.java | 6 +- .../chat/standard/EditorAction.java | 25 +- .../StandardChatToolWindowLandingPanel.java | 42 +- .../StandardChatToolWindowTabPanel.java | 4 +- .../conversations/ConversationPanel.java | 6 +- .../codegpt/util/MarkdownUtils.java | 9 +- .../carlrobert/codegpt/util/OverlayUtils.java | 21 +- .../CompletionRequestProviderTest.java | 50 +-- .../DefaultCompletionRequestHandlerTest.java | 50 +-- .../completions/PromptTemplateTest.java | 6 +- .../settings/state/SettingsStateTest.java | 6 +- .../codegpt/util/MarkdownUtilsTest.java | 146 +++---- 72 files changed, 1129 insertions(+), 564 deletions(-) create mode 100644 config/checkstyle/checkstyle.xml create mode 100644 config/checkstyle/suppressions.xml create mode 100644 src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/EditorActionEvent.java diff --git a/buildSrc/src/main/kotlin/codegpt.java-conventions.gradle.kts b/buildSrc/src/main/kotlin/codegpt.java-conventions.gradle.kts index cd0083c4..d2142221 100644 --- a/buildSrc/src/main/kotlin/codegpt.java-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/codegpt.java-conventions.gradle.kts @@ -1,6 +1,7 @@ fun properties(key: String) = project.findProperty(key).toString() plugins { + checkstyle id("java") id("idea") id("org.jetbrains.intellij") @@ -17,6 +18,10 @@ intellij { version.set(properties("platformVersion")) } +checkstyle { + toolVersion = "10.12.5" +} + dependencies { implementation("ee.carlrobert:llm-client:0.0.10") } diff --git a/codegpt-core/src/main/java/ee/carlrobert/embedding/EmbeddingsService.java b/codegpt-core/src/main/java/ee/carlrobert/embedding/EmbeddingsService.java index 4b4c8c4a..9ec32c52 100644 --- a/codegpt-core/src/main/java/ee/carlrobert/embedding/EmbeddingsService.java +++ b/codegpt-core/src/main/java/ee/carlrobert/embedding/EmbeddingsService.java @@ -40,7 +40,7 @@ public class EmbeddingsService { public List getEmbeddings(List chunks) { return openAIClient.getEmbeddings(chunks); } - + public String buildPromptWithContext(String prompt) { try { var inputEmbedding = openAIClient.getEmbedding(getSearchQuery(prompt)); @@ -63,7 +63,9 @@ public class EmbeddingsService { } } - public List> createEmbeddings(List checkedFiles, @Nullable ProgressIndicator indicator) { + public List> createEmbeddings( + List checkedFiles, + @Nullable ProgressIndicator indicator) { var words = new ArrayList>(); for (int i = 0; i < checkedFiles.size(); i++) { try { @@ -81,7 +83,10 @@ public class EmbeddingsService { } private String getSearchQuery(String userPrompt) throws JsonProcessingException { - var message = new OpenAIChatCompletionMessage("user", getResourceContent("/prompts/text-generator.txt").replace("{prompt}", userPrompt)); + var message = new OpenAIChatCompletionMessage( + "user", + getResourceContent("/prompts/text-generator.txt") + .replace("{prompt}", userPrompt)); var request = new OpenAIChatCompletionRequest.Builder(List.of(message)) .setModel(OpenAIChatCompletionModel.GPT_4) .setMaxTokens(400) @@ -100,16 +105,20 @@ public class EmbeddingsService { var fileExtension = checkedFile.getFileExtension(); var codeSplitter = SplitterFactory.getCodeSplitter(fileExtension); if (codeSplitter != null) { - var chunks = codeSplitter.split(checkedFile.getFileName(), checkedFile.getFileContent()); + var chunks = codeSplitter.split( + checkedFile.getFileName(), + checkedFile.getFileContent()); var embeddings = openAIClient.getEmbeddings(chunks); for (int i = 0; i < chunks.size(); i++) { - prevEmbeddings.add(new Word(chunks.get(i), checkedFile.getFileName(), normalize(embeddings.get(i)))); + prevEmbeddings.add( + new Word(chunks.get(i), checkedFile.getFileName(), normalize(embeddings.get(i)))); } } else { var chunks = splitText(checkedFile.getFileContent(), 400); var embeddings = getEmbeddings(chunks); for (int i = 0; i < chunks.size(); i++) { - prevEmbeddings.add(new Word(chunks.get(i), checkedFile.getFileName(), normalize(embeddings.get(i)))); + prevEmbeddings.add( + new Word(chunks.get(i), checkedFile.getFileName(), normalize(embeddings.get(i)))); } } } @@ -125,7 +134,8 @@ public class EmbeddingsService { // TODO: Move to shared module private static String getResourceContent(String name) { - try (var stream = Objects.requireNonNull(EmbeddingsService.class.getResourceAsStream(name))) { + try (var stream = + Objects.requireNonNull(EmbeddingsService.class.getResourceAsStream(name))) { return new String(stream.readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException("Unable to read resource", e); diff --git a/codegpt-core/src/main/java/ee/carlrobert/splitter/CodeSplitter.java b/codegpt-core/src/main/java/ee/carlrobert/splitter/CodeSplitter.java index 3837346d..b018548a 100644 --- a/codegpt-core/src/main/java/ee/carlrobert/splitter/CodeSplitter.java +++ b/codegpt-core/src/main/java/ee/carlrobert/splitter/CodeSplitter.java @@ -26,7 +26,9 @@ abstract class CodeSplitter implements Splitter { @Override public List split(String fileName, String content) { chunks = new ArrayList<>(); - ParseTreeWalker.DEFAULT.walk(getParseTreeListener(), getParseTree(CharStreams.fromString(content))); + ParseTreeWalker.DEFAULT.walk( + getParseTreeListener(), + getParseTree(CharStreams.fromString(content))); return chunks; } } diff --git a/codegpt-core/src/main/java/ee/carlrobert/vector/VectorStore.java b/codegpt-core/src/main/java/ee/carlrobert/vector/VectorStore.java index c4b97aeb..15f3c046 100644 --- a/codegpt-core/src/main/java/ee/carlrobert/vector/VectorStore.java +++ b/codegpt-core/src/main/java/ee/carlrobert/vector/VectorStore.java @@ -37,7 +37,10 @@ public class VectorStore { public void save(List> words) { var hnswIndex = HnswIndex - .newBuilder(words.get(0).vector().length, DistanceFunctions.DOUBLE_COSINE_DISTANCE, words.size()) + .newBuilder( + words.get(0).vector().length, + DistanceFunctions.DOUBLE_COSINE_DISTANCE, + words.size()) .build(); try { hnswIndex.addAll(words); diff --git a/codegpt-core/src/main/java/ee/carlrobert/vector/Word.java b/codegpt-core/src/main/java/ee/carlrobert/vector/Word.java index c972fcef..d27ca20d 100644 --- a/codegpt-core/src/main/java/ee/carlrobert/vector/Word.java +++ b/codegpt-core/src/main/java/ee/carlrobert/vector/Word.java @@ -34,10 +34,10 @@ public class Word implements Item { @Override public String toString() { - return "Word{" + - "id='" + id + '\'' + - ", vector=" + Arrays.toString(vector) + - '}'; + return "Word{" + + "id='" + id + '\'' + + ", vector=" + Arrays.toString(vector) + + '}'; } public String getMeta() { diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 00000000..4d719b6c --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,366 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 00000000..811e51c3 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/java/ee/carlrobert/codegpt/CodeGPTBundle.java b/src/main/java/ee/carlrobert/codegpt/CodeGPTBundle.java index 896c3cfb..54307025 100644 --- a/src/main/java/ee/carlrobert/codegpt/CodeGPTBundle.java +++ b/src/main/java/ee/carlrobert/codegpt/CodeGPTBundle.java @@ -16,7 +16,9 @@ public class CodeGPTBundle extends DynamicBundle { return INSTANCE.getMessage(key); } - public static String get(@NotNull @PropertyKey(resourceBundle = "messages.codegpt") String key, Object... params) { + public static String get( + @NotNull @PropertyKey(resourceBundle = "messages.codegpt") String key, + Object... params) { return INSTANCE.getMessage(key, params); } } diff --git a/src/main/java/ee/carlrobert/codegpt/Icons.java b/src/main/java/ee/carlrobert/codegpt/Icons.java index 6f8e2188..238018c3 100644 --- a/src/main/java/ee/carlrobert/codegpt/Icons.java +++ b/src/main/java/ee/carlrobert/codegpt/Icons.java @@ -6,7 +6,8 @@ import javax.swing.Icon; public final class Icons { public static final Icon DefaultIcon = IconLoader.getIcon("/icons/codegpt.svg", Icons.class); - public static final Icon DefaultSmallIcon = IconLoader.getIcon("/icons/codegpt-small.svg", Icons.class); + public static final Icon DefaultSmallIcon = + IconLoader.getIcon("/icons/codegpt-small.svg", Icons.class); public static final Icon AzureIcon = IconLoader.getIcon("/icons/azure.svg", Icons.class); public static final Icon LlamaIcon = IconLoader.getIcon("/icons/llama.svg", Icons.class); public static final Icon OpenAIIcon = IconLoader.getIcon("/icons/openai.svg", Icons.class); diff --git a/src/main/java/ee/carlrobert/codegpt/PluginStartupActivity.java b/src/main/java/ee/carlrobert/codegpt/PluginStartupActivity.java index 5404c6c1..148727b4 100644 --- a/src/main/java/ee/carlrobert/codegpt/PluginStartupActivity.java +++ b/src/main/java/ee/carlrobert/codegpt/PluginStartupActivity.java @@ -8,13 +8,13 @@ import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.startup.StartupActivity; import ee.carlrobert.codegpt.actions.editor.EditorActionsUtil; import ee.carlrobert.codegpt.completions.you.YouUserManager; +import ee.carlrobert.codegpt.completions.you.auth.AuthenticationHandler; +import ee.carlrobert.codegpt.completions.you.auth.SessionVerificationJob; +import ee.carlrobert.codegpt.completions.you.auth.YouAuthenticationError; +import ee.carlrobert.codegpt.completions.you.auth.YouAuthenticationService; +import ee.carlrobert.codegpt.completions.you.auth.response.YouAuthenticationResponse; import ee.carlrobert.codegpt.credentials.YouCredentialsManager; import ee.carlrobert.codegpt.settings.state.SettingsState; -import ee.carlrobert.codegpt.completions.you.auth.YouAuthenticationError; -import ee.carlrobert.codegpt.completions.you.auth.AuthenticationHandler; -import ee.carlrobert.codegpt.completions.you.auth.YouAuthenticationService; -import ee.carlrobert.codegpt.completions.you.auth.SessionVerificationJob; -import ee.carlrobert.codegpt.completions.you.auth.response.YouAuthenticationResponse; import ee.carlrobert.codegpt.util.OverlayUtils; import org.jetbrains.annotations.NotNull; import org.quartz.JobBuilder; @@ -89,18 +89,24 @@ public class PluginStartupActivity implements StartupActivity { .signInAsync(settings.getEmail(), password, new AuthenticationHandler() { @Override public void handleAuthenticated(YouAuthenticationResponse authenticationResponse) { - OverlayUtils.showNotification("Authentication successful.", NotificationType.INFORMATION); + OverlayUtils.showNotification( + "Authentication successful.", + NotificationType.INFORMATION); startSessionVerificationJob(); } @Override public void handleGenericError() { - OverlayUtils.showNotification("Something went wrong while trying to authenticate.", NotificationType.ERROR); + OverlayUtils.showNotification( + "Something went wrong while trying to authenticate.", + NotificationType.ERROR); } @Override public void handleError(YouAuthenticationError youAuthenticationError) { - OverlayUtils.showNotification(youAuthenticationError.getErrorMessage(), NotificationType.ERROR); + OverlayUtils.showNotification( + youAuthenticationError.getErrorMessage(), + NotificationType.ERROR); } }); } diff --git a/src/main/java/ee/carlrobert/codegpt/actions/editor/CustomPromptAction.java b/src/main/java/ee/carlrobert/codegpt/actions/editor/CustomPromptAction.java index e9f19a1b..9c0fe624 100644 --- a/src/main/java/ee/carlrobert/codegpt/actions/editor/CustomPromptAction.java +++ b/src/main/java/ee/carlrobert/codegpt/actions/editor/CustomPromptAction.java @@ -12,8 +12,8 @@ import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UI; import ee.carlrobert.codegpt.conversations.message.Message; import ee.carlrobert.codegpt.toolwindow.chat.standard.StandardChatToolWindowContentManager; -import ee.carlrobert.codegpt.util.file.FileUtils; import ee.carlrobert.codegpt.util.SwingUtils; +import ee.carlrobert.codegpt.util.file.FileUtils; import javax.swing.JComponent; import javax.swing.JTextArea; import javax.swing.SwingUtilities; @@ -31,18 +31,22 @@ class CustomPromptAction extends BaseEditorAction { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { if (selectedText != null && !selectedText.isEmpty()) { - var fileExtension = FileUtils.getFileExtension(((EditorImpl) editor).getVirtualFile().getName()); + var fileExtension = + FileUtils.getFileExtension(((EditorImpl) editor).getVirtualFile().getName()); var dialog = new CustomPromptDialog(previousUserPrompt); if (dialog.showAndGet()) { previousUserPrompt = dialog.getUserPrompt(); - var message = new Message(format("%s\n```%s\n%s\n```", previousUserPrompt, fileExtension, selectedText)); + var message = new Message( + format("%s\n```%s\n%s\n```", previousUserPrompt, fileExtension, selectedText)); message.setUserMessage(previousUserPrompt); - SwingUtilities.invokeLater(() -> project.getService(StandardChatToolWindowContentManager.class).sendMessage(message)); + SwingUtilities.invokeLater(() -> + project.getService(StandardChatToolWindowContentManager.class).sendMessage(message)); } } } private static class CustomPromptDialog extends DialogWrapper { + private final JTextArea userPromptTextArea; public CustomPromptDialog(String previousUserPrompt) { diff --git a/src/main/java/ee/carlrobert/codegpt/actions/editor/EditorActionsUtil.java b/src/main/java/ee/carlrobert/codegpt/actions/editor/EditorActionsUtil.java index a43fc7d4..366f60fc 100644 --- a/src/main/java/ee/carlrobert/codegpt/actions/editor/EditorActionsUtil.java +++ b/src/main/java/ee/carlrobert/codegpt/actions/editor/EditorActionsUtil.java @@ -21,7 +21,8 @@ import org.apache.commons.text.CaseUtils; public class EditorActionsUtil { public static Map DEFAULT_ACTIONS = new LinkedHashMap<>(Map.of( - "Find Bugs", "Find bugs and output code with bugs fixed in the following code: {{selectedCode}}", + "Find Bugs", "Find bugs and output code with bugs " + + "fixed in the following code: {{selectedCode}}", "Write Tests", "Write Tests for the selected code {{selectedCode}}", "Explain", "Explain the selected code {{selectedCode}}", "Refactor", "Refactor the selected code {{selectedCode}}", @@ -38,7 +39,8 @@ public class EditorActionsUtil { } public static void refreshActions() { - AnAction actionGroup = ActionManager.getInstance().getAction("action.editor.group.EditorActionGroup"); + AnAction actionGroup = + ActionManager.getInstance().getAction("action.editor.group.EditorActionGroup"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); @@ -53,10 +55,14 @@ public class EditorActionsUtil { var action = new BaseEditorAction(label, label) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { - var fileExtension = FileUtils.getFileExtension(((EditorImpl) editor).getVirtualFile().getName()); - var message = new Message(prompt.replace("{{selectedCode}}", format("\n```%s\n%s\n```", fileExtension, selectedText))); + var fileExtension = FileUtils.getFileExtension( + ((EditorImpl) editor).getVirtualFile().getName()); + var message = new Message(prompt.replace( + "{{selectedCode}}", + format("\n```%s\n%s\n```", fileExtension, selectedText))); message.setUserMessage(prompt.replace("{{selectedCode}}", "")); - var toolWindowContentManager = project.getService(StandardChatToolWindowContentManager.class); + var toolWindowContentManager = + project.getService(StandardChatToolWindowContentManager.class); var toolWindow = toolWindowContentManager.getToolWindow(); if (toolWindow != null) { toolWindow.show(); diff --git a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ClearChatWindowAction.java b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ClearChatWindowAction.java index e79cfdb4..62d835d9 100644 --- a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ClearChatWindowAction.java +++ b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ClearChatWindowAction.java @@ -5,8 +5,8 @@ import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import ee.carlrobert.codegpt.actions.ActionType; import ee.carlrobert.codegpt.actions.editor.EditorActionsUtil; -import ee.carlrobert.codegpt.telemetry.TelemetryAction; import ee.carlrobert.codegpt.conversations.ConversationsState; +import ee.carlrobert.codegpt.telemetry.TelemetryAction; import org.jetbrains.annotations.NotNull; public class ClearChatWindowAction extends AnAction { diff --git a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/DeleteAllConversationsAction.java b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/DeleteAllConversationsAction.java index 50625b95..b9b4b396 100644 --- a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/DeleteAllConversationsAction.java +++ b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/DeleteAllConversationsAction.java @@ -8,8 +8,8 @@ import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.ui.Messages; import ee.carlrobert.codegpt.actions.ActionType; import ee.carlrobert.codegpt.actions.editor.EditorActionsUtil; -import ee.carlrobert.codegpt.telemetry.TelemetryAction; import ee.carlrobert.codegpt.conversations.ConversationService; +import ee.carlrobert.codegpt.telemetry.TelemetryAction; import ee.carlrobert.codegpt.toolwindow.chat.standard.StandardChatToolWindowContentManager; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/OpenInEditorAction.java b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/OpenInEditorAction.java index b46d2189..3dfb2e39 100644 --- a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/OpenInEditorAction.java +++ b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/OpenInEditorAction.java @@ -11,8 +11,8 @@ import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.testFramework.LightVirtualFile; import ee.carlrobert.codegpt.actions.ActionType; import ee.carlrobert.codegpt.actions.editor.EditorActionsUtil; -import ee.carlrobert.codegpt.telemetry.TelemetryAction; import ee.carlrobert.codegpt.conversations.ConversationsState; +import ee.carlrobert.codegpt.telemetry.TelemetryAction; import java.time.format.DateTimeFormatter; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ReplaceCodeInMainEditorAction.java b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ReplaceCodeInMainEditorAction.java index a96dcdbe..a253daef 100644 --- a/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ReplaceCodeInMainEditorAction.java +++ b/src/main/java/ee/carlrobert/codegpt/actions/toolwindow/ReplaceCodeInMainEditorAction.java @@ -20,8 +20,8 @@ public class ReplaceCodeInMainEditorAction extends AnAction { @Override public void update(@NotNull AnActionEvent event) { event.getPresentation().setEnabled( - EditorUtils.isMainEditorTextSelected(requireNonNull(event.getProject())) && - EditorUtils.hasSelection(event.getData(PlatformDataKeys.EDITOR))); + EditorUtils.isMainEditorTextSelected(requireNonNull(event.getProject())) + && EditorUtils.hasSelection(event.getData(PlatformDataKeys.EDITOR))); } @Override @@ -29,7 +29,9 @@ public class ReplaceCodeInMainEditorAction extends AnAction { var project = event.getProject(); var toolWindowEditor = event.getData(PlatformDataKeys.EDITOR); if (project != null && toolWindowEditor != null) { - EditorUtils.replaceMainEditorSelection(project, requireNonNull(toolWindowEditor.getSelectionModel().getSelectedText())); + EditorUtils.replaceMainEditorSelection( + project, + requireNonNull(toolWindowEditor.getSelectionModel().getSelectedText())); } } } diff --git a/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestHandler.java b/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestHandler.java index e3d173db..6d960d1b 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestHandler.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestHandler.java @@ -54,7 +54,9 @@ public class CompletionRequestHandler { } catch (Throwable ex) { var errorMessage = "Something went wrong"; if (ex instanceof TotalUsageExceededException) { - errorMessage = "The length of the context exceeds the maximum limit that the model can handle. Try reducing the input message or maximum completion token size."; + errorMessage = + "The length of the context exceeds the maximum limit that the model can handle. " + + "Try reducing the input message or maximum completion token size."; } completionResponseEventListener.handleError(new ErrorDetails(errorMessage), ex); throw ex; diff --git a/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestProvider.java b/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestProvider.java index a4aee70d..0042a101 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestProvider.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/CompletionRequestProvider.java @@ -35,27 +35,27 @@ public class CompletionRequestProvider { private static final Logger LOG = Logger.getInstance(CompletionRequestProvider.class); - public static final String COMPLETION_SYSTEM_PROMPT = "You are an AI programming assistant.\n" + - "Follow the user's requirements carefully & to the letter.\n" + - "Your responses should be informative and logical.\n" + - "You should always adhere to technical information.\n" + - "If the user asks for code or technical questions, you must provide code suggestions and " + - "adhere to technical information.\n" + - "If the question is related to a developer, you must respond with " + - "content related to a developer.\n" + - "First think step-by-step - describe your plan for what to build in pseudocode, " + - "written out in great detail.\n" + - "Then output the code in a single code block.\n" + - "Minimize any other prose.\n" + - "Keep your answers short and impersonal.\n" + - "Use Markdown formatting in your answers.\n" + - "Make sure to include the programming language name at the start of the " + - "Markdown code blocks.\n" + - "Avoid wrapping the whole response in triple backticks.\n" + - "The user works in an IDE built by JetBrains which has a concept for editors " + - "with open files, integrated unit test support, and output pane that shows " + - "the output of running the code as well as an integrated terminal.\n" + - "You can only give one reply for each conversation turn."; + public static final String COMPLETION_SYSTEM_PROMPT = "You are an AI programming assistant.\n" + + "Follow the user's requirements carefully & to the letter.\n" + + "Your responses should be informative and logical.\n" + + "You should always adhere to technical information.\n" + + "If the user asks for code or technical questions, you must provide code suggestions and " + + "adhere to technical information.\n" + + "If the question is related to a developer, you must respond with " + + "content related to a developer.\n" + + "First think step-by-step - describe your plan for what to build in pseudocode, " + + "written out in great detail.\n" + + "Then output the code in a single code block.\n" + + "Minimize any other prose.\n" + + "Keep your answers short and impersonal.\n" + + "Use Markdown formatting in your answers.\n" + + "Make sure to include the programming language name at the start of the " + + "Markdown code blocks.\n" + + "Avoid wrapping the whole response in triple backticks.\n" + + "The user works in an IDE built by JetBrains which has a concept for editors " + + "with open files, integrated unit test support, and output pane that shows " + + "the output of running the code as well as an integrated terminal.\n" + + "You can only give one reply for each conversation turn."; private final EncodingManager encodingManager = EncodingManager.getInstance(); private final EmbeddingsService embeddingsService; @@ -70,9 +70,9 @@ public class CompletionRequestProvider { public LlamaCompletionRequest buildLlamaCompletionRequest(Message message) { var settings = LlamaSettingsState.getInstance(); - var promptTemplate = settings.isUseCustomModel() ? - settings.getPromptTemplate() : - LlamaModel.findByHuggingFaceModel(settings.getHuggingFaceModel()).getPromptTemplate(); + var promptTemplate = settings.isUseCustomModel() + ? settings.getPromptTemplate() + : LlamaModel.findByHuggingFaceModel(settings.getHuggingFaceModel()).getPromptTemplate(); var prompt = promptTemplate.buildPrompt( COMPLETION_SYSTEM_PROMPT, message.getPrompt(), @@ -90,8 +90,8 @@ public class CompletionRequestProvider { prevMessage.getPrompt(), prevMessage.getResponse())) .collect(toList())); - if (TelemetryConfiguration.getInstance().isEnabled() && - !ApplicationManager.getApplication().isUnitTestMode()) { + if (TelemetryConfiguration.getInstance().isEnabled() + && !ApplicationManager.getApplication().isUnitTestMode()) { requestBuilder.setUserId(UUID.fromString(UserId.INSTANCE.get())); } return requestBuilder.build(); diff --git a/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaModel.java b/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaModel.java index 323749fc..8cbacc6f 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaModel.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaModel.java @@ -12,7 +12,10 @@ import org.jetbrains.annotations.NotNull; public enum LlamaModel { CODE_LLAMA( "Code Llama", - "Code Llama is a family of large language models for code based on Llama 2 providing state-of-the-art performance among open models, infilling capabilities, support for large input contexts, and zero-shot instruction following ability for programming tasks.", + "Code Llama is a family of large language models for code based on Llama 2 " + + "providing state-of-the-art performance among open models, infilling capabilities, " + + "support for large input contexts, and zero-shot instruction following ability for " + + "programming tasks.", PromptTemplate.LLAMA, List.of( HuggingFaceModel.CODE_LLAMA_7B_Q3, @@ -27,7 +30,9 @@ public enum LlamaModel { ), CODE_BOOGA( "CodeBooga", - "CodeBooga is a high-performing code instruct model created by merging two existing code models:
  1. Phind-CodeLlama-34B-v2
  2. WizardCoder-Python-34B-V1.0
", + "CodeBooga is a high-performing code instruct model created by merging two existing" + + " code models: " + + "
  1. Phind-CodeLlama-34B-v2
  2. WizardCoder-Python-34B-V1.0
", PromptTemplate.ALPACA, List.of( HuggingFaceModel.CODE_BOOGA_34B_Q3, @@ -35,7 +40,9 @@ public enum LlamaModel { HuggingFaceModel.CODE_BOOGA_34B_Q5)), PHIND_CODE_LLAMA( "Phind Code Llama", - "This model is fine-tuned from Phind-CodeLlama-34B-v1 on an additional 1.5B tokens high-quality programming-related data, achieving 73.8% pass@1 on HumanEval. It's the current state-of-the-art amongst open-source models.", + "This model is fine-tuned from Phind-CodeLlama-34B-v1 on an additional 1.5B tokens " + + "high-quality programming-related data, achieving 73.8% pass@1 on HumanEval. " + + "It's the current state-of-the-art amongst open-source models.", PromptTemplate.ALPACA, List.of( HuggingFaceModel.PHIND_CODE_LLAMA_34B_Q3, @@ -43,7 +50,9 @@ public enum LlamaModel { HuggingFaceModel.PHIND_CODE_LLAMA_34B_Q5)), WIZARD_CODER_PYTHON( "WizardCoder - Python", - "WizardCoder, a Code Evol-Instruct fine-tuned Code LLM, which achieves the 73.2 pass@1 and surpasses GPT4 (2023/03/15), ChatGPT-3.5, and Claude2 on the HumanEval Benchmarks.", + "WizardCoder, a Code Evol-Instruct fine-tuned Code LLM, which achieves " + + "the 73.2 pass@1 and surpasses GPT4 (2023/03/15), ChatGPT-3.5, " + + "and Claude2 on the HumanEval Benchmarks.", PromptTemplate.ALPACA, List.of( HuggingFaceModel.WIZARD_CODER_PYTHON_7B_Q3, diff --git a/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaServerAgent.java b/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaServerAgent.java index 03e1561d..bc959a8a 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaServerAgent.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/llama/LlamaServerAgent.java @@ -57,9 +57,9 @@ public final class LlamaServerAgent implements Disposable { } public boolean isServerRunning() { - return startServerProcessHandler != null && - startServerProcessHandler.isStartNotified() && - !startServerProcessHandler.isProcessTerminated(); + return startServerProcessHandler != null + && startServerProcessHandler.isStartNotified() + && !startServerProcessHandler.isProcessTerminated(); } private ProcessListener getMakeProcessListener( @@ -117,6 +117,7 @@ public final class LlamaServerAgent implements Disposable { onSuccess.run(); } } catch (Exception ignore) { + // ignore } } } diff --git a/src/main/java/ee/carlrobert/codegpt/completions/llama/PromptTemplate.java b/src/main/java/ee/carlrobert/codegpt/completions/llama/PromptTemplate.java index 74e71b22..af6e6a9d 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/llama/PromptTemplate.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/llama/PromptTemplate.java @@ -78,8 +78,8 @@ public enum PromptTemplate { public String buildPrompt(String systemPrompt, String userPrompt, List history) { StringBuilder prompt = new StringBuilder(); - prompt.append( - "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"); + prompt.append("Below is an instruction that describes a task. " + + "Write a response that appropriately completes the request.\n\n"); for (Message message : history) { prompt.append("### Instruction\n") diff --git a/src/main/java/ee/carlrobert/codegpt/completions/you/YouApiClient.java b/src/main/java/ee/carlrobert/codegpt/completions/you/YouApiClient.java index 6e6b2379..18bd60ee 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/you/YouApiClient.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/you/YouApiClient.java @@ -30,10 +30,10 @@ public final class YouApiClient { .header("Cache-Control", "no-cache") .header("User-Agent", "youide CodeGPT") .header("Cookie", ( - "stytch_session=" + sessionId + "; " + - "ydc_stytch_session=" + sessionId + "; " + - "stytch_session_jwt=" + sessionJwt + "; " + - "ydc_stytch_session_jwt=" + sessionJwt + "; ")) + "stytch_session=" + sessionId + "; " + + "ydc_stytch_session=" + sessionId + "; " + + "stytch_session_jwt=" + sessionJwt + "; " + + "ydc_stytch_session_jwt=" + sessionJwt + "; ")) .get() .build(); diff --git a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/AuthenticationNotifier.java b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/AuthenticationNotifier.java index 253eb275..99060b5a 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/AuthenticationNotifier.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/AuthenticationNotifier.java @@ -4,7 +4,8 @@ import com.intellij.util.messages.Topic; public interface AuthenticationNotifier { - Topic AUTHENTICATION_TOPIC = Topic.create("authenticationTopic", AuthenticationNotifier.class); + Topic AUTHENTICATION_TOPIC = + Topic.create("authenticationTopic", AuthenticationNotifier.class); void authenticationSuccessful(); } diff --git a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/SignedOutNotifier.java b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/SignedOutNotifier.java index 1c3ffca7..682404c6 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/SignedOutNotifier.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/SignedOutNotifier.java @@ -4,7 +4,8 @@ import com.intellij.util.messages.Topic; public interface SignedOutNotifier { - Topic SIGNED_OUT_TOPIC = Topic.create("signedOutTopic", SignedOutNotifier.class); + Topic SIGNED_OUT_TOPIC = + Topic.create("signedOutTopic", SignedOutNotifier.class); void signedOut(); } \ No newline at end of file diff --git a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthClient.java b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthClient.java index b4ddcab4..b51974f8 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthClient.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthClient.java @@ -17,7 +17,15 @@ import okhttp3.RequestBody; public final class YouAuthClient { private static final String API_BASE_URL = "https://web.stytch.com/sdk"; - private static final String publicToken = "public-token-live-507a52ad-7e69-496b-aee0-1c9863c7c819"; + private static final String PUBLIC_TOKEN = + "public-token-live-507a52ad-7e69-496b-aee0-1c9863c7c819"; + private static final String SDK_CLIENT_JWT = "eyJldmVudF9pZCI6ImV2ZW50LWlkLWY5YmU4YWU5LWE3Mjct" + + "NGFlYy1hNzY0LTk4NDg1NDFkZjcwYSIsImFwcF9zZXNzaW9uX2lkIjoiYXBwLXNlc3Npb24taWQtYjY1NzcwZjM" + + "tMWFkMy00YjlhLWFjYzctMzJjNWQyMGMxNGU0IiwicGVyc2lzdGVudF9pZCI6InBlcnNpc3RlbnQtaWQtYzY0M2" + + "M0YTMtZDg5MC00ZGJkLTk3YjQtMjY0MmFlODdkMTZhIiwiY2xpZW50X3NlbnRfYXQiOiIyMDIzLTA5LTAxVDIyO" + + "jMwOjU1LjIzNFoiLCJ0aW1lem9uZSI6IkV1cm9wZS9UYWxsaW5uIiwiYXBwIjp7ImlkZW50aWZpZXIiOiJ5b3Uu" + + "Y29tIn0sInNkayI6eyJpZGVudGlmaWVyIjoiU3R5dGNoLmpzIEphdmFzY3JpcHQgU0RLIC0gWU9VLkNPTSBERUJ" + + "VRyBCVUlMRCIsInZlcnNpb24iOiI0LjAuMCJ9fQ=="; public static YouAuthClient getInstance() { return ApplicationManager.getApplication().getService(YouAuthClient.class); @@ -31,8 +39,9 @@ public final class YouAuthClient { .headers(Headers.of( "content-type", "application/json", "authority", "web.stytch.com", - "authorization", "Basic " + Base64.getEncoder().encodeToString((publicToken + ":" + publicToken).getBytes()), - "x-sdk-client", "eyJldmVudF9pZCI6ImV2ZW50LWlkLWY5YmU4YWU5LWE3MjctNGFlYy1hNzY0LTk4NDg1NDFkZjcwYSIsImFwcF9zZXNzaW9uX2lkIjoiYXBwLXNlc3Npb24taWQtYjY1NzcwZjMtMWFkMy00YjlhLWFjYzctMzJjNWQyMGMxNGU0IiwicGVyc2lzdGVudF9pZCI6InBlcnNpc3RlbnQtaWQtYzY0M2M0YTMtZDg5MC00ZGJkLTk3YjQtMjY0MmFlODdkMTZhIiwiY2xpZW50X3NlbnRfYXQiOiIyMDIzLTA5LTAxVDIyOjMwOjU1LjIzNFoiLCJ0aW1lem9uZSI6IkV1cm9wZS9UYWxsaW5uIiwiYXBwIjp7ImlkZW50aWZpZXIiOiJ5b3UuY29tIn0sInNkayI6eyJpZGVudGlmaWVyIjoiU3R5dGNoLmpzIEphdmFzY3JpcHQgU0RLIC0gWU9VLkNPTSBERUJVRyBCVUlMRCIsInZlcnNpb24iOiI0LjAuMCJ9fQ==", + "authorization", "Basic " + Base64.getEncoder().encodeToString( + (PUBLIC_TOKEN + ":" + PUBLIC_TOKEN).getBytes()), + "x-sdk-client", SDK_CLIENT_JWT, "x-sdk-parent-host", "https://you.com" )) .post(RequestBody.create(new ObjectMapper() diff --git a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthenticationError.java b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthenticationError.java index ff07b5b3..476c3e7b 100644 --- a/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthenticationError.java +++ b/src/main/java/ee/carlrobert/codegpt/completions/you/auth/YouAuthenticationError.java @@ -9,7 +9,9 @@ public class YouAuthenticationError { private final String errorType; private final String errorMessage; - public YouAuthenticationError(@JsonProperty("error_type") String errorType, @JsonProperty("error_message") String errorMessage) { + public YouAuthenticationError( + @JsonProperty("error_type") String errorType, + @JsonProperty("error_message") String errorMessage) { this.errorType = errorType; this.errorMessage = errorMessage; } diff --git a/src/main/java/ee/carlrobert/codegpt/conversations/ConversationService.java b/src/main/java/ee/carlrobert/codegpt/conversations/ConversationService.java index e1d77bb9..2d88c336 100644 --- a/src/main/java/ee/carlrobert/codegpt/conversations/ConversationService.java +++ b/src/main/java/ee/carlrobert/codegpt/conversations/ConversationService.java @@ -196,9 +196,9 @@ public final class ConversationService { return "YouCode"; case LLAMA_CPP: var llamaSettings = LlamaSettingsState.getInstance(); - return llamaSettings.isUseCustomModel() ? - llamaSettings.getCustomLlamaModelPath() : - llamaSettings.getHuggingFaceModel().getCode(); + return llamaSettings.isUseCustomModel() + ? llamaSettings.getCustomLlamaModelPath() + : llamaSettings.getHuggingFaceModel().getCode(); default: throw new RuntimeException("Could not find corresponding service mapping"); } diff --git a/src/main/java/ee/carlrobert/codegpt/conversations/ConversationsState.java b/src/main/java/ee/carlrobert/codegpt/conversations/ConversationsState.java index 0fb9d902..63b130b2 100644 --- a/src/main/java/ee/carlrobert/codegpt/conversations/ConversationsState.java +++ b/src/main/java/ee/carlrobert/codegpt/conversations/ConversationsState.java @@ -13,7 +13,9 @@ import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -@State(name = "ee.carlrobert.codegpt.state.conversations.ConversationsState", storages = @Storage("ChatGPTConversations_170.xml")) +@State( + name = "ee.carlrobert.codegpt.state.conversations.ConversationsState", + storages = @Storage("ChatGPTConversations_170.xml")) public class ConversationsState implements PersistentStateComponent { @OptionTag(converter = ConversationsConverter.class) diff --git a/src/main/java/ee/carlrobert/codegpt/credentials/AzureCredentialsManager.java b/src/main/java/ee/carlrobert/codegpt/credentials/AzureCredentialsManager.java index 883de476..bbee6592 100644 --- a/src/main/java/ee/carlrobert/codegpt/credentials/AzureCredentialsManager.java +++ b/src/main/java/ee/carlrobert/codegpt/credentials/AzureCredentialsManager.java @@ -19,7 +19,8 @@ public final class AzureCredentialsManager { private AzureCredentialsManager() { azureOpenAIApiKey = CredentialsUtil.getPassword(azureOpenAIApiKeyCredentialAttributes); - azureActiveDirectoryToken = CredentialsUtil.getPassword(azureActiveDirectoryTokenCredentialAttributes); + azureActiveDirectoryToken = + CredentialsUtil.getPassword(azureActiveDirectoryTokenCredentialAttributes); } public static AzureCredentialsManager getInstance() { @@ -27,7 +28,9 @@ public final class AzureCredentialsManager { } public String getSecret() { - return AzureSettingsState.getInstance().isUseAzureActiveDirectoryAuthentication() ? azureActiveDirectoryToken : azureOpenAIApiKey; + return AzureSettingsState.getInstance().isUseAzureActiveDirectoryAuthentication() + ? azureActiveDirectoryToken + : azureOpenAIApiKey; } public @Nullable String getAzureOpenAIApiKey() { @@ -45,7 +48,9 @@ public final class AzureCredentialsManager { public void setAzureActiveDirectoryToken(String azureActiveDirectoryToken) { this.azureActiveDirectoryToken = azureActiveDirectoryToken; - CredentialsUtil.setPassword(azureActiveDirectoryTokenCredentialAttributes, azureActiveDirectoryToken); + CredentialsUtil.setPassword( + azureActiveDirectoryTokenCredentialAttributes, + azureActiveDirectoryToken); } public boolean isCredentialSet() { diff --git a/src/main/java/ee/carlrobert/codegpt/credentials/OpenAICredentialsManager.java b/src/main/java/ee/carlrobert/codegpt/credentials/OpenAICredentialsManager.java index 71c4b362..f1b13ad4 100644 --- a/src/main/java/ee/carlrobert/codegpt/credentials/OpenAICredentialsManager.java +++ b/src/main/java/ee/carlrobert/codegpt/credentials/OpenAICredentialsManager.java @@ -8,7 +8,8 @@ import org.jetbrains.annotations.Nullable; @Service public final class OpenAICredentialsManager { - private static final CredentialAttributes openAIApiKeyCredentialAttributes = CredentialsUtil.createCredentialAttributes("OPENAI_API_KEY"); + private static final CredentialAttributes openAIApiKeyCredentialAttributes = + CredentialsUtil.createCredentialAttributes("OPENAI_API_KEY"); private String openAIApiKey; diff --git a/src/main/java/ee/carlrobert/codegpt/credentials/YouCredentialsManager.java b/src/main/java/ee/carlrobert/codegpt/credentials/YouCredentialsManager.java index b94970bc..cc3d9a5c 100644 --- a/src/main/java/ee/carlrobert/codegpt/credentials/YouCredentialsManager.java +++ b/src/main/java/ee/carlrobert/codegpt/credentials/YouCredentialsManager.java @@ -8,7 +8,8 @@ import org.jetbrains.annotations.Nullable; @Service public final class YouCredentialsManager { - private static final CredentialAttributes accountPasswordCredentialAttributes = CredentialsUtil.createCredentialAttributes("ACCOUNT_PASSWORD"); + private static final CredentialAttributes accountPasswordCredentialAttributes = + CredentialsUtil.createCredentialAttributes("ACCOUNT_PASSWORD"); private String accountPassword; diff --git a/src/main/java/ee/carlrobert/codegpt/indexes/CodebaseIndexingTask.java b/src/main/java/ee/carlrobert/codegpt/indexes/CodebaseIndexingTask.java index b520a0e7..d9d26faa 100644 --- a/src/main/java/ee/carlrobert/codegpt/indexes/CodebaseIndexingTask.java +++ b/src/main/java/ee/carlrobert/codegpt/indexes/CodebaseIndexingTask.java @@ -14,8 +14,8 @@ import com.intellij.openapi.util.io.FileUtil; import ee.carlrobert.codegpt.CodeGPTBundle; import ee.carlrobert.codegpt.CodeGPTPlugin; import ee.carlrobert.codegpt.completions.CompletionClientProvider; -import ee.carlrobert.codegpt.util.file.FileUtils; import ee.carlrobert.codegpt.util.OverlayUtils; +import ee.carlrobert.codegpt.util.file.FileUtils; import ee.carlrobert.embedding.CheckedFile; import ee.carlrobert.embedding.EmbeddingsService; import ee.carlrobert.vector.VectorStore; @@ -34,7 +34,9 @@ public class CodebaseIndexingTask extends Task.Backgroundable { super(project, CodeGPTBundle.get("codebaseIndexing.task.title"), true); this.project = project; this.checkedFiles = checkedFiles; - this.embeddingsService = new EmbeddingsService(CompletionClientProvider.getOpenAIClient(), CodeGPTPlugin.getPluginBasePath()); + this.embeddingsService = new EmbeddingsService( + CompletionClientProvider.getOpenAIClient(), + CodeGPTPlugin.getPluginBasePath()); } public void run() { @@ -56,11 +58,13 @@ public class CodebaseIndexingTask extends Task.Backgroundable { if (!FileUtil.exists(CodeGPTPlugin.getIndexStorePath())) { FileUtils.tryCreateDirectory(CodeGPTPlugin.getIndexStorePath()); } - FileUtils.createFile(CodeGPTPlugin.getProjectIndexStorePath(project), "index.json", fileContent); + FileUtils.createFile( + CodeGPTPlugin.getProjectIndexStorePath(project), "index.json", fileContent); try { indicator.setFraction(0); - List> embeddings = embeddingsService.createEmbeddings(checkedFiles, indicator); + List> embeddings = + embeddingsService.createEmbeddings(checkedFiles, indicator); VectorStore.getInstance(CodeGPTPlugin.getPluginBasePath()).save(embeddings); OverlayUtils.showNotification("Indexing completed", NotificationType.INFORMATION); diff --git a/src/main/java/ee/carlrobert/codegpt/indexes/FolderStructureTreePanel.java b/src/main/java/ee/carlrobert/codegpt/indexes/FolderStructureTreePanel.java index 2147b563..3aee0962 100644 --- a/src/main/java/ee/carlrobert/codegpt/indexes/FolderStructureTreePanel.java +++ b/src/main/java/ee/carlrobert/codegpt/indexes/FolderStructureTreePanel.java @@ -86,6 +86,7 @@ public class FolderStructureTreePanel { totalSize -= length; } } catch (Throwable ignored) { + // ignore } } }); @@ -122,10 +123,11 @@ public class FolderStructureTreePanel { panel.add(new JBLabel("Total size:")); panel.add(loadingFilesSpinner); } else { - panel.add(new JBLabel("Total size: " + - FileUtils.convertFileSize(totalSize) + " ~ " + - (convertLongValue(totalSize / 4)) + " tokens " + " ~ " + - new DecimalFormat("#.##").format(((double) (totalSize / 4) / 1000) * 0.0001) + " $")); + panel.add(new JBLabel("Total size: " + + FileUtils.convertFileSize(totalSize) + " ~ " + + (convertLongValue(totalSize / 4)) + " tokens " + " ~ " + + new DecimalFormat("#.##") + .format(((double) (totalSize / 4) / 1000) * 0.0001) + " $")); } return panel; } @@ -149,16 +151,17 @@ public class FolderStructureTreePanel { try { if (node.isChecked()) { - node.setChecked(!changeListManager.isIgnoredFile(file) && - !ignoreManager.isPotentiallyIgnoredFile(file) && - FileUtils.isUtf8File(file.getPath()) && - fileSize < Math.pow(1024, 2)); + node.setChecked(!changeListManager.isIgnoredFile(file) + && !ignoreManager.isPotentiallyIgnoredFile(file) + && FileUtils.isUtf8File(file.getPath()) + && fileSize < Math.pow(1024, 2)); } if (node.isChecked()) { totalSize += fileSize; } } catch (RuntimeException ignored) { + // ignore } } diff --git a/src/main/java/ee/carlrobert/codegpt/settings/SettingsComponent.java b/src/main/java/ee/carlrobert/codegpt/settings/SettingsComponent.java index 3fa06753..a465aa47 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/SettingsComponent.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/SettingsComponent.java @@ -98,8 +98,8 @@ public class SettingsComponent { .withValidator(() -> { if (component instanceof ComboBox) { var selectedItem = ((ComboBox) component).getSelectedItem(); - if (selectedItem == ServiceType.OPENAI && - OpenAISettingsState.getInstance().isOpenAIQuotaExceeded()) { + if (selectedItem == ServiceType.OPENAI + && OpenAISettingsState.getInstance().isOpenAIQuotaExceeded()) { return new ValidationInfo( CodeGPTBundle.get("settings.openaiQuotaExceeded"), component); diff --git a/src/main/java/ee/carlrobert/codegpt/settings/SettingsConfigurable.java b/src/main/java/ee/carlrobert/codegpt/settings/SettingsConfigurable.java index c2118821..31a72b28 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/SettingsConfigurable.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/SettingsConfigurable.java @@ -54,31 +54,25 @@ public class SettingsConfigurable implements Configurable { var serviceSelectionForm = settingsComponent.getServiceSelectionForm(); var llamaModelPreferencesForm = serviceSelectionForm.getLlamaModelPreferencesForm(); - return !settingsComponent.getDisplayName().equals(settings.getDisplayName()) || - isServiceChanged(settings) || - openAISettings.isModified(serviceSelectionForm) || - azureSettings.isModified(serviceSelectionForm) || - serviceSelectionForm.isDisplayWebSearchResults() != - YouSettingsState.getInstance().isDisplayWebSearchResults() || + return !settingsComponent.getDisplayName().equals(settings.getDisplayName()) + || isServiceChanged(settings) + || openAISettings.isModified(serviceSelectionForm) + || azureSettings.isModified(serviceSelectionForm) + || serviceSelectionForm.isDisplayWebSearchResults() + != YouSettingsState.getInstance().isDisplayWebSearchResults() - llamaSettings.isUseCustomModel() != llamaModelPreferencesForm.isUseCustomLlamaModel() || - llamaSettings.getServerPort() != serviceSelectionForm.getLlamaServerPort() || - llamaSettings.getContextSize() != serviceSelectionForm.getContextSize() || - llamaSettings.getHuggingFaceModel() != llamaModelPreferencesForm.getSelectedModel() || - !llamaSettings.getPromptTemplate().equals(llamaModelPreferencesForm.getPromptTemplate()) || - !llamaSettings.getCustomLlamaModelPath() - .equals(llamaModelPreferencesForm.getCustomLlamaModelPath()); + || llamaSettings.isUseCustomModel() != llamaModelPreferencesForm.isUseCustomLlamaModel() + || llamaSettings.getServerPort() != serviceSelectionForm.getLlamaServerPort() + || llamaSettings.getContextSize() != serviceSelectionForm.getContextSize() + || llamaSettings.getHuggingFaceModel() != llamaModelPreferencesForm.getSelectedModel() + || !llamaSettings.getPromptTemplate().equals(llamaModelPreferencesForm.getPromptTemplate()) + || !llamaSettings.getCustomLlamaModelPath() + .equals(llamaModelPreferencesForm.getCustomLlamaModelPath()); } @Override public void apply() { var serviceSelectionForm = settingsComponent.getServiceSelectionForm(); - var settings = SettingsState.getInstance(); - var openAISettings = OpenAISettingsState.getInstance(); - var azureSettings = AzureSettingsState.getInstance(); - var llamaSettings = LlamaSettingsState.getInstance(); - var serviceChanged = isServiceChanged(settings); - var modelChanged = !openAISettings.getModel().equals(serviceSelectionForm.getOpenAIModel()); var prevKey = OpenAICredentialsManager.getInstance().getApiKey(); if (prevKey != null && !prevKey.equals(serviceSelectionForm.getOpenAIApiKey())) { @@ -90,10 +84,12 @@ public class SettingsConfigurable implements Configurable { AzureCredentialsManager.getInstance() .setAzureActiveDirectoryToken(serviceSelectionForm.getAzureActiveDirectoryToken()); + var settings = SettingsState.getInstance(); settings.setDisplayName(settingsComponent.getDisplayName()); settings.setSelectedService(settingsComponent.getSelectedService()); var llamaModelPreferencesForm = serviceSelectionForm.getLlamaModelPreferencesForm(); + var llamaSettings = LlamaSettingsState.getInstance(); llamaSettings.setCustomLlamaModelPath(llamaModelPreferencesForm.getCustomLlamaModelPath()); llamaSettings.setHuggingFaceModel(llamaModelPreferencesForm.getSelectedModel()); llamaSettings.setUseCustomModel(llamaModelPreferencesForm.isUseCustomLlamaModel()); @@ -101,11 +97,15 @@ public class SettingsConfigurable implements Configurable { llamaSettings.setServerPort(serviceSelectionForm.getLlamaServerPort()); llamaSettings.setContextSize(serviceSelectionForm.getContextSize()); + var azureSettings = AzureSettingsState.getInstance(); + var openAISettings = OpenAISettingsState.getInstance(); openAISettings.apply(serviceSelectionForm); azureSettings.apply(serviceSelectionForm); YouSettingsState.getInstance() .setDisplayWebSearchResults(serviceSelectionForm.isDisplayWebSearchResults()); + var serviceChanged = isServiceChanged(settings); + var modelChanged = !openAISettings.getModel().equals(serviceSelectionForm.getOpenAIModel()); if (serviceChanged || modelChanged) { resetActiveTab(); if (serviceChanged) { @@ -119,15 +119,13 @@ public class SettingsConfigurable implements Configurable { @Override public void reset() { var settings = SettingsState.getInstance(); - var openAISettings = OpenAISettingsState.getInstance(); - var azureSettings = AzureSettingsState.getInstance(); - var llamaSettings = LlamaSettingsState.getInstance(); var serviceSelectionForm = settingsComponent.getServiceSelectionForm(); // settingsComponent.setEmail(settings.getEmail()); settingsComponent.setDisplayName(settings.getDisplayName()); settingsComponent.setSelectedService(settings.getSelectedService()); + var llamaSettings = LlamaSettingsState.getInstance(); var llamaModelPreferencesForm = serviceSelectionForm.getLlamaModelPreferencesForm(); llamaModelPreferencesForm.setSelectedModel(llamaSettings.getHuggingFaceModel()); llamaModelPreferencesForm.setCustomLlamaModelPath(llamaSettings.getCustomLlamaModelPath()); @@ -135,8 +133,9 @@ public class SettingsConfigurable implements Configurable { llamaModelPreferencesForm.setPromptTemplate(llamaSettings.getPromptTemplate()); serviceSelectionForm.setLlamaServerPort(llamaSettings.getServerPort()); serviceSelectionForm.setContextSize(llamaSettings.getContextSize()); - openAISettings.reset(serviceSelectionForm); - azureSettings.reset(serviceSelectionForm); + + OpenAISettingsState.getInstance().reset(serviceSelectionForm); + AzureSettingsState.getInstance().reset(serviceSelectionForm); serviceSelectionForm.setDisplayWebSearchResults( YouSettingsState.getInstance().isDisplayWebSearchResults()); diff --git a/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsComponent.java b/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsComponent.java index 51d28fab..b876dde8 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsComponent.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsComponent.java @@ -30,7 +30,7 @@ public class AdvancedSettingsComponent { private final PortField readTimeoutField; public AdvancedSettingsComponent(AdvancedSettingsState advancedSettings) { - proxyTypeComboBox = new ComboBox<>(new Proxy.Type[] { + proxyTypeComboBox = new ComboBox<>(new Proxy.Type[]{ Proxy.Type.SOCKS, Proxy.Type.HTTP, Proxy.Type.DIRECT, @@ -57,7 +57,8 @@ public class AdvancedSettingsComponent { "advancedSettingsConfigurable.proxy.title"))) .addComponent(createProxySettingsForm()) .addVerticalGap(4) - .addComponent(new TitledSeparator(CodeGPTBundle.get("advancedSettingsConfigurable.connectionSettings.title"))) + .addComponent(new TitledSeparator( + CodeGPTBundle.get("advancedSettingsConfigurable.connectionSettings.title"))) .addComponent(createConnectionSettingsForm()) .addComponentFillVertically(new JPanel(), 0) .getPanel(); @@ -65,8 +66,13 @@ public class AdvancedSettingsComponent { private JPanel createConnectionSettingsForm() { var panel = FormBuilder.createFormBuilder() - .addLabeledComponent(CodeGPTBundle.get("advancedSettingsConfigurable.connectionSettings.connectionTimeout.label"), connectionTimeoutField) - .addLabeledComponent(CodeGPTBundle.get("advancedSettingsConfigurable.connectionSettings.readTimeout.label"), readTimeoutField) + .addLabeledComponent( + CodeGPTBundle.get( + "advancedSettingsConfigurable.connectionSettings.connectionTimeout.label"), + connectionTimeoutField) + .addLabeledComponent( + CodeGPTBundle.get("advancedSettingsConfigurable.connectionSettings.readTimeout.label"), + readTimeoutField) .getPanel(); panel.setBorder(JBUI.Borders.emptyLeft(16)); return panel; diff --git a/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsConfigurable.java b/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsConfigurable.java index fdba9680..7aae281c 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsConfigurable.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsConfigurable.java @@ -27,14 +27,16 @@ public class AdvancedSettingsConfigurable implements Configurable { @Override public boolean isModified() { var advancedSettings = AdvancedSettingsState.getInstance(); - return !advancedSettingsComponent.getProxyType().equals(advancedSettings.getProxyType()) || - !advancedSettingsComponent.getProxyHost().equals(advancedSettings.getProxyHost()) || - advancedSettingsComponent.getProxyPort() != advancedSettings.getProxyPort() || - advancedSettingsComponent.isProxyAuthSelected() != advancedSettings.isProxyAuthSelected() || - !advancedSettingsComponent.getProxyAuthUsername().equals(advancedSettings.getProxyUsername()) || - !advancedSettingsComponent.getProxyAuthPassword().equals(advancedSettings.getProxyPassword()) || - advancedSettingsComponent.getConnectionTimeout() != advancedSettings.getConnectTimeout() || - advancedSettingsComponent.getReadTimeout() != advancedSettings.getReadTimeout(); + return !advancedSettingsComponent.getProxyType().equals(advancedSettings.getProxyType()) + || !advancedSettingsComponent.getProxyHost().equals(advancedSettings.getProxyHost()) + || advancedSettingsComponent.getProxyPort() != advancedSettings.getProxyPort() + || advancedSettingsComponent.isProxyAuthSelected() != advancedSettings.isProxyAuthSelected() + || !advancedSettingsComponent.getProxyAuthUsername() + .equals(advancedSettings.getProxyUsername()) + || !advancedSettingsComponent.getProxyAuthPassword() + .equals(advancedSettings.getProxyPassword()) + || advancedSettingsComponent.getConnectionTimeout() != advancedSettings.getConnectTimeout() + || advancedSettingsComponent.getReadTimeout() != advancedSettings.getReadTimeout(); } @Override diff --git a/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsState.java b/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsState.java index 1d52ccd5..293f8057 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsState.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/advanced/AdvancedSettingsState.java @@ -9,7 +9,9 @@ import java.net.Proxy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -@State(name = "CodeGPT_AdvancedSettings_210", storages = @Storage("CodeGPT_AdvancedSettings_210.xml")) +@State( + name = "CodeGPT_AdvancedSettings_210", + storages = @Storage("CodeGPT_AdvancedSettings_210.xml")) public class AdvancedSettingsState implements PersistentStateComponent { private String proxyHost = ""; diff --git a/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationComponent.java b/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationComponent.java index f2d9da7f..349fd09a 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationComponent.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationComponent.java @@ -60,7 +60,8 @@ public class ConfigurationComponent { table.getColumnModel().getColumn(1).setPreferredWidth(240); table.getEmptyText().setText(CodeGPTBundle.get("configurationConfigurable.table.emptyText")); var tablePanel = createTablePanel(); - tablePanel.setBorder(BorderFactory.createTitledBorder(CodeGPTBundle.get("configurationConfigurable.table.title"))); + tablePanel.setBorder(BorderFactory.createTitledBorder( + CodeGPTBundle.get("configurationConfigurable.table.title"))); temperatureField = new JBTextField(12); temperatureField.setText(String.valueOf(configuration.getTemperature())); @@ -99,14 +100,16 @@ public class ConfigurationComponent { systemPromptTextArea.setColumns(60); systemPromptTextArea.setRows(3); - openNewTabCheckBox = new JBCheckBox(CodeGPTBundle.get("configurationConfigurable.openNewTabCheckBox.label"), false); + openNewTabCheckBox = new JBCheckBox( + CodeGPTBundle.get("configurationConfigurable.openNewTabCheckBox.label"), false); mainPanel = FormBuilder.createFormBuilder() .addComponent(tablePanel) .addVerticalGap(4) .addComponent(openNewTabCheckBox) .addVerticalGap(4) - .addComponent(new TitledSeparator(CodeGPTBundle.get("configurationConfigurable.section.assistant.title"))) + .addComponent(new TitledSeparator( + CodeGPTBundle.get("configurationConfigurable.section.assistant.title"))) .addComponent(createAssistantConfigurationForm()) .addComponentFillVertically(new JPanel(), 0) .getPanel(); @@ -140,7 +143,11 @@ public class ConfigurationComponent { } // Formatted keys are not referenced in the messages bundle file - private void addAssistantFormLabeledComponent(FormBuilder formBuilder, String labelKey, String commentKey, JComponent component) { + private void addAssistantFormLabeledComponent( + FormBuilder formBuilder, + String labelKey, + String commentKey, + JComponent component) { formBuilder.addLabeledComponent( new JBLabel(CodeGPTBundle.get(labelKey)) .withBorder(JBUI.Borders.emptyLeft(2)), @@ -180,17 +187,23 @@ public class ConfigurationComponent { return form; } - private ComponentValidator createInputValidator(Disposable parentDisposable, JBTextField component) { + private ComponentValidator createInputValidator( + Disposable parentDisposable, + JBTextField component) { var validator = new ComponentValidator(parentDisposable) .withValidator(() -> { var valueText = component.getText(); try { var value = Double.parseDouble(valueText); if (value > 1.0 || value < 0.0) { - return new ValidationInfo(CodeGPTBundle.get("validation.error.mustBeBetweenZeroAndOne"), component); + return new ValidationInfo( + CodeGPTBundle.get("validation.error.mustBeBetweenZeroAndOne"), + component); } } catch (NumberFormatException e) { - return new ValidationInfo(CodeGPTBundle.get("validation.error.mustBeNumber"), component); + return new ValidationInfo( + CodeGPTBundle.get("validation.error.mustBeNumber"), + component); } return null; @@ -246,7 +259,9 @@ public class ConfigurationComponent { class RevertToDefaultsActionButton extends AnActionButton { RevertToDefaultsActionButton() { - super(CodeGPTBundle.get("configurationConfigurable.table.action.revertToDefaults.text"), AllIcons.Actions.Rollback); + super( + CodeGPTBundle.get("configurationConfigurable.table.action.revertToDefaults.text"), + AllIcons.Actions.Rollback); } @Override @@ -261,7 +276,9 @@ public class ConfigurationComponent { class KeymapActionButton extends AnActionButton { KeymapActionButton() { - super(CodeGPTBundle.get("configurationConfigurable.table.action.addKeymap.text"), Nodes.KeymapEditor); + super( + CodeGPTBundle.get("configurationConfigurable.table.action.addKeymap.text"), + Nodes.KeymapEditor); } @Override diff --git a/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationConfigurable.java b/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationConfigurable.java index 16f7f7a4..cae1cfe3 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationConfigurable.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationConfigurable.java @@ -33,11 +33,12 @@ public class ConfigurationConfigurable implements Configurable { @Override public boolean isModified() { var configuration = ConfigurationState.getInstance(); - return !configurationComponent.getTableData().equals(configuration.getTableData()) || - configurationComponent.getMaxTokens() != configuration.getMaxTokens() || - configurationComponent.getTemperature() != configuration.getTemperature() || - !configurationComponent.getSystemPrompt().equals(configuration.getSystemPrompt()) || - configurationComponent.isCreateNewChatOnEachAction() != configuration.isCreateNewChatOnEachAction(); + return !configurationComponent.getTableData().equals(configuration.getTableData()) + || configurationComponent.getMaxTokens() != configuration.getMaxTokens() + || configurationComponent.getTemperature() != configuration.getTemperature() + || !configurationComponent.getSystemPrompt().equals(configuration.getSystemPrompt()) + || configurationComponent.isCreateNewChatOnEachAction() + != configuration.isCreateNewChatOnEachAction(); } @Override @@ -47,7 +48,8 @@ public class ConfigurationConfigurable implements Configurable { configuration.setMaxTokens(configurationComponent.getMaxTokens()); configuration.setTemperature(configurationComponent.getTemperature()); configuration.setSystemPrompt(configurationComponent.getSystemPrompt()); - configuration.setCreateNewChatOnEachAction(configurationComponent.isCreateNewChatOnEachAction()); + configuration.setCreateNewChatOnEachAction( + configurationComponent.isCreateNewChatOnEachAction()); EditorActionsUtil.refreshActions(); } @@ -58,7 +60,8 @@ public class ConfigurationConfigurable implements Configurable { configurationComponent.setMaxTokens(configuration.getMaxTokens()); configurationComponent.setTemperature(configuration.getTemperature()); configurationComponent.setSystemPrompt(configuration.getSystemPrompt()); - configurationComponent.setCreateNewChatOnEachAction(configuration.isCreateNewChatOnEachAction()); + configurationComponent.setCreateNewChatOnEachAction( + configuration.isCreateNewChatOnEachAction()); EditorActionsUtil.refreshActions(); } diff --git a/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationState.java b/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationState.java index 75e45d97..976f3c17 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationState.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/configuration/ConfigurationState.java @@ -12,7 +12,9 @@ import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -@State(name = "CodeGPT_ConfigurationSettings_210", storages = @Storage("CodeGPT_ConfigurationSettings_210.xml")) +@State( + name = "CodeGPT_ConfigurationSettings_210", + storages = @Storage("CodeGPT_ConfigurationSettings_210.xml")) public class ConfigurationState implements PersistentStateComponent { private String systemPrompt = COMPLETION_SYSTEM_PROMPT; diff --git a/src/main/java/ee/carlrobert/codegpt/settings/service/DownloadModelAction.java b/src/main/java/ee/carlrobert/codegpt/settings/service/DownloadModelAction.java index dd3a5ca0..23576b57 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/service/DownloadModelAction.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/service/DownloadModelAction.java @@ -54,7 +54,10 @@ public class DownloadModelAction extends AnAction { class DownloadBackgroundTask extends Task.Backgroundable { DownloadBackgroundTask(Project project) { - super(project, CodeGPTBundle.get("settingsConfigurable.service.llama.progress.downloadingModel.title"), true); + super( + project, + CodeGPTBundle.get("settingsConfigurable.service.llama.progress.downloadingModel.title"), + true); } @Override @@ -68,15 +71,20 @@ public class DownloadModelAction extends AnAction { onDownload.accept(indicator); indicator.setIndeterminate(false); - indicator.setText(format(CodeGPTBundle.get("settingsConfigurable.service.llama.progress.downloadingModelIndicator.text"), model.getFileName())); + indicator.setText(format( + CodeGPTBundle.get( + "settingsConfigurable.service.llama.progress.downloadingModelIndicator.text"), + model.getFileName())); long fileSize = url.openConnection().getContentLengthLong(); long[] bytesRead = {0}; long startTime = System.currentTimeMillis(); progressUpdateScheduler = executorService.scheduleAtFixedRate(() -> - onUpdateProgress.accept( - DownloadingUtils.getFormattedDownloadProgress(startTime, fileSize, bytesRead[0])), + onUpdateProgress.accept(DownloadingUtils.getFormattedDownloadProgress( + startTime, + fileSize, + bytesRead[0])), 0, 1, TimeUnit.SECONDS); FileUtils.copyFileWithProgress(model.getFileName(), url, bytesRead, fileSize, indicator); } catch (IOException ex) { diff --git a/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaModelPreferencesForm.java b/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaModelPreferencesForm.java index 460cd87a..344bbdf1 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaModelPreferencesForm.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaModelPreferencesForm.java @@ -125,14 +125,16 @@ public class LlamaModelPreferencesForm { modelComboBoxModel, modelSizeComboBoxModel, huggingFaceComboBoxModel); - modelSizeComboBox.setEnabled(initialModelSizes.size() > 1 && !llamaServerAgent.isServerRunning()); + modelSizeComboBox.setEnabled( + initialModelSizes.size() > 1 && !llamaServerAgent.isServerRunning()); promptTemplateComboBox = new ComboBox<>(new EnumComboBoxModel<>(PromptTemplate.class)); promptTemplateComboBox.setSelectedItem(llamaSettings.getPromptTemplate()); promptTemplateComboBox.setEnabled( llamaSettings.isUseCustomModel() && !llamaServerAgent.isServerRunning()); promptTemplateComboBox.setPreferredSize(modelComboBox.getPreferredSize()); useCustomModelCheckBox = new JBCheckBox(CodeGPTBundle.get( - "settingsConfigurable.service.llama.useCustomModel.label"), llamaSettings.isUseCustomModel()); + "settingsConfigurable.service.llama.useCustomModel.label"), + llamaSettings.isUseCustomModel()); useCustomModelCheckBox.setEnabled(!llamaServerAgent.isServerRunning()); useCustomModelCheckBox.addChangeListener(e -> { var selected = ((JBCheckBox) e.getSource()).isSelected(); @@ -167,16 +169,25 @@ public class LlamaModelPreferencesForm { huggingFaceModelComboBoxWrapper.add(modelDetailsLabel); return FormBuilder.createFormBuilder() - .addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.shared.model.label"), modelComboBoxWrapper) - .addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.service.llama.modelSize.label"), modelSizeComboBox) - .addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.service.llama.quantization.label"), huggingFaceModelComboBoxWrapper) + .addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.shared.model.label"), + modelComboBoxWrapper) + .addLabeledComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.modelSize.label"), + modelSizeComboBox) + .addLabeledComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.quantization.label"), + huggingFaceModelComboBoxWrapper) .addComponentToRightColumn(quantizationHelpText) .addComponentToRightColumn(downloadModelActionLinkWrapper) .addComponentToRightColumn(progressLabel) .addVerticalGap(8) .addComponent(useCustomModelCheckBox) - .addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.service.llama.promptTemplate.label"), promptTemplateComboBox) - .addLabeledComponent(CodeGPTBundle.get("settingsConfigurable.service.llama.customModelPath.label"), customModelPathBrowserButton) + .addLabeledComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.promptTemplate.label"), + promptTemplateComboBox) + .addLabeledComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.customModelPath.label"), + customModelPathBrowserButton) .addComponentToRightColumn(customModelHelpText) .addVerticalGap(4) .getPanel(); @@ -297,8 +308,8 @@ public class LlamaModelPreferencesForm { var models = selectedModel.getHuggingFaceModels().stream() .filter(model -> { var selectedModelSize = (ModelSize) modelSizeComboBoxModel.getSelectedItem(); - return selectedModelSize != null && - selectedModelSize.getSize() == model.getParameterSize(); + return selectedModelSize != null + && selectedModelSize.getSize() == model.getParameterSize(); }) .collect(toList()); if (!models.isEmpty()) { @@ -349,18 +360,23 @@ public class LlamaModelPreferencesForm { JPanel actionLinkWrapper, DefaultComboBoxModel huggingFaceComboBoxModel, ProgressIndicator progressIndicator) { - return new AnActionLink(CodeGPTBundle.get("settingsConfigurable.service.llama.cancelDownloadLink.label"), new AnAction() { - @Override - public void actionPerformed(@NotNull AnActionEvent e) { - SwingUtilities.invokeLater(() -> { - configureFieldsForDownloading(false); - updateActionLink( - actionLinkWrapper, - createDownloadModelLink(progressLabel, actionLinkWrapper, huggingFaceComboBoxModel)); - progressIndicator.cancel(); + return new AnActionLink( + CodeGPTBundle.get("settingsConfigurable.service.llama.cancelDownloadLink.label"), + new AnAction() { + @Override + public void actionPerformed(@NotNull AnActionEvent e) { + SwingUtilities.invokeLater(() -> { + configureFieldsForDownloading(false); + updateActionLink( + actionLinkWrapper, + createDownloadModelLink( + progressLabel, + actionLinkWrapper, + huggingFaceComboBoxModel)); + progressIndicator.cancel(); + }); + } }); - } - }); } private void updateActionLink(JPanel actionLinkWrapper, AnActionLink actionLink) { @@ -383,33 +399,39 @@ public class LlamaModelPreferencesForm { JBLabel progressLabel, JPanel actionLinkWrapper, DefaultComboBoxModel huggingFaceComboBoxModel) { - return new AnActionLink(CodeGPTBundle.get("settingsConfigurable.service.llama.downloadModelLink.label"), new DownloadModelAction( - progressIndicator -> { - SwingUtilities.invokeLater(() -> { - configureFieldsForDownloading(true); - updateActionLink( - actionLinkWrapper, - createCancelDownloadLink( - progressLabel, + return new AnActionLink( + CodeGPTBundle.get("settingsConfigurable.service.llama.downloadModelLink.label"), + new DownloadModelAction( + progressIndicator -> { + SwingUtilities.invokeLater(() -> { + configureFieldsForDownloading(true); + updateActionLink( actionLinkWrapper, - huggingFaceComboBoxModel, - progressIndicator)); - }); - }, - () -> SwingUtilities.invokeLater(() -> { - configureFieldsForDownloading(false); - updateActionLink( - actionLinkWrapper, - createDownloadModelLink(progressLabel, actionLinkWrapper, huggingFaceComboBoxModel)); - actionLinkWrapper.setVisible(false); - LlamaSettingsState.getInstance() - .setHuggingFaceModel((HuggingFaceModel) huggingFaceComboBoxModel.getSelectedItem()); - }), - (error) -> { - throw new RuntimeException(error); - }, - (text) -> SwingUtilities.invokeLater(() -> progressLabel.setText(text)), - huggingFaceComboBoxModel), "unknown"); + createCancelDownloadLink( + progressLabel, + actionLinkWrapper, + huggingFaceComboBoxModel, + progressIndicator)); + }); + }, + () -> SwingUtilities.invokeLater(() -> { + configureFieldsForDownloading(false); + updateActionLink( + actionLinkWrapper, + createDownloadModelLink( + progressLabel, + actionLinkWrapper, + huggingFaceComboBoxModel)); + actionLinkWrapper.setVisible(false); + LlamaSettingsState.getInstance() + .setHuggingFaceModel( + (HuggingFaceModel) huggingFaceComboBoxModel.getSelectedItem()); + }), + (error) -> { + throw new RuntimeException(error); + }, + (text) -> SwingUtilities.invokeLater(() -> progressLabel.setText(text)), + huggingFaceComboBoxModel), "unknown"); } private void updateModelHelpTooltip(HuggingFaceModel model) { @@ -418,7 +440,9 @@ public class LlamaModelPreferencesForm { new HelpTooltip() .setTitle(llamaModel.getLabel()) .setDescription("

" + llamaModel.getDescription() + "

") - .setBrowserLink(CodeGPTBundle.get("settingsConfigurable.service.llama.linkToModel.label"), model.getHuggingFaceURL()) + .setBrowserLink( + CodeGPTBundle.get("settingsConfigurable.service.llama.linkToModel.label"), + model.getHuggingFaceURL()) .installOn(helpIcon); } diff --git a/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaServiceSelectionForm.java b/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaServiceSelectionForm.java index c8da2e75..010c506d 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaServiceSelectionForm.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/service/LlamaServiceSelectionForm.java @@ -31,12 +31,12 @@ public class LlamaServiceSelectionForm extends JPanel { private final IntegerField maxTokensField; public LlamaServiceSelectionForm() { - var llamaServerAgent = ApplicationManager.getApplication().getService(LlamaServerAgent.class); + var llamaServerAgent = + ApplicationManager.getApplication().getService(LlamaServerAgent.class); var serverRunning = llamaServerAgent.isServerRunning(); portField = new PortField(LlamaSettingsState.getInstance().getServerPort()); portField.setEnabled(!serverRunning); - var serverProgressPanel = new ServerProgressPanel(); llamaModelPreferencesForm = new LlamaModelPreferencesForm(); maxTokensField = new IntegerField("max_tokens", 256, 4096); @@ -44,10 +44,68 @@ public class LlamaServiceSelectionForm extends JPanel { maxTokensField.setValue(2048); maxTokensField.setEnabled(!serverRunning); + var serverProgressPanel = new ServerProgressPanel(); + var serverButton = getServerButton(serverRunning, llamaServerAgent, serverProgressPanel); + var contextSizeHelpText = ComponentPanelBuilder.createCommentComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.contextSize.comment"), + true); + contextSizeHelpText.setBorder(JBUI.Borders.empty(0, 4)); + + setLayout(new BorderLayout()); + add(FormBuilder.createFormBuilder() + .addComponent(new TitledSeparator( + CodeGPTBundle.get("settingsConfigurable.service.llama.modelPreferences.title"))) + .addComponent(withEmptyLeftBorder(llamaModelPreferencesForm.getForm())) + .addComponent(new TitledSeparator( + CodeGPTBundle.get("settingsConfigurable.service.llama.serverPreferences.title"))) + .addComponent(withEmptyLeftBorder(FormBuilder.createFormBuilder() + .addLabeledComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.contextSize.label"), + maxTokensField) + .addComponentToRightColumn(contextSizeHelpText) + .addLabeledComponent( + CodeGPTBundle.get("settingsConfigurable.service.llama.port.label"), + JBUI.Panels.simplePanel() + .addToLeft(portField) + .addToRight(serverButton)) + .getPanel())) + .addVerticalGap(4) + .addComponent(withEmptyLeftBorder(serverProgressPanel)) + .addComponentFillVertically(new JPanel(), 0) + .getPanel()); + } + + public void setServerPort(int serverPort) { + portField.setNumber(serverPort); + } + + public int getServerPort() { + return portField.getNumber(); + } + + public LlamaModelPreferencesForm getLlamaModelPreferencesForm() { + return llamaModelPreferencesForm; + } + + private JComponent withEmptyLeftBorder(JComponent component) { + component.setBorder(JBUI.Borders.emptyLeft(16)); + return component; + } + + public int getContextSize() { + return maxTokensField.getValue(); + } + + public void setContextSize(int contextSize) { + maxTokensField.setValue(contextSize); + } + + private JButton getServerButton(boolean serverRunning, LlamaServerAgent llamaServerAgent, + ServerProgressPanel serverProgressPanel) { var serverButton = new JButton(); - serverButton.setText(serverRunning ? - CodeGPTBundle.get("settingsConfigurable.service.llama.stopServer.label") : - CodeGPTBundle.get("settingsConfigurable.service.llama.startServer.label")); + serverButton.setText(serverRunning + ? CodeGPTBundle.get("settingsConfigurable.service.llama.stopServer.label") + : CodeGPTBundle.get("settingsConfigurable.service.llama.startServer.label")); serverButton.setIcon(serverRunning ? Actions.Suspend : Actions.Execute); serverButton.addActionListener(event -> { if (llamaModelPreferencesForm.isUseCustomLlamaModel()) { @@ -87,11 +145,11 @@ public class LlamaServiceSelectionForm extends JPanel { CodeGPTBundle.get("settingsConfigurable.service.llama.progress.startingServer")); // TODO: Move to LlamaModelPreferencesForm - var modelPath = llamaModelPreferencesForm.isUseCustomLlamaModel() ? - llamaModelPreferencesForm.getCustomLlamaModelPath() : - CodeGPTPlugin.getLlamaModelsPath() + - File.separator + - llamaModelPreferencesForm.getSelectedModel().getFileName(); + var modelPath = llamaModelPreferencesForm.isUseCustomLlamaModel() + ? llamaModelPreferencesForm.getCustomLlamaModelPath() + : CodeGPTPlugin.getLlamaModelsPath() + + File.separator + + llamaModelPreferencesForm.getSelectedModel().getFileName(); llamaServerAgent.startAgent( modelPath, maxTokensField.getValue(), @@ -104,34 +162,7 @@ public class LlamaServiceSelectionForm extends JPanel { }); } }); - - var contextSizeHelpText = ComponentPanelBuilder.createCommentComponent( - CodeGPTBundle.get("settingsConfigurable.service.llama.contextSize.comment"), - true); - contextSizeHelpText.setBorder(JBUI.Borders.empty(0, 4)); - - setLayout(new BorderLayout()); - add(FormBuilder.createFormBuilder() - .addComponent(new TitledSeparator( - CodeGPTBundle.get("settingsConfigurable.service.llama.modelPreferences.title"))) - .addComponent(withEmptyLeftBorder(llamaModelPreferencesForm.getForm())) - .addComponent(new TitledSeparator( - CodeGPTBundle.get("settingsConfigurable.service.llama.serverPreferences.title"))) - .addComponent(withEmptyLeftBorder(FormBuilder.createFormBuilder() - .addLabeledComponent( - CodeGPTBundle.get("settingsConfigurable.service.llama.contextSize.label"), - maxTokensField) - .addComponentToRightColumn(contextSizeHelpText) - .addLabeledComponent( - CodeGPTBundle.get("settingsConfigurable.service.llama.port.label"), - JBUI.Panels.simplePanel() - .addToLeft(portField) - .addToRight(serverButton)) - .getPanel())) - .addVerticalGap(4) - .addComponent(withEmptyLeftBorder(serverProgressPanel)) - .addComponentFillVertically(new JPanel(), 0) - .getPanel()); + return serverButton; } private boolean isModelExists(HuggingFaceModel model) { @@ -144,29 +175,4 @@ public class LlamaServiceSelectionForm extends JPanel { portField.setEnabled(enabled); maxTokensField.setEnabled(enabled); } - - public void setServerPort(int serverPort) { - portField.setNumber(serverPort); - } - - public int getServerPort() { - return portField.getNumber(); - } - - public LlamaModelPreferencesForm getLlamaModelPreferencesForm() { - return llamaModelPreferencesForm; - } - - private JComponent withEmptyLeftBorder(JComponent component) { - component.setBorder(JBUI.Borders.emptyLeft(16)); - return component; - } - - public int getContextSize() { - return maxTokensField.getValue(); - } - - public void setContextSize(int contextSize) { - maxTokensField.setValue(contextSize); - } } diff --git a/src/main/java/ee/carlrobert/codegpt/settings/service/ServiceSelectionForm.java b/src/main/java/ee/carlrobert/codegpt/settings/service/ServiceSelectionForm.java index 3909c771..e24e42c7 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/service/ServiceSelectionForm.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/service/ServiceSelectionForm.java @@ -61,12 +61,17 @@ public class ServiceSelectionForm { public ServiceSelectionForm(Disposable parentDisposable) { this.parentDisposable = parentDisposable; - var openAISettings = OpenAISettingsState.getInstance(); - var azureSettings = AzureSettingsState.getInstance(); openAIApiKeyField = new JBPasswordField(); openAIApiKeyField.setColumns(30); openAIApiKeyField.setText(OpenAICredentialsManager.getInstance().getApiKey()); + var azureSettings = AzureSettingsState.getInstance(); + useAzureApiKeyAuthenticationRadioButton = new JBRadioButton( + CodeGPTBundle.get("settingsConfigurable.service.azure.useApiKeyAuth.label"), + azureSettings.isUseAzureApiKeyAuthentication()); + useAzureActiveDirectoryAuthenticationRadioButton = new JBRadioButton( + CodeGPTBundle.get("settingsConfigurable.service.azure.useActiveDirectoryAuth.label"), + azureSettings.isUseAzureActiveDirectoryAuthentication()); azureApiKeyField = new JBPasswordField(); azureApiKeyField.setColumns(30); azureApiKeyField.setText(AzureCredentialsManager.getInstance().getAzureOpenAIApiKey()); @@ -82,13 +87,8 @@ public class ServiceSelectionForm { .withLabel(CodeGPTBundle.get("settingsConfigurable.service.azure.bearerToken.label")) .resizeX(false) .createPanel(); - useAzureApiKeyAuthenticationRadioButton = new JBRadioButton( - CodeGPTBundle.get("settingsConfigurable.service.azure.useApiKeyAuth.label"), - azureSettings.isUseAzureApiKeyAuthentication()); - useAzureActiveDirectoryAuthenticationRadioButton = new JBRadioButton( - CodeGPTBundle.get("settingsConfigurable.service.azure.useActiveDirectoryAuth.label"), - azureSettings.isUseAzureActiveDirectoryAuthentication()); + var openAISettings = OpenAISettingsState.getInstance(); openAIBaseHostField = new JBTextField(openAISettings.getBaseHost(), 30); openAIPathField = new JBTextField(openAISettings.getPath(), 30); openAIOrganizationField = new JBTextField(openAISettings.getOrganization(), 30); diff --git a/src/main/java/ee/carlrobert/codegpt/settings/service/YouServiceSelectionForm.java b/src/main/java/ee/carlrobert/codegpt/settings/service/YouServiceSelectionForm.java index 0c6a0209..51d4087a 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/service/YouServiceSelectionForm.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/service/YouServiceSelectionForm.java @@ -158,8 +158,13 @@ public class YouServiceSelectionForm extends JPanel { "" + "" + "

Free GPT-4

" - + "

Your coupon code

" - + "

CODEGPT

" + + "

" + + "Your coupon code" + + "

" + + "

" + + "CODEGPT" + + "

" + "" + "") .withBorder(JBUI.Borders.emptyLeft(45)) // TODO diff --git a/src/main/java/ee/carlrobert/codegpt/settings/state/AzureSettingsState.java b/src/main/java/ee/carlrobert/codegpt/settings/state/AzureSettingsState.java index 763aace1..ad5ba9dc 100644 --- a/src/main/java/ee/carlrobert/codegpt/settings/state/AzureSettingsState.java +++ b/src/main/java/ee/carlrobert/codegpt/settings/state/AzureSettingsState.java @@ -12,7 +12,7 @@ import org.jetbrains.annotations.NotNull; @State(name = "CodeGPT_AzureSettings_210", storages = @Storage("CodeGPT_AzureSettings_210.xml")) public class AzureSettingsState implements PersistentStateComponent { - private final String BASE_PATH = "/openai/deployments/%s/chat/completions?api-version=%s"; + private static final String BASE_PATH = "/openai/deployments/%s/chat/completions?api-version=%s"; private String resourceName = ""; private String deploymentId = ""; @@ -38,23 +38,24 @@ public class AzureSettingsState implements PersistentStateComponent { - private final String BASE_PATH = "/v1/chat/completions"; + private static final String BASE_PATH = "/v1/chat/completions"; private String organization = ""; private String baseHost = "https://api.openai.com"; @@ -36,11 +36,12 @@ public class OpenAISettingsState implements PersistentStateComponent" + - "

Search results:

" + - "
    %s
" + - "", titles); + "" + + "

Search results:

" + + "
    %s
" + + "", titles); } public void clear() { diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/SmartScroller.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/SmartScroller.java index 1d87fed5..c9ed224c 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/SmartScroller.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/SmartScroller.java @@ -10,45 +10,21 @@ import javax.swing.SwingUtilities; import javax.swing.text.DefaultCaret; import javax.swing.text.JTextComponent; -/** - * The SmartScroller will attempt to keep the viewport positioned based on - * the users interaction with the scrollbar. The normal behaviour is to keep - * the viewport positioned to see new data as it is dynamically added. - *

- * Assuming vertical scrolling and data is added to the bottom: - *

- * - when the viewport is at the bottom and new data is added, - * then automatically scroll the viewport to the bottom - * - when the viewport is not at the bottom and new data is added, - * then do nothing with the viewport - *

- * Assuming vertical scrolling and data is added to the top: - *

- * - when the viewport is at the top and new data is added, - * then do nothing with the viewport - * - when the viewport is not at the top and new data is added, then adjust - * the viewport to the relative position it was at before the data was added - *

- * Similiar logic would apply for horizontal scrolling. - */ public class SmartScroller implements AdjustmentListener { - public final static int HORIZONTAL = 0; - public final static int VERTICAL = 1; - public final static int START = 0; - public final static int END = 1; + private static final int HORIZONTAL = 0; + private static final int VERTICAL = 1; + private static final int START = 0; + private static final int END = 1; - private int viewportPosition; + private final int viewportPosition; - private JScrollBar scrollBar; private boolean adjustScrollBar = true; - private int previousValue = -1; private int previousMaximum = -1; /** - * Convenience constructor. - * Scroll direction is VERTICAL and viewport position is at the END. + * Convenience constructor. Scroll direction is VERTICAL and viewport position is at the END. * * @param scrollPane the scroll pane to monitor */ @@ -56,26 +32,15 @@ public class SmartScroller implements AdjustmentListener { this(scrollPane, VERTICAL, END); } - /** - * Convenience constructor. - * Scroll direction is VERTICAL. - * - * @param scrollPane the scroll pane to monitor - * @param viewportPosition valid values are START and END - */ - public SmartScroller(JScrollPane scrollPane, int viewportPosition) { - this(scrollPane, VERTICAL, viewportPosition); - } /** * Specify how the SmartScroller will function. * * @param scrollPane the scroll pane to monitor - * @param scrollDirection indicates which JScrollBar to monitor. - * Valid values are HORIZONTAL and VERTICAL. - * @param viewportPosition indicates where the viewport will normally be - * positioned as data is added. - * Valid values are START and END + * @param scrollDirection indicates which JScrollBar to monitor. Valid values are HORIZONTAL and + * VERTICAL. + * @param viewportPosition indicates where the viewport will normally be positioned as data is + * added. Valid values are START and END */ public SmartScroller(JScrollPane scrollPane, int scrollDirection, int viewportPosition) { if (scrollDirection != HORIZONTAL @@ -90,6 +55,7 @@ public class SmartScroller implements AdjustmentListener { this.viewportPosition = viewportPosition; + JScrollBar scrollBar; if (scrollDirection == HORIZONTAL) { scrollBar = scrollPane.getHorizontalScrollBar(); } else { diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/UserPromptTextAreaHeader.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/UserPromptTextAreaHeader.java index 5e3a1f8a..79a5aebe 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/UserPromptTextAreaHeader.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/UserPromptTextAreaHeader.java @@ -35,6 +35,7 @@ public class UserPromptTextAreaHeader extends JPanel { subscribeToYouTopics(project, gpt4CheckBox); add(gpt4CheckBox, BorderLayout.LINE_START); break; + default: } add(JBUI.Panels .simplePanel(new ModelIconLabel( diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/YouProCheckbox.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/YouProCheckbox.java index ce21bc34..a0f87d32 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/YouProCheckbox.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/components/YouProCheckbox.java @@ -31,9 +31,9 @@ public class YouProCheckbox extends JBCheckBox { private String getTooltipText(YouUserManager youUserManager, boolean selected) { if (youUserManager.isSubscribed()) { - return selected ? - CodeGPTBundle.get("toolwindow.chat.youProCheckBox.disable") : - CodeGPTBundle.get("toolwindow.chat.youProCheckBox.enable"); + return selected + ? CodeGPTBundle.get("toolwindow.chat.youProCheckBox.disable") + : CodeGPTBundle.get("toolwindow.chat.youProCheckBox.enable"); } return CodeGPTBundle.get("toolwindow.chat.youProCheckBox.notAllowed"); } diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/ContextualChatToolWindowLandingPanel.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/ContextualChatToolWindowLandingPanel.java index 983863c9..806c6c38 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/ContextualChatToolWindowLandingPanel.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/ContextualChatToolWindowLandingPanel.java @@ -19,19 +19,13 @@ import ee.carlrobert.vector.VectorStore; import javax.swing.JTextPane; import javax.swing.event.HyperlinkEvent; -@FunctionalInterface -interface ActionEvent { - - void handleAction(String prompt); -} - class ContextualChatToolWindowLandingPanel extends ResponsePanel { private static final Logger LOG = Logger.getInstance(ContextualChatToolWindowLandingPanel.class); private final Project project; - private final ActionEvent actionEvent; + private final EditorActionEvent actionEvent; - ContextualChatToolWindowLandingPanel(Project project, ActionEvent actionEvent) { + ContextualChatToolWindowLandingPanel(Project project, EditorActionEvent actionEvent) { this.project = project; this.actionEvent = actionEvent; addContent(createContent()); @@ -45,26 +39,38 @@ class ContextualChatToolWindowLandingPanel extends ResponsePanel { private JTextPane createContent() { var description = createTextPane(); if (VectorStore.getInstance(CodeGPTPlugin.getPluginBasePath()).isIndexExists()) { - description.setText("" + - "

Feel free to ask me anything about your codebase, and I'll be your helpful guide, dedicated to providing you with the best answers possible!

" - + - "

Here are a few examples of how I might be helpful:

" - + - "
    " + - "
  • List all the dependencies that the project usesAre there any scheduled tasks or background jobs running in our codebase, and if so, what are they responsible for?
  • " - + - "
  • Can you provide an overview of the authentication and authorization mechanism implemented in our application?
  • " - + - ""); + description.setText("" + + "

    " + + "Feel free to ask me anything about your codebase, and I'll be your helpful guide, " + + "dedicated to providing you with the best answers possible!" + + "

    " + + "

    " + + "Here are a few examples of how I might be helpful:" + + "

    " + + "" + + ""); } else { - description.setText("" + - "

    It looks like you haven't indexed your codebase yet.

    " - + - "

    Start indexing your codebase to get access to contextual chat experience.

    " - + - ""); + description.setText("" + + "

    " + + "It looks like you haven't indexed your codebase yet." + + "

    " + + "

    " + + "Start indexing your codebase to get " + + "access to contextual chat experience." + + "

    " + + ""); } return description; @@ -87,12 +93,12 @@ class ContextualChatToolWindowLandingPanel extends ResponsePanel { actionEvent.handleAction("List all the dependencies that the project uses"); break; case "SCHEDULED_TASKS": - actionEvent.handleAction( - "Are there any scheduled tasks or background jobs running in our codebase, and if so, what are they responsible for?"); + actionEvent.handleAction("Are there any scheduled tasks or background " + + "jobs running in our codebase, and if so, what are they responsible for?"); break; case "AUTHENTICATION_MECHANISM": - actionEvent.handleAction( - "Can you provide an overview of the authentication and authorization mechanism implemented in our application?"); + actionEvent.handleAction("Can you provide an overview of the authentication " + + "and authorization mechanism implemented in our application?"); break; case "START_INDEXING": var folderStructureTreePanel = new FolderStructureTreePanel(project); diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/EditorActionEvent.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/EditorActionEvent.java new file mode 100644 index 00000000..b8fdecc9 --- /dev/null +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/contextual/EditorActionEvent.java @@ -0,0 +1,7 @@ +package ee.carlrobert.codegpt.toolwindow.chat.contextual; + +@FunctionalInterface +public interface EditorActionEvent { + + void handleAction(String prompt); +} diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/ResponseEditor.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/ResponseEditor.java index 3103185b..22ed7182 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/ResponseEditor.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/ResponseEditor.java @@ -112,11 +112,11 @@ public class ResponseEditor extends JPanel implements Disposable { } private String getLinkText(boolean expanded) { - return expanded ? - format( + return expanded + ? format( CodeGPTBundle.get("toolwindow.chat.editor.action.expand"), - ((EditorEx) editor).getDocument().getLineCount() - 1) : - CodeGPTBundle.get("toolwindow.chat.editor.action.collapse"); + ((EditorEx) editor).getDocument().getLineCount() - 1) + : CodeGPTBundle.get("toolwindow.chat.editor.action.collapse"); } private JPanel createFooterComponent(Color backgroundColor) { diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/DiffAction.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/DiffAction.java index d075327d..18f5e51b 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/DiffAction.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/DiffAction.java @@ -18,8 +18,8 @@ import ee.carlrobert.codegpt.CodeGPTBundle; import ee.carlrobert.codegpt.actions.ActionType; import ee.carlrobert.codegpt.actions.TrackableAction; import ee.carlrobert.codegpt.util.EditorUtils; -import ee.carlrobert.codegpt.util.file.FileUtils; import ee.carlrobert.codegpt.util.OverlayUtils; +import ee.carlrobert.codegpt.util.file.FileUtils; import org.jetbrains.annotations.NotNull; public class DiffAction extends TrackableAction { diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/EditAction.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/EditAction.java index c524c75c..ee2ac3e0 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/EditAction.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/editor/actions/EditAction.java @@ -34,9 +34,9 @@ public class EditAction extends TrackableAction { settings.setCaretRowShown(!viewer); event.getPresentation().setIcon(viewer ? Actions.EditSource : Actions.Show); - event.getPresentation().setText(viewer ? - CodeGPTBundle.get("toolwindow.chat.editor.action.edit.title") : - CodeGPTBundle.get("toolwindow.chat.editor.action.disableEditing.title")); + event.getPresentation().setText(viewer + ? CodeGPTBundle.get("toolwindow.chat.editor.action.edit.title") + : CodeGPTBundle.get("toolwindow.chat.editor.action.disableEditing.title")); var locationOnScreen = ((MouseEvent) event.getInputEvent()).getLocationOnScreen(); locationOnScreen.y = locationOnScreen.y - 16; diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/EditorAction.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/EditorAction.java index 1d3c4e61..597de764 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/EditorAction.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/EditorAction.java @@ -1,11 +1,26 @@ package ee.carlrobert.codegpt.toolwindow.chat.standard; enum EditorAction { - FIND_BUGS("Find Bugs", "Find bugs in the following code", "Find bugs and output code with bugs fixed in the following code: {{selectedCode}}"), - WRITE_TESTS("Write Tests", "Write Tests for the following code", "Write Tests for the following code: {{selectedCode}}"), - EXPLAIN("Explain", "Explain the following code", "Explain the following code: {{selectedCode}}"), - REFACTOR("Refactor", "Refactor the following code", "Refactor the following code: {{selectedCode}}"), - OPTIMIZE("Optimize", "Optimize the following code", "Optimize the following code: {{selectedCode}}"); + FIND_BUGS( + "Find Bugs", + "Find bugs in the following code", + "Find bugs and output code with bugs fixed in the following code: {{selectedCode}}"), + WRITE_TESTS( + "Write Tests", + "Write Tests for the following code", + "Write Tests for the following code: {{selectedCode}}"), + EXPLAIN( + "Explain", + "Explain the following code", + "Explain the following code: {{selectedCode}}"), + REFACTOR( + "Refactor", + "Refactor the following code", + "Refactor the following code: {{selectedCode}}"), + OPTIMIZE( + "Optimize", + "Optimize the following code", + "Optimize the following code: {{selectedCode}}"); private final String label; private final String userMessage; diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowLandingPanel.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowLandingPanel.java index 718ff11b..1706f1a9 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowLandingPanel.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowLandingPanel.java @@ -25,18 +25,36 @@ class StandardChatToolWindowLandingPanel extends ResponsePanel { private JTextPane createContent() { var textPane = SwingUtils.createTextPane( - "" + - format( - "

    Welcome %s, I'm your intelligent code companion, here to be your partner-in-crime for getting things done in a flash. Together, we'll tackle tasks swiftly and efficiently, making your coding experience a joy.

    ", - SettingsState.getInstance().getDisplayName()) + - "

    Feel free to ask me anything you'd like, but my true superpower lies in assisting you with your code! Here are a few examples of how I can assist you:

    " + - "
      " + - "
    • Generate unit tests for the selected codeExplain the selected code
    • " + - "
    • Find bugs in the selected code
    • " + - "Being an AI-powered assistant, I may occasionally have surprises or make mistakes. Therefore, it's wise to double-check any code or suggestions I provide.

      " + - "", + "" + + format( + "

      " + + "Welcome %s, I'm your intelligent code companion, here to be" + + " your partner-in-crime for getting things done in a flash. Together, we'll " + + "tackle tasks swiftly and efficiently, making your coding experience a joy." + + "

      ", + SettingsState.getInstance().getDisplayName()) + + "

      " + + "Feel free to ask me anything you'd like, but my true superpower lies in assisting " + + "you with your code! Here are a few examples of how I can assist you:" + + "

      " + + + "
        " + + "
      • " + + "Generate unit tests for the selected code" + + "
      • " + + "
      • " + + "Explain the selected code" + + "
      • " + + "
      • " + + "Find bugs in the selected code" + + "
      • " + + "" + + "Being an AI-powered assistant, I may occasionally have surprises or make mistakes. " + + "Therefore, it's wise to double-check any code or suggestions I provide." + + "

        " + + "", this::handleHyperlinkClicked); textPane.setBackground(getPanelBackgroundColor()); return textPane; diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowTabPanel.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowTabPanel.java index 5a49aadc..4940e2fe 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowTabPanel.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/chat/standard/StandardChatToolWindowTabPanel.java @@ -61,8 +61,8 @@ public class StandardChatToolWindowTabPanel extends BaseChatToolWindowTabPanel { .withResponse(message.getResponse()); var serpResults = message.getSerpResults(); - if (YouSettingsState.getInstance().isDisplayWebSearchResults() && - serpResults != null && !serpResults.isEmpty()) { + if (YouSettingsState.getInstance().isDisplayWebSearchResults() + && serpResults != null && !serpResults.isEmpty()) { messageResponseBody.displaySerpResults(serpResults); } diff --git a/src/main/java/ee/carlrobert/codegpt/toolwindow/conversations/ConversationPanel.java b/src/main/java/ee/carlrobert/codegpt/toolwindow/conversations/ConversationPanel.java index 8bfec8fe..365a1b08 100644 --- a/src/main/java/ee/carlrobert/codegpt/toolwindow/conversations/ConversationPanel.java +++ b/src/main/java/ee/carlrobert/codegpt/toolwindow/conversations/ConversationPanel.java @@ -59,9 +59,9 @@ class ConversationPanel extends JPanel { } private void addStyles(boolean isSelected) { - var border = isSelected ? - JBUI.Borders.customLine(JBUI.CurrentTheme.ActionButton.focusedBorder(), 2, 2, 2, 2) : - JBUI.Borders.customLine(JBColor.border(), 1, 0, 1, 0); + var border = isSelected + ? JBUI.Borders.customLine(JBUI.CurrentTheme.ActionButton.focusedBorder(), 2, 2, 2, 2) + : JBUI.Borders.customLine(JBColor.border(), 1, 0, 1, 0); setBackground(getPanelBackgroundColor()); setBorder(JBUI.Borders.compound(border, JBUI.Borders.empty(8))); setLayout(new GridBagLayout()); diff --git a/src/main/java/ee/carlrobert/codegpt/util/MarkdownUtils.java b/src/main/java/ee/carlrobert/codegpt/util/MarkdownUtils.java index 9f9ed0cf..8b310aed 100644 --- a/src/main/java/ee/carlrobert/codegpt/util/MarkdownUtils.java +++ b/src/main/java/ee/carlrobert/codegpt/util/MarkdownUtils.java @@ -10,11 +10,12 @@ import java.util.regex.Pattern; public class MarkdownUtils { /** - * Splits a given string into a list of strings where each element is either a code block surrounded by triple backticks - * or a non-code block text. + * Splits a given string into a list of strings where each element is either a code block + * surrounded by triple backticks or a non-code block text. * - * @param inputMarkdown The input markdown formatted string to be split. - * @return A list of strings where each element is a code block or a non-code block text from the input string. + * @param inputMarkdown The input markdown formatted string to be split. + * @return A list of strings where each element is a code block or a non-code block text from the + * input string. */ public static List splitCodeBlocks(String inputMarkdown) { List result = new ArrayList<>(); diff --git a/src/main/java/ee/carlrobert/codegpt/util/OverlayUtils.java b/src/main/java/ee/carlrobert/codegpt/util/OverlayUtils.java index 9b2e1125..dbed0b77 100644 --- a/src/main/java/ee/carlrobert/codegpt/util/OverlayUtils.java +++ b/src/main/java/ee/carlrobert/codegpt/util/OverlayUtils.java @@ -34,18 +34,23 @@ import org.jetbrains.annotations.NotNull; public class OverlayUtils { public static void showNotification(String content, NotificationType type) { - Notifications.Bus.notify(new Notification("CodeGPT Notification Group", "CodeGPT", content, type)); + Notifications.Bus.notify( + new Notification("CodeGPT Notification Group", "CodeGPT", content, type)); } - public static int showFileStructureDialog(Project project, FolderStructureTreePanel folderStructureTreePanel) { + public static int showFileStructureDialog( + Project project, + FolderStructureTreePanel folderStructureTreePanel) { var dialogBuilder = new DialogBuilder(project); dialogBuilder.setNorthPanel(JBUI.Panels.simplePanel(new JBLabel( - "" + - "

        Indexing files enables direct queries related to your codebase.

        " + - "
        " + - "

        File indexing occurs locally on your computer; no files are sent to any 3rd party services.

        " + - "

        For additional information, refer to the CodeGPT documentation.

        " + - "") + "" + + "

        Indexing files enables direct queries related to your codebase.

        " + + "
        " + + "

        File indexing occurs locally on your computer; " + + "no files are sent to any 3rd party services.

        " + + "

        For additional information, refer to the " + + "CodeGPT documentation.

        " + + "") .setCopyable(true) .setAllowAutoWrapping(true) .withFont(JBFont.medium())) diff --git a/src/test/java/ee/carlrobert/codegpt/completions/CompletionRequestProviderTest.java b/src/test/java/ee/carlrobert/codegpt/completions/CompletionRequestProviderTest.java index 0739bd30..755a9ce2 100644 --- a/src/test/java/ee/carlrobert/codegpt/completions/CompletionRequestProviderTest.java +++ b/src/test/java/ee/carlrobert/codegpt/completions/CompletionRequestProviderTest.java @@ -144,20 +144,20 @@ public class CompletionRequestProviderTest extends IntegrationTest { List.of(Map.of( "role", "user", "content", - "You are Text Generator, a helpful expert of generating natural language into semantically comparable search query.\n" - + - "\n" + - "Text: List all the dependencies that the project uses\n" + - "AI: project dependencies, development dependencies, versions, libraries, frameworks, packages\n" - + - "\n" + - "Text: Are there any scheduled tasks or background jobs running in our codebase, and if so, what are they responsible for?\n" - + - "AI: scheduled tasks, background jobs, cron jobs, task schedules, codebase tasks\n" - + - "\n" + - "Text: TEST_CHAT_COMPLETION_PROMPT\n" + - "AI:"))); + "You are Text Generator, a helpful expert of generating natural " + + "language into semantically comparable search query.\n" + + "\n" + + "Text: List all the dependencies that the project uses\n" + + "AI: project dependencies, development dependencies, " + + "versions, libraries, frameworks, packages\n" + + "\n" + + "Text: Are there any scheduled tasks or background jobs " + + "running in our codebase, and if so, what are they responsible for?\n" + + "AI: scheduled tasks, background jobs, cron jobs, " + + "task schedules, codebase tasks\n" + + "\n" + + "Text: TEST_CHAT_COMPLETION_PROMPT\n" + + "AI:"))); return new ResponseEntity(200, jsonMapResponse("choices", jsonArray(jsonMap("message", @@ -183,17 +183,17 @@ public class CompletionRequestProviderTest extends IntegrationTest { assertThat(request.getMessages().get(0)) .extracting("role", "content") .containsExactly("user", - "Use the following pieces of context to answer the question at the end.\n" + - "If you don't know the answer, just say that you don't know, don't try to make up an answer.\n" - + - "\n" + - "Context:\n" + - "\n" + - "TEST_CONTEXT\n" + - "\n" + - "Question: TEST_CHAT_COMPLETION_PROMPT\n" + - "\n" + - "Helpful answer in Markdown format:"); + "Use the following pieces of context to answer the question at the end.\n" + + "If you don't know the answer, just say that you don't know, " + + "don't try to make up an answer.\n" + + "\n" + + "Context:\n" + + "\n" + + "TEST_CONTEXT\n" + + "\n" + + "Question: TEST_CHAT_COMPLETION_PROMPT\n" + + "\n" + + "Helpful answer in Markdown format:"); } private Message createDummyMessage(int tokenSize) { diff --git a/src/test/java/ee/carlrobert/codegpt/completions/DefaultCompletionRequestHandlerTest.java b/src/test/java/ee/carlrobert/codegpt/completions/DefaultCompletionRequestHandlerTest.java index 1592be68..c6b8bf16 100644 --- a/src/test/java/ee/carlrobert/codegpt/completions/DefaultCompletionRequestHandlerTest.java +++ b/src/test/java/ee/carlrobert/codegpt/completions/DefaultCompletionRequestHandlerTest.java @@ -56,8 +56,6 @@ public class DefaultCompletionRequestHandlerTest extends IntegrationTest { public void testAzureChatCompletionCall() { useAzureService(); var conversationService = ConversationService.getInstance(); - var message = new Message("TEST_PROMPT"); - var requestHandler = new CompletionRequestHandler(false, getRequestEventListener(message)); var prevMessage = new Message("TEST_PREV_PROMPT"); prevMessage.setResponse("TEST_PREV_RESPONSE"); var conversation = conversationService.startConversation(); @@ -82,6 +80,8 @@ public class DefaultCompletionRequestHandlerTest extends IntegrationTest { jsonMapResponse("choices", jsonArray(jsonMap("delta", jsonMap("content", "lo")))), jsonMapResponse("choices", jsonArray(jsonMap("delta", jsonMap("content", "!"))))); }); + var message = new Message("TEST_PROMPT"); + var requestHandler = new CompletionRequestHandler(false, getRequestEventListener(message)); requestHandler.call(conversation, message, false); @@ -99,34 +99,36 @@ public class DefaultCompletionRequestHandlerTest extends IntegrationTest { assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getUri().getPath()).isEqualTo("/api/streamingSearch"); assertThat(request.getUri().getQuery()).isEqualTo( - "q=TEST_PROMPT&" + - "page=1&" + - "cfr=CodeGPT&" + - "count=10&" + - "safeSearch=WebPages,Translations,TimeZone,Computation,RelatedSearches&" + - "domain=youchat&" + - "chat=[{\"question\":\"Ping\",\"answer\":\"Pong\"}]&" + - "utm_source=ide&" + - "utm_medium=jetbrains&" + - "utm_campaign=" + CodeGPTPlugin.getVersion() + "&" + - "utm_content=CodeGPT"); + "q=TEST_PROMPT&" + + "page=1&" + + "cfr=CodeGPT&" + + "count=10&" + + "safeSearch=WebPages,Translations,TimeZone,Computation,RelatedSearches&" + + "domain=youchat&" + + "chat=[{\"question\":\"Ping\",\"answer\":\"Pong\"}]&" + + "utm_source=ide&" + + "utm_medium=jetbrains&" + + "utm_campaign=" + CodeGPTPlugin.getVersion() + "&" + + "utm_content=CodeGPT"); assertThat(request.getHeaders()) .flatExtracting("Accept", "Connection", "User-agent", "Cookie") .containsExactly( "text/event-stream", "Keep-Alive", "youide CodeGPT", - "safesearch_guest=Moderate; " + - "youpro_subscription=true; " + - "you_subscription=free; " + - "stytch_session=; " + - "ydc_stytch_session=; " + - "stytch_session_jwt=; " + - "ydc_stytch_session_jwt=; " + - "eg4=false; " + - "safesearch_9015f218b47611b62bbbaf61125cd2dac629e65c3d6f47573a2ec0e9b615c691=Moderate; " - + - "__cf_bm=aN2b3pQMH8XADeMB7bg9s1bJ_bfXBcCHophfOGRg6g0-1693601599-0-AWIt5Mr4Y3xQI4mIJ1lSf4+vijWKDobrty8OopDeBxY+NABe0MRFidF3dCUoWjRt8SVMvBZPI3zkOgcRs7Mz3yazd7f7c58HwW5Xg9jdBjNg;"); + "safesearch_guest=Moderate; " + + "youpro_subscription=true; " + + "you_subscription=free; " + + "stytch_session=; " + + "ydc_stytch_session=; " + + "stytch_session_jwt=; " + + "ydc_stytch_session_jwt=; " + + "eg4=false; " + + "safesearch_9015f218b47611b62bbbaf61125cd2dac629e65c3d6f" + + "47573a2ec0e9b615c691=Moderate; " + + "__cf_bm=aN2b3pQMH8XADeMB7bg9s1bJ_bfXBcCHophfOGRg6g0-1693601599-0-" + + "AWIt5Mr4Y3xQI4mIJ1lSf4+vijWKDobrty8OopDeBxY+NABe0MRFidF3dCUoWjRt8" + + "SVMvBZPI3zkOgcRs7Mz3yazd7f7c58HwW5Xg9jdBjNg;"); return List.of( jsonMapResponse("youChatToken", "Hel"), jsonMapResponse("youChatToken", "lo"), diff --git a/src/test/java/ee/carlrobert/codegpt/completions/PromptTemplateTest.java b/src/test/java/ee/carlrobert/codegpt/completions/PromptTemplateTest.java index 3f1edbe4..ae022167 100644 --- a/src/test/java/ee/carlrobert/codegpt/completions/PromptTemplateTest.java +++ b/src/test/java/ee/carlrobert/codegpt/completions/PromptTemplateTest.java @@ -45,7 +45,8 @@ public class PromptTemplateTest { var prompt = ALPACA.buildPrompt(SYSTEM_PROMPT, USER_PROMPT, HISTORY); assertThat(prompt).isEqualTo( - "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n" + "Below is an instruction that describes a task. " + + "Write a response that appropriately completes the request.\n" + "\n" + "### Instruction\n" + "TEST_PREV_PROMPT_1\n" @@ -70,7 +71,8 @@ public class PromptTemplateTest { var prompt = ALPACA.buildPrompt(SYSTEM_PROMPT, USER_PROMPT, List.of()); assertThat(prompt).isEqualTo( - "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n" + "Below is an instruction that describes a task. " + + "Write a response that appropriately completes the request.\n" + "\n" + "### Instruction\n" + "TEST_USER_PROMPT\n" diff --git a/src/test/java/ee/carlrobert/codegpt/settings/state/SettingsStateTest.java b/src/test/java/ee/carlrobert/codegpt/settings/state/SettingsStateTest.java index ae9bffcc..df84e5ec 100644 --- a/src/test/java/ee/carlrobert/codegpt/settings/state/SettingsStateTest.java +++ b/src/test/java/ee/carlrobert/codegpt/settings/state/SettingsStateTest.java @@ -11,12 +11,12 @@ import ee.carlrobert.codegpt.settings.service.ServiceType; public class SettingsStateTest extends BasePlatformTestCase { public void testOpenAISettingsSync() { - var settings = SettingsState.getInstance(); var openAISettings = OpenAISettingsState.getInstance(); openAISettings.setModel("gpt-3.5-turbo"); var conversation = new Conversation(); conversation.setModel("gpt-4"); conversation.setClientCode("chat.completion"); + var settings = SettingsState.getInstance(); settings.sync(conversation); @@ -47,12 +47,12 @@ public class SettingsStateTest extends BasePlatformTestCase { } public void testLlamaSettingsModelPathSync() { - var settings = SettingsState.getInstance(); var llamaSettings = LlamaSettingsState.getInstance(); llamaSettings.setHuggingFaceModel(HuggingFaceModel.WIZARD_CODER_PYTHON_7B_Q3); var conversation = new Conversation(); conversation.setModel("TEST_LLAMA_MODEL_PATH"); conversation.setClientCode("llama.chat.completion"); + var settings = SettingsState.getInstance(); settings.sync(conversation); @@ -62,12 +62,12 @@ public class SettingsStateTest extends BasePlatformTestCase { } public void testLlamaSettingsHuggingFaceModelSync() { - var settings = SettingsState.getInstance(); var llamaSettings = LlamaSettingsState.getInstance(); llamaSettings.setHuggingFaceModel(HuggingFaceModel.WIZARD_CODER_PYTHON_7B_Q3); var conversation = new Conversation(); conversation.setModel("CODE_LLAMA_7B_Q3"); conversation.setClientCode("llama.chat.completion"); + var settings = SettingsState.getInstance(); settings.sync(conversation); diff --git a/src/test/java/ee/carlrobert/codegpt/util/MarkdownUtilsTest.java b/src/test/java/ee/carlrobert/codegpt/util/MarkdownUtilsTest.java index a171c86b..626da194 100644 --- a/src/test/java/ee/carlrobert/codegpt/util/MarkdownUtilsTest.java +++ b/src/test/java/ee/carlrobert/codegpt/util/MarkdownUtilsTest.java @@ -8,99 +8,99 @@ public class MarkdownUtilsTest { @Test public void shouldExtractMarkdownCodeBlocks() { - String testInput = "**C++ Code Block**\n" + - "```cpp\n" + - "#include \n" + - "\n" + - "int main() {\n" + - " return 0;\n" + - "}\n" + - "```\n" + - "1. We include the **iostream** header file.\n" + - "2. We define the main function.\n" + - "\n" + - "**Java Code Block**\n" + - "```java\n" + - "public class Main {\n" + - " public static void main(String[] args) {\n" + - " }\n" + - "}\n" + - "```\n" + - "1. We define a **public class** called **Main**.\n" + - "2. We define the **main** method which is the entry point of the program.\n"; + String testInput = "**C++ Code Block**\n" + + "```cpp\n" + + "#include \n" + + "\n" + + "int main() {\n" + + " return 0;\n" + + "}\n" + + "```\n" + + "1. We include the **iostream** header file.\n" + + "2. We define the main function.\n" + + "\n" + + "**Java Code Block**\n" + + "```java\n" + + "public class Main {\n" + + " public static void main(String[] args) {\n" + + " }\n" + + "}\n" + + "```\n" + + "1. We define a **public class** called **Main**.\n" + + "2. We define the **main** method which is the entry point of the program.\n"; var result = MarkdownUtils.splitCodeBlocks(testInput); assertThat(result).containsExactly( "**C++ Code Block**\n", - "```cpp\n" + - "#include \n" + - "\n" + - "int main() {\n" + - " return 0;\n" + - "}\n" + - "```", - "\n1. We include the **iostream** header file.\n" + - "2. We define the main function.\n" + - "\n" + - "**Java Code Block**\n", - "```java\n" + - "public class Main {\n" + - " public static void main(String[] args) {\n" + - " }\n" + - "}\n" + - "```", - "\n1. We define a **public class** called **Main**.\n" + - "2. We define the **main** method which is the entry point of the program.\n"); + "```cpp\n" + + "#include \n" + + "\n" + + "int main() {\n" + + " return 0;\n" + + "}\n" + + "```", + "\n1. We include the **iostream** header file.\n" + + "2. We define the main function.\n" + + "\n" + + "**Java Code Block**\n", + "```java\n" + + "public class Main {\n" + + " public static void main(String[] args) {\n" + + " }\n" + + "}\n" + + "```", + "\n1. We define a **public class** called **Main**.\n" + + "2. We define the **main** method which is the entry point of the program.\n"); } @Test public void shouldExtractMarkdownWithoutCode() { - String testInput = "**C++ Code Block**\n" + - "1. We include the **iostream** header file.\n" + - "2. We define the main function.\n" + - "\n"; + String testInput = "**C++ Code Block**\n" + + "1. We include the **iostream** header file.\n" + + "2. We define the main function.\n" + + "\n"; var result = MarkdownUtils.splitCodeBlocks(testInput); assertThat(result).containsExactly( - "**C++ Code Block**\n" + - "1. We include the **iostream** header file.\n" + - "2. We define the main function.\n" + - "\n"); + "**C++ Code Block**\n" + + "1. We include the **iostream** header file.\n" + + "2. We define the main function.\n" + + "\n"); } @Test public void shouldExtractMarkdownCodeOnly() { - String testInput = "```cpp\n" + - "#include \n" + - "\n" + - "int main() {\n" + - " return 0;\n" + - "}\n" + - "```\n" + - "```java\n" + - "public class Main {\n" + - " public static void main(String[] args) {\n" + - " }\n" + - "}\n" + - "```\n"; + String testInput = "```cpp\n" + + "#include \n" + + "\n" + + "int main() {\n" + + " return 0;\n" + + "}\n" + + "```\n" + + "```java\n" + + "public class Main {\n" + + " public static void main(String[] args) {\n" + + " }\n" + + "}\n" + + "```\n"; var result = MarkdownUtils.splitCodeBlocks(testInput); assertThat(result).containsExactly( - "```cpp\n" + - "#include \n" + - "\n" + - "int main() {\n" + - " return 0;\n" + - "}\n" + - "```", - "```java\n" + - "public class Main {\n" + - " public static void main(String[] args) {\n" + - " }\n" + - "}\n" + - "```"); + "```cpp\n" + + "#include \n" + + "\n" + + "int main() {\n" + + " return 0;\n" + + "}\n" + + "```", + "```java\n" + + "public class Main {\n" + + " public static void main(String[] args) {\n" + + " }\n" + + "}\n" + + "```"); } }