From 1f602e53c29eb28d98754252823ad8f40f839d1b Mon Sep 17 00:00:00 2001 From: Big Boss Date: Fri, 29 Nov 2024 15:58:01 -0600 Subject: [PATCH 01/19] fix: intellij freezing Reverts useIsOSREnabled to use the single use event listener instead of subscribing to `useWebviewListener` --- core/protocol/ideWebview.ts | 2 +- .../toolWindow/ContinueBrowser.kt | 6 ++++-- gui/src/hooks/useIsOSREnabled.ts | 16 ++++++++++------ 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 91fa40395..bf5866cca 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -43,7 +43,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { insertAtCursor: [{ text: string }, void]; copyText: [{ text: string }, void]; "jetbrains/editorInsetHeight": [{ height: number }, void]; - "jetbrains/isOSREnabled": [undefined, void]; + "jetbrains/isOSREnabled": [undefined, boolean]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; acceptDiff: [{ filepath: string; streamId?: string }, void]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 659ec4998..b2350759c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -137,7 +137,7 @@ class ContinueBrowser(val project: Project, url: String) { } "jetbrains/isOSREnabled" -> { - sendToWebview( "jetbrains/isOSREnabled", isOSREnabled) + respond(isOSREnabled) } "onLoad" -> { @@ -267,7 +267,9 @@ class ContinueBrowser(val project: Project, url: String) { val jsCode = buildJavaScript(jsonData) try { - this.browser.executeJavaScriptAsync(jsCode) + this.browser.executeJavaScriptAsync(jsCode).onError { + println("Failed to execute jsCode error: ${it.message}") + } } catch (error: IllegalStateException) { println("Webview not initialized yet $error") } diff --git a/gui/src/hooks/useIsOSREnabled.ts b/gui/src/hooks/useIsOSREnabled.ts index 10ad04756..8ceca9cbf 100644 --- a/gui/src/hooks/useIsOSREnabled.ts +++ b/gui/src/hooks/useIsOSREnabled.ts @@ -7,15 +7,19 @@ export default function useIsOSREnabled() { const [isOSREnabled, setIsOSREnabled] = useState(false); const ideMessenger = useContext(IdeMessengerContext); - useWebviewListener("jetbrains/isOSREnabled", async (isOSREnabled) => { - setIsOSREnabled(isOSREnabled); - }); - useEffect(() => { if (isJetBrains()) { - ideMessenger.post("jetbrains/isOSREnabled", undefined); + (async () => { + await ideMessenger + .request("jetbrains/isOSREnabled", undefined) + .then((result) => { + if (result.status === "success") { + setIsOSREnabled(result.content); + } + }); + })(); } - }, []); + }, [ideMessenger]); return isOSREnabled; } From 858d3d8a052e25ae525046a04a97fc0355144285 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 3 Dec 2024 21:56:06 -0800 Subject: [PATCH 02/19] fix lag on new sesssion --- gui/src/hooks/useHistory.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 415e8bffc..cedf9210d 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -4,9 +4,9 @@ import { renderChatMessage } from "core/util/messageContent"; import { useCallback, useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; +import { useAppSelector } from "../redux/hooks"; import { newSession, updateSessionTitle } from "../redux/slices/sessionSlice"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { useAppSelector } from "../redux/hooks"; const MAX_TITLE_LENGTH = 100; @@ -52,6 +52,11 @@ function useHistory(dispatch: Dispatch) { async function saveSession(openNewSession: boolean = true) { if (history.length === 0) return; + if (openNewSession) { + dispatch(newSession()); + updateLastSessionId(sessionId); + } + let currentTitle = title; if (config?.ui?.getChatTitles && currentTitle === "New Session") { try { @@ -91,10 +96,7 @@ function useHistory(dispatch: Dispatch) { await ideMessenger.request("history/save", session); - if (openNewSession) { - dispatch(newSession()); - updateLastSessionId(sessionId); - } else { + if (!openNewSession) { dispatch(updateSessionTitle(newTitle)); } } From 6c2cb6490a6b83e8e2f55571c7267f2ec334938d Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 3 Dec 2024 22:21:03 -0800 Subject: [PATCH 03/19] Don't show debug logs on window open --- extensions/vscode/src/ContinueGUIWebviewViewProvider.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts index 610d262fc..f98b09f93 100644 --- a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts @@ -22,9 +22,7 @@ export class ContinueGUIWebviewViewProvider private updateDebugLogsStatus() { const settings = vscode.workspace.getConfiguration(EXTENSION_NAME); this.enableDebugLogs = settings.get("enableDebugLogs", false); - if (this.enableDebugLogs) { - this.outputChannel.show(true); - } else { + if (!this.enableDebugLogs) { this.outputChannel.hide(); } } @@ -35,9 +33,7 @@ export class ContinueGUIWebviewViewProvider if (event.affectsConfiguration("continue.enableDebugLogs")) { const settings = vscode.workspace.getConfiguration(EXTENSION_NAME); const enableDebugLogs = settings.get("enableDebugLogs", false); - if (enableDebugLogs) { - this.outputChannel.show(true); - } else { + if (!enableDebugLogs) { this.outputChannel.hide(); } } From 93989459e3806f1ba6d647036dc9db064bf30e38 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 4 Dec 2024 09:51:59 -0800 Subject: [PATCH 04/19] fix: use index when sending chat input --- gui/src/pages/gui/Chat.tsx | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 000a06f12..258a92013 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -228,7 +228,12 @@ export function Chat() { const { widget, highlights } = useFindWidget(stepsDivRef); const sendInput = useCallback( - (editorState: JSONContent, modifiers: InputModifiers, editor: Editor) => { + ( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + index?: number, + ) => { if (defaultModel?.provider === "free-trial") { const u = getLocalStorage("ftc"); if (u) { @@ -259,7 +264,9 @@ export function Chat() { ? getMultifileEditPrompt(codeToEdit) : undefined; - dispatch(streamResponseThunk({ editorState, modifiers, promptPreamble })); + dispatch( + streamResponseThunk({ editorState, modifiers, promptPreamble, index }), + ); // Increment localstorage counter for popup const currentCount = getLocalStorage("mainTextEntryCounter"); @@ -355,7 +362,9 @@ export function Chat() { <> {isInEditMode && index === 0 && } + sendInput(editorState, modifiers, editor, index) + } isLastUserInput={isLastUserInput(index)} isMainInput={false} editorState={item.editorState} From a5d69f35faef0803a4deb5fb862a7a9b13939ef8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 4 Dec 2024 11:54:38 -0800 Subject: [PATCH 05/19] core test utils p1 --- .continue/prompts/core-util-test.prompt | 8 ++- core/jest.config.js | 5 +- core/package.json | 2 +- core/util/withExponentialBackoff.test.ts | 76 ++++++++++++++++++++++++ core/util/withExponentialBackoff.ts | 10 +++- 5 files changed, 93 insertions(+), 8 deletions(-) create mode 100644 core/util/withExponentialBackoff.test.ts diff --git a/.continue/prompts/core-util-test.prompt b/.continue/prompts/core-util-test.prompt index 19202ddee..3985432dc 100644 --- a/.continue/prompts/core-util-test.prompt +++ b/.continue/prompts/core-util-test.prompt @@ -1,7 +1,11 @@ name: Write Core Utility Test description: Generate unit tests for core utilities --- -Write jest tests for the provided code. Use best practices. Be clear and consise. +Write jest tests for the provided code. +Use jest version ^29 (e.g. jest 29.7.0) + +Do NOT write tests for core/test/util/fixtures.ts` or `core/gui/src/components/mainInput/types.d.ts`, only use them as helpers for testing other files. +Use best practices. Be clear and consise. Aim for 100% code coverage where reasonable. Multiple tests can be written, split up tests for best clarity and readability. Only use typescript, and if the file/code is not typescript, warn the user. @@ -18,4 +22,4 @@ Existing test fixtures can be found in: - import and use `ideSettingsPromise` for any IdeSettings needs // This note is for if using edit mode to encourage it to create new files -The tests are to be put in a new file with the same filepath but with a .test.ts extension rather than a .ts extension \ No newline at end of file +The tests are to be put in a new file with the same filepath but with a .test.ts extension rather than a .ts extension diff --git a/core/jest.config.js b/core/jest.config.js index b92d03e5e..f97054326 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -8,8 +8,8 @@ export default { moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", "^uuid$": "uuid", // https://stackoverflow.com/a/73626360 - '^@azure/(.*)$': '/node_modules/@azure/$1', - '^mssql$': '/node_modules/mssql' + "^@azure/(.*)$": "/node_modules/@azure/$1", + "^mssql$": "/node_modules/mssql", }, extensionsToTreatAsEsm: [".ts"], preset: "ts-jest/presets/default-esm", @@ -21,4 +21,5 @@ export default { }, globalSetup: "/jest.global-setup.ts", setupFilesAfterEnv: ["/jest.setup-after-env.ts"], + maxWorkers: 1 // equivalent to CLI --runInBand }; diff --git a/core/package.json b/core/package.json index 78d7ecf65..366b4bd9e 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,7 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", "tsc:check": "tsc -p ./ --noEmit", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", diff --git a/core/util/withExponentialBackoff.test.ts b/core/util/withExponentialBackoff.test.ts new file mode 100644 index 000000000..cfea914ed --- /dev/null +++ b/core/util/withExponentialBackoff.test.ts @@ -0,0 +1,76 @@ +// core/util/withExponentialBackoff.test.ts + +import { + withExponentialBackoff, + RETRY_AFTER_HEADER, +} from "./withExponentialBackoff"; + +// Helper function to simulate delay +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +describe("withExponentialBackoff", () => { + it("should return result immediately if apiCall is successful", async () => { + const mockApiCall = jest.fn().mockResolvedValue("success"); + + const result = await withExponentialBackoff(mockApiCall); + expect(result).toBe("success"); + expect(mockApiCall).toHaveBeenCalledTimes(1); + }); + + it("should retry on API error 429 and eventually succeed", async () => { + // Mock an API function that returns HTTP 429 twice then succeeds + const mockApiCall = jest + .fn() + .mockRejectedValueOnce({ + response: { status: 429, headers: new Map() }, + }) + .mockRejectedValueOnce({ + response: { status: 429, headers: new Map() }, + }) + .mockResolvedValue("success"); + + const result = await withExponentialBackoff(mockApiCall, 3, 0.001); // Use a short delay for testing + expect(result).toBe("success"); + expect(mockApiCall).toHaveBeenCalledTimes(3); + }); + + it("should respect Retry-After header value for delay", async () => { + const mockApiCall = jest + .fn() + .mockRejectedValueOnce({ + response: { + status: 429, + headers: new Map([[RETRY_AFTER_HEADER, "1"]]), + }, + }) + .mockResolvedValue("success"); + + const startTime = Date.now(); + const result = await withExponentialBackoff(mockApiCall, 2, 1); + const endTime = Date.now(); + + expect(result).toBe("success"); + expect(endTime - startTime).toBeGreaterThanOrEqual(1000); // At least 1 second delay + expect(mockApiCall).toHaveBeenCalledTimes(2); + }); + + it("should throw error after maxRetries are exhausted", async () => { + const mockApiCall = jest.fn().mockRejectedValue(new Error("Network Error")); + + await expect(withExponentialBackoff(mockApiCall, 3, 0.001)).rejects.toThrow( + "Network Error", + ); + expect(mockApiCall).toHaveBeenCalledTimes(3); + }); + + it("should throw the error immediately if it is not rate limit reached error", async () => { + const mockApiCall = jest + .fn() + .mockRejectedValue(new Error("Unexpected Error")); + + await expect(withExponentialBackoff(mockApiCall, 3, 0.001)).rejects.toThrow( + "Unexpected Error", + ); + expect(mockApiCall).toHaveBeenCalledTimes(1); + }); +}); diff --git a/core/util/withExponentialBackoff.ts b/core/util/withExponentialBackoff.ts index efe9d95c1..84b301b26 100644 --- a/core/util/withExponentialBackoff.ts +++ b/core/util/withExponentialBackoff.ts @@ -2,7 +2,7 @@ interface APIError extends Error { response?: Response; } -const RETRY_AFTER_HEADER = "Retry-After"; +export const RETRY_AFTER_HEADER = "Retry-After"; const withExponentialBackoff = async ( apiCall: () => Promise, @@ -18,8 +18,12 @@ const withExponentialBackoff = async ( (error as APIError).response?.status === 429 && attempt < maxRetries - 1 ) { - const retryAfter = (error as APIError).response?.headers.get(RETRY_AFTER_HEADER); - const delay = retryAfter ? parseInt(retryAfter, 10) : initialDelaySeconds * 2 ** attempt; + const retryAfter = (error as APIError).response?.headers.get( + RETRY_AFTER_HEADER, + ); + const delay = retryAfter + ? parseInt(retryAfter, 10) + : initialDelaySeconds * 2 ** attempt; console.log( `Hit rate limit. Retrying in ${delay} seconds (attempt ${ attempt + 1 From ea6d09389a86ef02f0ba3edff4f8d302ab057195 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 4 Dec 2024 13:46:04 -0800 Subject: [PATCH 06/19] jest utils p2 --- core/jest.config.js | 1 + core/jest.setup-after-env.ts | 2 + core/package-lock.json | 8 +-- core/package.json | 2 +- core/util/withExponentialBackoff.test.ts | 89 +++++++++++------------- extensions/vscode/package-lock.json | 2 +- gui/package-lock.json | 2 +- 7 files changed, 52 insertions(+), 54 deletions(-) diff --git a/core/jest.config.js b/core/jest.config.js index f97054326..d58b0b510 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -19,6 +19,7 @@ export default { __dirname: path.dirname(fileURLToPath(import.meta.url)), __filename: path.resolve(fileURLToPath(import.meta.url)), }, + globalSetup: "/jest.global-setup.ts", setupFilesAfterEnv: ["/jest.setup-after-env.ts"], maxWorkers: 1 // equivalent to CLI --runInBand diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index b5fbacc11..d92f171dd 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -1,4 +1,5 @@ // https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 + import { TextDecoder, TextEncoder } from "util"; import { jest } from "@jest/globals"; @@ -10,6 +11,7 @@ if (process.env.DEBUG === "jest") { const globalThis = global as any; +globalThis.jest = jest; globalThis.fetch = fetch; globalThis.Request = Request; globalThis.Response = Response; diff --git a/core/package-lock.json b/core/package-lock.json index 58762590f..3a3f77c43 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -27,7 +27,7 @@ "comment-json": "^4.2.3", "dbinfoz": "^0.14.0", "diff": "^7.0.0", - "dotenv": "^16.4.5", + "dotenv": "^16.4.7", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", @@ -7882,9 +7882,9 @@ } }, "node_modules/dotenv": { - "version": "16.4.5", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", - "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", "engines": { "node": ">=12" }, diff --git a/core/package.json b/core/package.json index 366b4bd9e..8aa6f9f9c 100644 --- a/core/package.json +++ b/core/package.json @@ -58,7 +58,7 @@ "comment-json": "^4.2.3", "dbinfoz": "^0.14.0", "diff": "^7.0.0", - "dotenv": "^16.4.5", + "dotenv": "^16.4.7", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", diff --git a/core/util/withExponentialBackoff.test.ts b/core/util/withExponentialBackoff.test.ts index cfea914ed..55bdb6184 100644 --- a/core/util/withExponentialBackoff.test.ts +++ b/core/util/withExponentialBackoff.test.ts @@ -1,41 +1,35 @@ -// core/util/withExponentialBackoff.test.ts - import { withExponentialBackoff, RETRY_AFTER_HEADER, } from "./withExponentialBackoff"; - -// Helper function to simulate delay -const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const MAX_RETRIES = 4; +const INITIAL_DELAY_SECONDS = 0.01; describe("withExponentialBackoff", () => { - it("should return result immediately if apiCall is successful", async () => { - const mockApiCall = jest.fn().mockResolvedValue("success"); + // beforeEach(() => { + // jest.useFakeTimers(); + // jest.clearAllMocks(); + // }); + + // afterEach(() => { + // jest.useRealTimers(); + // }); + + it("should return result on first successful API call", async () => { + const apiCall = jest.fn().mockResolvedValue("success"); + + const result = await withExponentialBackoff( + apiCall, + MAX_RETRIES, + INITIAL_DELAY_SECONDS, + ); - const result = await withExponentialBackoff(mockApiCall); expect(result).toBe("success"); - expect(mockApiCall).toHaveBeenCalledTimes(1); + expect(apiCall).toHaveBeenCalledTimes(1); }); - it("should retry on API error 429 and eventually succeed", async () => { - // Mock an API function that returns HTTP 429 twice then succeeds - const mockApiCall = jest - .fn() - .mockRejectedValueOnce({ - response: { status: 429, headers: new Map() }, - }) - .mockRejectedValueOnce({ - response: { status: 429, headers: new Map() }, - }) - .mockResolvedValue("success"); - - const result = await withExponentialBackoff(mockApiCall, 3, 0.001); // Use a short delay for testing - expect(result).toBe("success"); - expect(mockApiCall).toHaveBeenCalledTimes(3); - }); - - it("should respect Retry-After header value for delay", async () => { - const mockApiCall = jest + it("should retry on API rate limit and succeed", async () => { + const apiCall = jest .fn() .mockRejectedValueOnce({ response: { @@ -45,32 +39,33 @@ describe("withExponentialBackoff", () => { }) .mockResolvedValue("success"); - const startTime = Date.now(); - const result = await withExponentialBackoff(mockApiCall, 2, 1); - const endTime = Date.now(); + const result = await withExponentialBackoff( + apiCall, + MAX_RETRIES, + INITIAL_DELAY_SECONDS, + ); expect(result).toBe("success"); - expect(endTime - startTime).toBeGreaterThanOrEqual(1000); // At least 1 second delay - expect(mockApiCall).toHaveBeenCalledTimes(2); + expect(apiCall).toHaveBeenCalledTimes(2); }); - it("should throw error after maxRetries are exhausted", async () => { - const mockApiCall = jest.fn().mockRejectedValue(new Error("Network Error")); + it("should stop retrying after maxRetries and throw error", async () => { + const apiCall = jest.fn().mockRejectedValue({ + response: { status: 429, headers: new Map([[RETRY_AFTER_HEADER, "1"]]) }, + }); - await expect(withExponentialBackoff(mockApiCall, 3, 0.001)).rejects.toThrow( - "Network Error", - ); - expect(mockApiCall).toHaveBeenCalledTimes(3); + await expect( + withExponentialBackoff(apiCall, MAX_RETRIES, INITIAL_DELAY_SECONDS), + ).rejects.toThrow("Failed to make API call after multiple retries"); + expect(apiCall).toHaveBeenCalledTimes(MAX_RETRIES); }); - it("should throw the error immediately if it is not rate limit reached error", async () => { - const mockApiCall = jest - .fn() - .mockRejectedValue(new Error("Unexpected Error")); + it("should throw on non-rate limit errors", async () => { + const apiCall = jest.fn().mockRejectedValue(new Error("Server Error")); - await expect(withExponentialBackoff(mockApiCall, 3, 0.001)).rejects.toThrow( - "Unexpected Error", - ); - expect(mockApiCall).toHaveBeenCalledTimes(1); + await expect( + withExponentialBackoff(apiCall, MAX_RETRIES, INITIAL_DELAY_SECONDS), + ).rejects.toThrow("Server Error"); + expect(apiCall).toHaveBeenCalledTimes(1); }); }); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 9ac0c6f53..20f94f30a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -112,7 +112,7 @@ "comment-json": "^4.2.3", "dbinfoz": "^0.14.0", "diff": "^7.0.0", - "dotenv": "^16.4.5", + "dotenv": "^16.4.7", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", diff --git a/gui/package-lock.json b/gui/package-lock.json index 91410e6df..af3d5cafa 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -121,7 +121,7 @@ "comment-json": "^4.2.3", "dbinfoz": "^0.14.0", "diff": "^7.0.0", - "dotenv": "^16.4.5", + "dotenv": "^16.4.7", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", From a632c43beafd16750115575d22a782f131dcf446 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 4 Dec 2024 13:53:39 -0800 Subject: [PATCH 07/19] bugfix: prevent edit submission w/o code to edit --- .../CodeToEditCard/CodeToEditCard.tsx | 12 +++++++-- gui/src/components/mainInput/InputToolbar.tsx | 27 ++++++++++++++----- gui/src/components/mainInput/TipTapEditor.tsx | 6 +++-- gui/src/redux/slices/sessionSlice.ts | 4 +++ 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 3f4ef372d..04c55e8cc 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -5,7 +5,7 @@ import CodeToEditListItem from "./CodeToEditListItem"; import type { CodeToEdit, RangeInFileWithContents } from "core"; import AddFileButton from "./AddFileButton"; import AddFileCombobox from "./AddFileCombobox"; -import { XMarkIcon } from "@heroicons/react/24/outline"; +import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { addCodeToEdit, @@ -61,7 +61,7 @@ export default function CodeToEditCard() { setShowAddFileCombobox(true)} /> - {codeToEdit.length > 0 && ( + {codeToEdit.length > 0 ? (
    {codeToEdit.map((code, i) => ( ))}
+ ) : ( +
setShowAddFileCombobox(true)} + > + + Add a file to get started +
)} {showAddFileCombobox && ( diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index a7591b84c..80867e710 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -20,8 +20,13 @@ import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; import HoverItem from "./InputToolbar/HoverItem"; import ToggleToolsButton from "./InputToolbar/ToggleToolsButton"; -import { useAppSelector } from "../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { + selectHasCodeToEdit, + selectIsInEditMode, +} from "../../redux/slices/sessionSlice"; +import { exitEditMode } from "../../redux/thunks"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -76,9 +81,15 @@ interface InputToolbarProps { } function InputToolbar(props: InputToolbarProps) { + const dispatch = useAppDispatch(); const fileInputRef = useRef(null); const defaultModel = useAppSelector(selectDefaultModel); const useActiveFile = useAppSelector(selectUseActiveFile); + const isInEditMode = useAppSelector(selectIsInEditMode); + const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); + + const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; const supportsImages = defaultModel && @@ -172,13 +183,15 @@ function InputToolbar(props: InputToolbarProps) { )} { - props.onEnter({ - useCodebase: isMetaEquivalentKeyPressed(e as any), - noContext: useActiveFile ? e.altKey : !e.altKey, - }); + onClick={async (e) => { + if (props.onEnter) { + props.onEnter({ + useCodebase: isMetaEquivalentKeyPressed(e as any), + noContext: useActiveFile ? e.altKey : !e.altKey, + }); + } }} - disabled={props.disabled} + disabled={isEnterDisabled} > ⏎ {props.toolbarOptions?.enterText ?? "Enter"} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 7621ca76c..bf6a65b85 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -68,6 +68,7 @@ import { selectDefaultModel } from "../../redux/slices/configSlice"; import { addCodeToEdit, clearCodeToEdit, + selectHasCodeToEdit, selectIsInEditMode, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; @@ -253,6 +254,8 @@ function TipTapEditor(props: TipTapEditorProps) { const isInEditMode = useAppSelector(selectIsInEditMode); const isInEditModeRef = useUpdatingRef(isInEditMode); + const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); + const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; async function handleImageFile( file: File, @@ -489,7 +492,6 @@ function TipTapEditor(props: TipTapEditorProps) { ), allow: () => isInEditModeRef.current, command: async ({ editor, range, props }) => { - console.log({ range }); editor.chain().focus().insertContentAt(range, "").run(); const filepath = props.id; const contents = await ideMessenger.ide.readFile(filepath); @@ -630,7 +632,7 @@ function TipTapEditor(props: TipTapEditorProps) { const onEnterRef = useUpdatingRef( (modifiers: InputModifiers) => { - if (isStreaming) { + if (isStreaming || isEditModeAndNoCodeToEdit) { return; } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index d3d4f0da4..46e9e21f5 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -526,6 +526,9 @@ export const sessionSlice = createSlice({ return selectIsSingleRangeEdit || isInsertion; }, + selectHasCodeToEdit: (state) => { + return state.codeToEdit.length > 0; + }, }, extraReducers: (builder) => { addPassthroughCases(builder, [streamResponseThunk]); @@ -599,6 +602,7 @@ export const { selectIsGatheringContext, selectIsInEditMode, selectIsSingleRangeEditOrInsertion, + selectHasCodeToEdit, } = sessionSlice.selectors; export default sessionSlice.reducer; From 3622c50f2c15e01936b02f15a3fc47d4ae9b4a23 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 4 Dec 2024 14:13:21 -0800 Subject: [PATCH 08/19] exponential backoff test iteration --- core/util/withExponentialBackoff.test.ts | 34 +++++++++++------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/core/util/withExponentialBackoff.test.ts b/core/util/withExponentialBackoff.test.ts index 55bdb6184..07298dfe7 100644 --- a/core/util/withExponentialBackoff.test.ts +++ b/core/util/withExponentialBackoff.test.ts @@ -3,7 +3,7 @@ import { RETRY_AFTER_HEADER, } from "./withExponentialBackoff"; const MAX_RETRIES = 4; -const INITIAL_DELAY_SECONDS = 0.01; +const INITIAL_DELAY = 0.01; // so the tests run fast describe("withExponentialBackoff", () => { // beforeEach(() => { @@ -18,16 +18,11 @@ describe("withExponentialBackoff", () => { it("should return result on first successful API call", async () => { const apiCall = jest.fn().mockResolvedValue("success"); - const result = await withExponentialBackoff( - apiCall, - MAX_RETRIES, - INITIAL_DELAY_SECONDS, - ); + const result = await withExponentialBackoff(apiCall, MAX_RETRIES); expect(result).toBe("success"); expect(apiCall).toHaveBeenCalledTimes(1); }); - it("should retry on API rate limit and succeed", async () => { const apiCall = jest .fn() @@ -39,23 +34,26 @@ describe("withExponentialBackoff", () => { }) .mockResolvedValue("success"); - const result = await withExponentialBackoff( - apiCall, - MAX_RETRIES, - INITIAL_DELAY_SECONDS, - ); + const start = Date.now(); + + const result = await withExponentialBackoff(apiCall, MAX_RETRIES); + + const duration = (Date.now() - start) / 1000; expect(result).toBe("success"); expect(apiCall).toHaveBeenCalledTimes(2); + expect(duration).toBeGreaterThanOrEqual(1); }); - it("should stop retrying after maxRetries and throw error", async () => { const apiCall = jest.fn().mockRejectedValue({ - response: { status: 429, headers: new Map([[RETRY_AFTER_HEADER, "1"]]) }, + response: { + status: 429, + headers: new Map(), + }, }); await expect( - withExponentialBackoff(apiCall, MAX_RETRIES, INITIAL_DELAY_SECONDS), + withExponentialBackoff(apiCall, MAX_RETRIES, INITIAL_DELAY), ).rejects.toThrow("Failed to make API call after multiple retries"); expect(apiCall).toHaveBeenCalledTimes(MAX_RETRIES); }); @@ -63,9 +61,9 @@ describe("withExponentialBackoff", () => { it("should throw on non-rate limit errors", async () => { const apiCall = jest.fn().mockRejectedValue(new Error("Server Error")); - await expect( - withExponentialBackoff(apiCall, MAX_RETRIES, INITIAL_DELAY_SECONDS), - ).rejects.toThrow("Server Error"); + await expect(withExponentialBackoff(apiCall, MAX_RETRIES)).rejects.toThrow( + "Server Error", + ); expect(apiCall).toHaveBeenCalledTimes(1); }); }); From 5f0abda3956e6367369d2b94e175f47c3848b1d6 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 4 Dec 2024 14:59:29 -0800 Subject: [PATCH 09/19] bugfix: prevent overflow of btns on small screens --- gui/src/components/mainInput/InputToolbar.tsx | 17 +++++++++++------ .../InputToolbar/ToggleToolsButton.tsx | 6 ------ 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 80867e710..730de2896 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,6 +1,6 @@ import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; -import { modelSupportsImages } from "core/llm/autodetect"; +import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; import { useRef } from "react"; import styled from "styled-components"; import { @@ -54,6 +54,7 @@ const EnterButton = styled.button` border-radius: ${defaultBorderRadius}; color: ${vscForeground}; cursor: pointer; + :disabled { cursor: wait; } @@ -81,15 +82,17 @@ interface InputToolbarProps { } function InputToolbar(props: InputToolbarProps) { - const dispatch = useAppDispatch(); const fileInputRef = useRef(null); const defaultModel = useAppSelector(selectDefaultModel); const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); - const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; + const shouldRenderToolsButton = + defaultModel && + modelSupportsTools(defaultModel.model) && + !props.toolbarOptions?.hideTools; const supportsImages = defaultModel && @@ -110,7 +113,7 @@ function InputToolbar(props: InputToolbarProps) { >
-
+
{props.toolbarOptions?.hideImageUpload || (supportsImages && ( <> @@ -149,13 +152,15 @@ function InputToolbar(props: InputToolbarProps) { )} - {props.toolbarOptions?.hideTools || } + {shouldRenderToolsButton && }
{props.toolbarOptions?.hideUseCodebase || ( -
+